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
    %s/\s\+$//e
    if line("'Z") != line(".")
        echo "Stripped whitespace\n"
    endif
    normal `Z
endfunction
autocmd BufWritePre COMMIT_EDITMSG,.vimrc,*.js,*.cpp,*.hpp,*.i,*.h,*.c :call StripTrailingWhitespace()

3 comments:

  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

    ReplyDelete
  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.

    ReplyDelete
  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.

    ReplyDelete