26 February 2010

Vim: strip trailing whitespace on write

Git is picky about leave trailing whitespace (spaces at the end of a line) in your code. To keep it from being a problem, I modified some helpful scripts to my exacting specifications: it will notify you if it replaces trailing whitespace, it won't change your cursor position, and it won't affect innocent bystander files. Add it to your $HOME/.vim/ftplugin/cpp.vim ftplugin file.

" automatically remove trailing whitespace before write
function! StripTrailingWhitespace()
  normal mZ
  %s/\s\+$//e
  if line("'Z") != line(".")
    echo "Stripped whitespace\n"
  endif
  normal `Z
endfunction
autocmd BufWritePre *.cpp,*.hpp,*.i :call StripTrailingWhitespace()

I like Vim, but I despise Vimscript. Trying to get it to do exactly what I want takes so much guessing and consequently far too much time.

0 comments:

Post a Comment