Last Updated: February 25, 2016
·
1.371K
· gshutler

Trim trailing whitespace in vim

Sometimes you want to remove trailing whitespace from a whole file if you notice some. Doing that by hand gets a little laborious:

:%s/\s\+$//<CR>

And means you end up at a random point in the file.

I've bound a key in normal mode which places a marker, strips the trailing whitespace, and returns to the marker it placed before stripping the whitespace. This is what I added to my .vimrc:

nnoremap <F8> my:%s/\s\+$//<CR>`y

You might want to change the name of the marker used (y) or the key that it is bound to (F8).