I am getting \'trailing whitespace\' errors trying to commit some files in git.
I want to remove these trailing whitespace characters automatically right before I sa
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
I saw this solution in a comment at VIM Wikia - Remove unwanted spaces
I really liked it. Adds a .
on the unwanted white spaces.
.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()
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:
set encoding=utf-8
set listchars=trail:·
set list
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:
#!/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.
I also usually have a :
match Todo /\s\+$/
in my .vimrc
file, so that end of line whitespace are hilighted.
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 :-)
I found the answer here.
Adding the following to my .vimrc file did the trick.
autocmd BufWritePre *.py :%s/\s\+$//e