在Git中提交一些文件时,我得到了“尾随空白”错误。

我想在保存Python文件之前自动删除这些尾随的空白字符。

您可以配置Vim来实现这一点吗?如果有,怎么做?


当前回答

我在评论中看到了这个解决方案 删除不需要的空格

我真的很喜欢。添加。在多余的空白上。

把这个放到你的。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()

其他回答

autocmd BufWritePre *.py execute 'norm m`' | %s/\s\+$//e | norm g``

这将使光标保持在保存之前的相同位置

简单地从文件中去除尾随空格的解决方案在所有情况下都是不可接受的。它将在从一开始就具有此策略的项目中工作,因此在即将提交的提交中没有这样的空白。

假设您只是希望不添加尾随空格的新实例,而不影响未编辑行的现有空格,以使您的提交免受与您的工作无关的更改。

在这种情况下,使用git,你可以使用这样的脚本:

#!/bin/sh

set -e # bail on errors

git stash save commit-cleanup
git stash show -p | sed '/^\+/s/ *$//' | git apply
git stash drop

也就是说,我们保存更改,然后过滤diff中的所有+行,以在我们重新将更改应用到工作目录时删除它们的尾随空格。如果这个命令管道成功,我们就丢弃隐藏。

我在评论中看到了这个解决方案 删除不需要的空格

我真的很喜欢。添加。在多余的空白上。

把这个放到你的。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()

我就是这么做的。我不记得从哪里偷来的了。

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