Vim仅在行的开头处保留空格

Fra*_*wis 7 vim whitespace tabs

我正在使用

:set noet|retab!
Run Code Online (Sandbox Code Playgroud)

但我遇到的问题是它将整个文件中的4个空格的所有实例替换为选项卡.我需要vim只在行的开头替换4个空格的实例.

如果我删除了!在零售结束时,空间不会在任何地方更换.

我尝试过使用某人创建的自定义函数:

" Retab spaced file, but only indentation
command! RetabIndents call RetabIndents()

" Retab spaced file, but only indentation
func! RetabIndents()
    let saved_view = winsaveview()
    execute '%s@^\( \{'.&ts.'}\)\+@\=repeat("\t", len(submatch(0))/'.&ts.')@'
    call winrestview(saved_view)
endfunc
Run Code Online (Sandbox Code Playgroud)

但是当我运行时,我得到一个很好的小错误信息:

:RetabIndents
Run Code Online (Sandbox Code Playgroud)

处理函数RetabIndents时检测到错误:

第2行:

E486:未找到模式:^({4})+

Fra*_*wis 9

在与其他人谈论此事后,我需要添加无声!执行前的命令.所以这就是我现在的工作:

autocmd BufWritePre * :RetabIndents
command! RetabIndents call RetabIndents()

func! RetabIndents()
    let saved_view = winsaveview()
    execute '%s@^\(\ \{'.&ts.'\}\)\+@\=repeat("\t", len(submatch(0))/'.&ts.')@e'
    call winrestview(saved_view)
endfunc
Run Code Online (Sandbox Code Playgroud)

所以现在这个函数将自动用每行开头的制表符替换空格.

  • 您可以在`:substitute`命令的末尾使用`e`标志而不是`silent!`,请参阅`:h s_flags`. (3认同)