在Git中提交一些文件时,我得到了“尾随空白”错误。
我想在保存Python文件之前自动删除这些尾随的空白字符。
您可以配置Vim来实现这一点吗?如果有,怎么做?
在Git中提交一些文件时,我得到了“尾随空白”错误。
我想在保存Python文件之前自动删除这些尾随的空白字符。
您可以配置Vim来实现这一点吗?如果有,怎么做?
当前回答
我既突出显示现有的尾随空白,也去掉尾随空白。
我配置我的编辑器(vim)在结尾显示空白,例如。
在我的。vimrc的底部:
highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches()
在保存文件时,我会“自动剥离”它,在我的情况下*。Rb为ruby文件,同样在我的~/.vimrc中
function! TrimWhiteSpace()
%s/\s\+$//e
endfunction
autocmd BufWritePre *.rb :call TrimWhiteSpace()
其他回答
autocmd BufWritePre *.py execute 'norm m`' | %s/\s\+$//e | norm g``
这将使光标保持在保存之前的相同位置
我在评论中看到了这个解决方案 删除不需要的空格
我真的很喜欢。添加。在多余的空白上。
把这个放到你的。vimrc里
" Removes trailing spaces
function TrimWhiteSpace()
%s/\s*$//
''
endfunction
set list listchars=trail:.,extends:>
autocmd FileWritePre * call TrimWhiteSpace()
autocmd FileAppendPre * call TrimWhiteSpace()
autocmd FilterWritePre * call TrimWhiteSpace()
autocmd BufWritePre * call TrimWhiteSpace()
编译以上加上保存光标位置:
function! <SID>StripTrailingWhitespaces()
if !&binary && &filetype != 'diff'
let l:save = winsaveview()
keeppatterns %s/\s\+$//e
call winrestview(l:save)
endif
endfun
autocmd FileType c,cpp,java,php,ruby,python autocmd BufWritePre <buffer> :call <SID>StripTrailingWhitespaces()
如果你想在保存到任何文件时应用此命令,请省略第二个autocmd并使用通配符*:
autocmd BufWritePre,FileWritePre,FileAppendPre,FilterWritePre *
\ :call <SID>StripTrailingWhitespaces()
从http://blog.kamil.dworakowski.name/2009/09/unobtrusive-highlighting-of-trailing.html复制粘贴(链接不再工作,但你需要的位在下面)
这样做的好处是不会突出显示你在行末键入的每个空格,只有当你打开文件或退出插入模式时才会突出显示。非常整洁。”
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
对于那些想要为特定的文件类型(FileTypes并不总是可靠的)运行它的人:
autocmd BufWritePre *.c,*.cpp,*.cc,*.h,*.hpp,*.py,*.m,*.mm :%s/\s\+$//e
或者使用vim7:
autocmd BufWritePre *.{c,cpp,cc,h,hpp,py,m,mm} :%s/\s\+$//e