如何自动删除vim中的尾随空格

时间:2021-07-12 14:13:54

I am getting 'trailing whitespace' errors trying to commit some files in git.

我在git中提交一些文件时,会出现“尾随空格”错误。

I want to remove these trailing whitespace characters automatically right before I save python files.

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

Can you configure vim to do this? If so, how?

你能配置vim来做这个吗?如果是这样,如何?

13 个解决方案

#1


188  

I found the answer here.

我在这里找到了答案。

Adding the following to my .vimrc file did the trick.

在我的.vimrc文件中添加以下内容就可以了。

autocmd BufWritePre *.py :%s/\s\+$//e

#2


158  

Compilation of above plus saving cursor position:

以上加上保存光标位置的编译:

fun! <SID>StripTrailingWhitespaces()
    let l = line(".")
    let c = col(".")
    %s/\s\+$//e
    call cursor(l, c)
endfun

autocmd FileType c,cpp,java,php,ruby,python autocmd BufWritePre <buffer> :call <SID>StripTrailingWhitespaces()

If you want to apply this on save to any file, leave out the first autocmd and use a wildcard *:

如果您想将此应用于任何文件的save,请删除第一个autocmd并使用通配符*:

autocmd BufWritePre * :call <SID>StripTrailingWhitespaces()

#3


63  

I also usually have a :

我通常还有一个:

match Todo /\s\+$/

in my .vimrc file, so that end of line whitespace are hilighted.

在我的.vimrc文件中,使行尾空格被分隔。

Todo being a syntax hilighting group-name that is used for hilighting keywords like TODO, FIXME or XXX. It has an annoyingly ugly yellowish background color, and I find it's the best to hilight things you don't want in your code :-)

Todo是一个语法组名,用于设置诸如Todo、FIXME或XXX等关键字。它有一种令人讨厌的黄色背景色,我发现最好在你的代码中隐藏你不想要的东西:

#4


50  

I both highlight existing trailing whitespace and also strip trailing whitespace.

我既突出了现有的拖尾空白,也突出了拖尾空白。

I configure my editor (vim) to show white space at the end, e.g.

我配置编辑器(vim)以显示最后的空白。

如何自动删除vim中的尾随空格

with this at the bottom of my .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()

and I 'auto-strip' it from files when saving them, in my case *.rb for ruby files, again in my ~/.vimrc

当我保存文件时,我会自动将它从文件中删除,在我的例子中是*。ruby文件的rb,同样在我的~/.vimrc中

function! TrimWhiteSpace()
    %s/\s\+$//e
endfunction
autocmd BufWritePre     *.rb :call TrimWhiteSpace()

#5


13  

Here's a way to filter by more than one FileType.

这里有一种方法可以通过多个文件类型进行筛选。

autocmd FileType c,cpp,python,ruby,java autocmd BufWritePre <buffer> :%s/\s\+$//e

#6


7  

Copied and pasted from http://blog.kamil.dworakowski.name/2009/09/unobtrusive-highlighting-of-trailing.html (the link no longer works, but the bit you need is below)

复制粘贴自http://blog.kamil.dworakowski.name/2009/09/unobtrusive-highlighting-of trailding .html(链接不再有效,但您需要的位在下面)

"This has the advantage of not highlighting each space you type at the end of the line, only when you open a file or leave insert mode. Very neat."

这样做的好处是,只有在打开文件或保持插入模式时,才不会突出显示在行尾键入的每个空格。非常整洁。”

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\+$/

#7


5  

This is how I'm doing it. I can't remember where I stole it from tbh.

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

autocmd BufWritePre * :call <SID>StripWhite()
fun! <SID>StripWhite()
    %s/[ \t]\+$//ge
    %s!^\( \+\)\t!\=StrRepeat("\t", 1 + strlen(submatch(1)) / 8)!ge
endfun

#8


3  

A solution which simply strips trailing whitespace from the file is not acceptable in all circumstances. It will work in a project which has had this policy from the start, and so there are no such whitespace that you did not just add yourself in your upcoming commit.

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

Suppose you wish merely not to add new instances of trailing whitespace, without affecting existing whitespace in lines that you didn't edit, in order to keep your commit free of changes which are irrelevant to your work.

假设您仅仅希望不添加拖尾空白的新实例,而不影响您没有编辑的行中的现有空白,以便使您的提交不发生与您的工作无关的更改。

In that case, with git, you can can use a script like this:

在这种情况下,使用git,您可以使用如下脚本:

#!/bin/sh

set -e # bail on errors

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

That is to say, we stash the changes, and then filter all the + lines in the diff to remove their trailing whitespace as we re-apply the change to the working directory. If this command pipe is successful, we drop the stash.

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

#9


2  

I saw this solution in a comment at VIM Wikia - Remove unwanted spaces

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

I really liked it. Adds a . on the unwanted white spaces.

我真的很喜欢它。添加一个。在不想要的空白上。

如何自动删除vim中的尾随空格

Put this in your .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()

#10


1  

The other approaches here somehow didn't work for me in MacVim when used in the .vimrc file. So here's one that does and highlights trailing spaces:

在MacVim中,当在.vimrc文件中使用时,这里的其他方法不太适合我。这里有一个可以突出结尾的空格:

set encoding=utf-8
set listchars=trail:·
set list

#11


0  

autocmd BufWritePre * :%s/\s\+$//<CR>:let @/=''<CR>

autocmd BufWritePre *:% s / \ \ + $ / / < CR >:让@ / = " < CR >

#12


0  

For people who want to run it for specific file types (FileTypes are not always reliable):

对于想要为特定文件类型运行它的人(文件类型并不总是可靠的):

autocmd BufWritePre *.c,*.cpp,*.cc,*.h,*.hpp,*.py,*.m,*.mm :%s/\s\+$//e

Or with vim7:

或与vim7:

autocmd BufWritePre *.{c,cpp,cc,h,hpp,py,m,mm} :%s/\s\+$//e

#13


0  

If you trim whitespace, you should only do it on files that are already clean. "When in Rome...". This is good etiquette when working on codebases where spurious changes are unwelcome.

如果修改空格,则应该只在已经清理的文件上执行。“当在罗马……”。在不欢迎虚假更改的代码库工作时,这是很好的礼节。

This function detects trailing whitespace and turns on trimming only if it was already clean.

此函数检测拖尾空格,并只在已清除时才启用修剪。

The credit for this idea goes to a gem of a comment here: https://github.com/atom/whitespace/issues/10 (longest bug ticket comment stream ever)

这个想法的功劳要归功于这里的一个评论: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

#1


188  

I found the answer here.

我在这里找到了答案。

Adding the following to my .vimrc file did the trick.

在我的.vimrc文件中添加以下内容就可以了。

autocmd BufWritePre *.py :%s/\s\+$//e

#2


158  

Compilation of above plus saving cursor position:

以上加上保存光标位置的编译:

fun! <SID>StripTrailingWhitespaces()
    let l = line(".")
    let c = col(".")
    %s/\s\+$//e
    call cursor(l, c)
endfun

autocmd FileType c,cpp,java,php,ruby,python autocmd BufWritePre <buffer> :call <SID>StripTrailingWhitespaces()

If you want to apply this on save to any file, leave out the first autocmd and use a wildcard *:

如果您想将此应用于任何文件的save,请删除第一个autocmd并使用通配符*:

autocmd BufWritePre * :call <SID>StripTrailingWhitespaces()

#3


63  

I also usually have a :

我通常还有一个:

match Todo /\s\+$/

in my .vimrc file, so that end of line whitespace are hilighted.

在我的.vimrc文件中,使行尾空格被分隔。

Todo being a syntax hilighting group-name that is used for hilighting keywords like TODO, FIXME or XXX. It has an annoyingly ugly yellowish background color, and I find it's the best to hilight things you don't want in your code :-)

Todo是一个语法组名,用于设置诸如Todo、FIXME或XXX等关键字。它有一种令人讨厌的黄色背景色,我发现最好在你的代码中隐藏你不想要的东西:

#4


50  

I both highlight existing trailing whitespace and also strip trailing whitespace.

我既突出了现有的拖尾空白,也突出了拖尾空白。

I configure my editor (vim) to show white space at the end, e.g.

我配置编辑器(vim)以显示最后的空白。

如何自动删除vim中的尾随空格

with this at the bottom of my .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()

and I 'auto-strip' it from files when saving them, in my case *.rb for ruby files, again in my ~/.vimrc

当我保存文件时,我会自动将它从文件中删除,在我的例子中是*。ruby文件的rb,同样在我的~/.vimrc中

function! TrimWhiteSpace()
    %s/\s\+$//e
endfunction
autocmd BufWritePre     *.rb :call TrimWhiteSpace()

#5


13  

Here's a way to filter by more than one FileType.

这里有一种方法可以通过多个文件类型进行筛选。

autocmd FileType c,cpp,python,ruby,java autocmd BufWritePre <buffer> :%s/\s\+$//e

#6


7  

Copied and pasted from http://blog.kamil.dworakowski.name/2009/09/unobtrusive-highlighting-of-trailing.html (the link no longer works, but the bit you need is below)

复制粘贴自http://blog.kamil.dworakowski.name/2009/09/unobtrusive-highlighting-of trailding .html(链接不再有效,但您需要的位在下面)

"This has the advantage of not highlighting each space you type at the end of the line, only when you open a file or leave insert mode. Very neat."

这样做的好处是,只有在打开文件或保持插入模式时,才不会突出显示在行尾键入的每个空格。非常整洁。”

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\+$/

#7


5  

This is how I'm doing it. I can't remember where I stole it from tbh.

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

autocmd BufWritePre * :call <SID>StripWhite()
fun! <SID>StripWhite()
    %s/[ \t]\+$//ge
    %s!^\( \+\)\t!\=StrRepeat("\t", 1 + strlen(submatch(1)) / 8)!ge
endfun

#8


3  

A solution which simply strips trailing whitespace from the file is not acceptable in all circumstances. It will work in a project which has had this policy from the start, and so there are no such whitespace that you did not just add yourself in your upcoming commit.

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

Suppose you wish merely not to add new instances of trailing whitespace, without affecting existing whitespace in lines that you didn't edit, in order to keep your commit free of changes which are irrelevant to your work.

假设您仅仅希望不添加拖尾空白的新实例,而不影响您没有编辑的行中的现有空白,以便使您的提交不发生与您的工作无关的更改。

In that case, with git, you can can use a script like this:

在这种情况下,使用git,您可以使用如下脚本:

#!/bin/sh

set -e # bail on errors

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

That is to say, we stash the changes, and then filter all the + lines in the diff to remove their trailing whitespace as we re-apply the change to the working directory. If this command pipe is successful, we drop the stash.

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

#9


2  

I saw this solution in a comment at VIM Wikia - Remove unwanted spaces

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

I really liked it. Adds a . on the unwanted white spaces.

我真的很喜欢它。添加一个。在不想要的空白上。

如何自动删除vim中的尾随空格

Put this in your .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()

#10


1  

The other approaches here somehow didn't work for me in MacVim when used in the .vimrc file. So here's one that does and highlights trailing spaces:

在MacVim中,当在.vimrc文件中使用时,这里的其他方法不太适合我。这里有一个可以突出结尾的空格:

set encoding=utf-8
set listchars=trail:·
set list

#11


0  

autocmd BufWritePre * :%s/\s\+$//<CR>:let @/=''<CR>

autocmd BufWritePre *:% s / \ \ + $ / / < CR >:让@ / = " < CR >

#12


0  

For people who want to run it for specific file types (FileTypes are not always reliable):

对于想要为特定文件类型运行它的人(文件类型并不总是可靠的):

autocmd BufWritePre *.c,*.cpp,*.cc,*.h,*.hpp,*.py,*.m,*.mm :%s/\s\+$//e

Or with vim7:

或与vim7:

autocmd BufWritePre *.{c,cpp,cc,h,hpp,py,m,mm} :%s/\s\+$//e

#13


0  

If you trim whitespace, you should only do it on files that are already clean. "When in Rome...". This is good etiquette when working on codebases where spurious changes are unwelcome.

如果修改空格,则应该只在已经清理的文件上执行。“当在罗马……”。在不欢迎虚假更改的代码库工作时,这是很好的礼节。

This function detects trailing whitespace and turns on trimming only if it was already clean.

此函数检测拖尾空格,并只在已清除时才启用修剪。

The credit for this idea goes to a gem of a comment here: https://github.com/atom/whitespace/issues/10 (longest bug ticket comment stream ever)

这个想法的功劳要归功于这里的一个评论: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