如何在 Vi 和 Vim 中保存时自动去除尾随空格?

Mic*_*ant 27 vim editors vi vimrc whitespace

.vimrc保存文件时是否有自动删除尾随空格的设置?

理想情况下(为了安全起见)我只想对某些文件使用此功能,例如 *.rb

Mic*_*ant 32

这适用于所有文件(在 .vimrc 文件中):

autocmd BufWritePre * :%s/\s\+$//e
Run Code Online (Sandbox Code Playgroud)

这仅适用于 ruby​​(.rb) 文件(在 .vimrc 文件中):

autocmd BufWritePre *.rb :%s/\s\+$//e
Run Code Online (Sandbox Code Playgroud)

  • 这个解决方案很好,但我认为下面@Sukminder 的解决方案更好,因为它正确地重新定位了光标。 (9认同)

Run*_*ium 27

要保持光标位置,请使用以下内容:

function! <SID>StripTrailingWhitespaces()
    let l = line(".")
    let c = col(".")
    %s/\s\+$//e
    call cursor(l, c)
endfun
Run Code Online (Sandbox Code Playgroud)

否则光标将在保存后最后一次替换行的开头结束。

示例:您在行尾有一个空格122,您在线982并输入:w。不恢复位置,会导致光标在行首结束,122从而扼杀工作流程。

使用 设置对函数的调用autocmd,一些示例:

" Using file extension
autocmd BufWritePre *.h,*.c,*.java :call <SID>StripTrailingWhitespaces()

" Often files are not necessarily identified by extension, if so use e.g.:
autocmd BufWritePre * if &ft =~ 'sh\|perl\|python' | :call <SID>StripTrailingWhitespaces() | endif

" Or if you want it to be called when file-type i set
autocmd FileType sh,perl,python  :call <SID>StripTrailingWhitespaces()

" etc.
Run Code Online (Sandbox Code Playgroud)

也可以通过以下方式使用getpos(),但在这种情况下不需要

let save_cursor = getpos(".")
" Some replace command
call setpos('.', save_cursor)

" To list values to variables use:
let [bufnum, lnum, col, off] = getpos(".")
Run Code Online (Sandbox Code Playgroud)