用制表符替换行开头的所有空格 [英] Replace all spaces at the start of the line with tabs
问题描述
我想用制表符替换行首的所有空格.以下代码段有效,但仅适用于第一个缩进级别.
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.
我如何使其适用于 1到∞的缩进级别?以便用3个制表符替换12个空格(假设tabstop
为4)?
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
请注意,在这里似乎不是使用:retab
的选项,因为:retab
不仅会更改缩进,而且还会更改文件中所有repeat(' ', &tabstop)
出现的位置 .
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.
也不能选择使用=
重新缩进文件,因为Vim&有时候我对应该缩进哪个级别有不同的看法(即,它有太多的副作用).
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).
我还考虑过使用expand
& unexpand
程序,但我希望不要依赖外部实用程序.
I also thought about using the expand
& unexpand
programs, but I would prefer not to rely on external utilities.
推荐答案
您的尝试朝着正确的方向前进,但是您需要:help sub-replace-expr
来计算匹配空格的数量并将其转换为相应数量的制表符: /p>
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'
这篇关于用制表符替换行开头的所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!