Vim: How to Remove Trailing Whitespace on Save in Vim

Tyler Tyler (291)
2 minutes

Trailing whitespace can be a real pain - especially when diffing changes between two versions of a file. Fortunately for vim users, there is an easy way to eliminate unwanted trailing whitespace without having to think about it.

Posted in these interests:
h/vim23 guides
h/webdev60 guides

Your .vimrc file is typically located in your home directory. So you can edit it by typing:

vim ~/.vimrc

Then adding the following line to your .vimrc will ensure that every time you save a file (:w), it will remove all trailing whitespace.

autocmd BufWritePre * :%s/\s\+$//e

Trailing whitespace will now be removed from the file when using the Vim editor.

Dayne Dayne (57)
0

You probably already know how to use vim's basic undo and redo features. For a quick refresher, read this short tutorial on how to use vim redo and undo.