Skip to content

Instantly share code, notes, and snippets.

@bbugh
Created October 5, 2012 22:21
Show Gist options
  • Save bbugh/3842793 to your computer and use it in GitHub Desktop.
Save bbugh/3842793 to your computer and use it in GitHub Desktop.
Automatically stripping/highlighting trailing whitespace in VIM
" Two best solutions from the discussion here http://stackoverflow.com/questions/356126/how-can-you-automatically-remove-trailing-whitespace-in-vim
" Automatically strip white space on save in VIM.
fun! <SID>StripTrailingWhitespaces()
let l = line(".")
let c = col(".")
%s/\s\+$//e
call cursor(l, c)
endfun
autocmd BufWritePre *.* :call <SID>StripTrailingWhitespaces()
" Also highlight trailing whitespace in a red color when you're not in INSERT mode
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment