How can you automatically remove trailing whitespace in vim

I found the answer here.

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

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

Compilation of above plus saving cursor position:

function! <SID>StripTrailingWhitespaces()
  if !&binary && &filetype != 'diff'
    let l:save = winsaveview()
    keeppatterns %s/\s\+$//e
    call winrestview(l:save)
  endif
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 second autocmd and use a wildcard *:

autocmd BufWritePre,FileWritePre,FileAppendPre,FilterWritePre *
  \ :call <SID>StripTrailingWhitespaces()

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