:best of Vim

Showcasing the top Vim plugins, tips and tricks.

What is Vim?

Vim is a text editor for programmers, power users & command-line junkies.

What is :best of Vim?

:best of Vim showcases the best plugins, extensions & tips for making the most of Vim.

It was built for NoVIMber 2011.

Learn more...

Follow

Trailing Whitespace

Some of us hate trailing whitespace in our files. Here are some tips to deal with it.

Find it

Add this to your .vimrc:

match ErrorMsg '\s\+$'

...and trailing whitespace will be highlighted automatically, with the same syntax highlighting as an error.

Delete it

Add this to your .vimrc:

nnoremap <Leader>rtw :%s/\s\+$//e<CR>

...and <Leader>rtw will remove trailing whitespace. (You can replace rtw with anything you want. Remove Trailing Whitespace seems easy to remember.)

See :help <Leader> for more.

Kill it

The mapping above can be turned into a function that automatically kills trailing whitespace when Vim writes. Redefine it by adding this to your .vimrc:

" Removes trailing spaces
function! TrimWhiteSpace()
    %s/\s\+$//e
endfunction

nnoremap <silent> <Leader>rts :call TrimWhiteSpace()<CR>

Then you can add on-write triggers that call that function. Again, in your .vimrc:

autocmd FileWritePre    * :call TrimWhiteSpace()
autocmd FileAppendPre   * :call TrimWhiteSpace()
autocmd FilterWritePre  * :call TrimWhiteSpace()
autocmd BufWritePre     * :call TrimWhiteSpace()

You can also enable that mapping on a per-filetype basis with:

autocmd FileType python,java autocmd FileWritePre    * :call TrimWhiteSpace()
autocmd FileType python,java autocmd FileAppendPre   * :call TrimWhiteSpace()
autocmd FileType python,java autocmd FilterWritePre  * :call TrimWhiteSpace()
autocmd FileType python,java autocmd BufWritePre     * :call TrimWhiteSpace()

(Thanks to @mklappstuhl for the suggestion.)

Comments...