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

The e flag at the end means that the command doesn't issue an error message if the search pattern fails. See :h :s_flags for more.


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