Replace all spaces at the start of the line with tabs

和自甴很熟 提交于 2019-12-11 12:26:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!