tags:

views:

2574

answers:

4

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 save python files.

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

+21  A: 

I found the answer here (http://vim.wikia.com/wiki/Remove_unwanted_spaces#Automatically_removing_all_trailing_whitespace).

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

autocmd BufWritePre *.py :%s/\s\+$//e
Paul D. Eden
Is there any easy way to tell stackoverflow that the // is not really a comment here?
Mikeage
Interesting! Trailing white space is a battle at work. I loathe it, others don't understand why. We use as much vi as vim (I use vim; they don't because they'd have to install it). I have a program I call stb to Strip Trailing Blanks and I use that as a filter; works in vi too. This is better.
Jonathan Leffler
This changes cursor position on each save. Is is possible to avoid it?
stepancheg
OK, I've found, answer is below.
stepancheg
+22  A: 

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 :-)

mat
Handy! I like it. :)
Jonathan
Or you can set list and set listchars+=trail:.
Oli
Like my namesake, I like this. Thanks.
Jonathan Leffler
+2  A: 

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
gregf
Hum, that's pretty dangerous to do it on "*" if you eventually open up binary files, they may end up in a pretty bad shape.
mat
Yeah probably not the smartest, then again I don't use vim for a hex editor either. That won't execute unless you save.
gregf
+8  A: 

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 BufWritePre *.h :call <SID>StripTrailingWhitespaces()
stepancheg