问题
I would like to replace all spaces at the start of the line with tabs. The below snippet works, but only for the first indentation level.
How do I make it work for 1 to ∞ indentation levels? So that it replaces 12 spaces with 3 tabs (assuming a tabstop
of 4)?
fun! Retab()
let l:spaces = repeat(' ', &tabstop)
silent! execute '%s/^' . l:spaces . '/\t/g'
endfun
Note that using :retab
doesn't seem to be an option here, since :retab
doesn't just change indentation, but also changes all repeat(' ', &tabstop)
occurrences everywhere in the file.
Re-indenting the file (with =
) is also not an option, since Vim & I sometimes have different opinions on what should be indented at which level (ie. it has too many side-effects).
I also thought about using the expand
& unexpand
programs, but I would prefer not to rely on external utilities.
回答1:
Your attempt goes into the right direction, but you need :help sub-replace-expr
to count the number of matched spaces and convert this into a corresponding number of tab characters:
silent! execute '%substitute#^\%(' . l:spaces . '\)\+#\=repeat("\t", len(submatch(0)) / &tabstop)#e'
To do the reverse (replaces tabs to spaces), you can do:
silent! execute '%substitute#^\%(\t\)\+#\=repeat("' . l:spaces . '", len(submatch(0)))#e'
来源:https://stackoverflow.com/questions/27547756/replace-all-spaces-at-the-start-of-the-line-with-tabs