Friday, December 31, 2010

Auto stripping of trailing whitespace characters on write

With anyone working on patches it's always important we have whitespace stripped before the diff/patch is pushed. Therefore this is what I add in my .vimrc(I use vim).
" automatically remove trailing whitespace before write
function! StripTrailingWhitespace()
    normal mZ
    if line("'Z") != line(".")
        echo "Stripped whitespace\n"
    normal `Z
autocmd BufWritePre COMMIT_EDITMSG,.vimrc,*.js,*.cpp,*.hpp,*.i,*.h,*.c :call StripTrailingWhitespace()


  1. I have this stuff highlighted in vim. just add this to your ~/.vimrc:

    let c_space_errors = 1
    let c_no_tab_space_error = 1

  2. Interesting snippet that will work well for many projects. However, if you edit a file that *already* has trailing whitespace, you shouldn't remove it in the same commit as other changes.

  3. @Anon75UGYhyT: Exactly. But that's what "git add -i" is for. ;)

    Thanks for the tip Hellyna! I use vim and I was looking for something like this, but I never took the time to learn how to write one.