【发布时间】:2012-01-09 14:08:10
【问题描述】:
我有一个BufWritePre 钩子添加到我的.vimrc 中,它在保存缓冲区之前修剪尾随空格。在编辑我自己的代码或其他也有始终删除尾随空格的策略的其他人的代码时,这对我来说非常方便。但是,这让我有时会弄乱其他人的空白,这在版本控制中看起来不太好。
我有两个想法,一般来说如何解决这个问题,我都有具体的问题:
选项 1
打开文件后(可能使用BufReadPost钩子),检测文件中是否有尾随空格。如果是,则设置一个缓冲区本地标志来发出信号。如果设置了标志,请在保存前禁用修剪。
这种方法的问题是我似乎不知道如何检测缓冲区中是否有尾随空格。我知道=~,但是如何将缓冲区内容作为字符串获取?或者更好的是,我可以使用/\s+$<cr> 进行搜索,但是如何检查搜索是否成功(如果有命中)?
选项 2(更智能)
如果空白修剪只发生在实际修改的行上会更好。这样我就可以不必关心代码中的尾随空格,但仍然不会弄乱文件的其余部分。这就提出了一个问题:我能否以某种方式获得我添加或修改的行的行号?
我是 Vimscript 的新手,如果有任何提示或提示,我将不胜感激 :)
更新:我现在选择了选项 1:
" configure list facility
highlight SpecialKey term=standout ctermbg=yellow guibg=yellow
set listchars=tab:>-,trail:~
" determine whether the current file has trailing whitespace
function! SetWhitespaceMode()
let b:has_trailing_whitespace=!!search('\v\s+$', 'cwn')
if b:has_trailing_whitespace
" if yes, we want to enable list for this file
set list
else
set nolist
endif
endfunction
" trim trailing whitespace in the current file
function! RTrim()
%s/\v\s+$//e
noh
endfunction
" trim trailing whitespace in the given range
function! RTrimRange() range
exec a:firstline.",".a:lastline."substitute /\\v\\s+$//e"
endfunction
" after opening and saving files, check the whitespace mode
autocmd BufReadPost * call SetWhitespaceMode()
autocmd BufWritePost * call SetWhitespaceMode()
" on save, remove trailing whitespace if there was already trailing whitespace
" in the file before
autocmd BufWritePre * if !b:has_trailing_whitespace | call RTrim() | endif
" strip whitespace manually
nmap <silent> <leader>W :call RTrim()<cr>
vmap <silent> <leader>W :call RTrimRange()<cr>
【问题讨论】: