在Git中提交一些文件时,我得到了“尾随空白”错误。
我想在保存Python文件之前自动删除这些尾随的空白字符。
您可以配置Vim来实现这一点吗?如果有,怎么做?
在Git中提交一些文件时,我得到了“尾随空白”错误。
我想在保存Python文件之前自动删除这些尾随的空白字符。
您可以配置Vim来实现这一点吗?如果有,怎么做?
当前回答
在.vimrc文件中使用时,这里的其他方法在MacVim中不知何故对我不起作用。这里有一个这样的例子,它突出显示了尾随空格:
set encoding=utf-8
set listchars=trail:·
set list
其他回答
我就是这么做的。我不记得从哪里偷来的了。
autocmd BufWritePre * :call <SID>StripWhite()
fun! <SID>StripWhite()
%s/[ \t]\+$//ge
%s!^\( \+\)\t!\=StrRepeat("\t", 1 + strlen(submatch(1)) / 8)!ge
endfun
下面是一种通过多个FileType进行过滤的方法。
autocmd FileType c,cpp,python,ruby,java autocmd BufWritePre <buffer> :%s/\s\+$//e
如果要删除空白,应该只对已经是干净的文件进行处理。“在罗马的时候……”在不欢迎虚假更改的代码库上工作时,这是一种良好的礼仪。
此函数检测尾随空格,并仅在已经清除的情况下开启修剪。
这个想法的功劳来自这里的一个评论:https://github.com/atom/whitespace/issues/10(有史以来最长的bug票评论流)
autocmd BufNewFile,BufRead *.test call KarlDetectWhitespace()
fun! KarlDetectWhitespace()
python << endpython
import vim
nr_unclean = 0
for line in vim.current.buffer:
if line.rstrip() != line:
nr_unclean += 1
print "Unclean Lines: %d" % nr_unclean
print "Name: %s" % vim.current.buffer.name
cmd = "autocmd BufWritePre <buffer> call KarlStripTrailingWhitespace()"
if nr_unclean == 0:
print "Enabling Whitespace Trimming on Save"
vim.command(cmd)
else:
print "Whitespace Trimming Disabled"
endpython
endfun
fun! KarlStripTrailingWhitespace()
let l = line(".")
let c = col(".")
%s/\s\+$//e
call cursor(l, c)
endfun
我通常也有一个:
match Todo /\s\+$/
在我的.vimrc文件中,使行末空格高亮显示。
Todo是一个语法高亮组名,用于高亮Todo、FIXME或XXX等关键字。它有一个讨厌的丑陋的黄色背景色,我发现它是最好的突出你不想在你的代码中的东西:-)
autocmd BufWritePre *.py execute 'norm m`' | %s/\s\+$//e | norm g``
这将使光标保持在保存之前的相同位置