Remove trailing whitespace on file save in Vim
I first want to say that I’m not the first to discover this. But I
recently added a modification to what I had in my .vimrc
that has
removed some small frustration.
In my .vimrc
, I remove trailing whitespace on file save, or writing
the buffer in Vim terms, using the autocmd
feature. To accomplish
this, I have the following lines in my .vimrc
file:
augroup eventtypemappings
autocmd!
autocmd BufWrite * execute "normal! mz" | keeppatterns %s/\v\s+$//e | normal `z
augroup END
The item that I added that I was originally unaware of was
keeppatterns
. It executes the command that follows without adding
anything to the search history.
Without this additional command, every time I wrote a file, the most
recent search would be set to \v\s+$
. This was most annoying when I
would be going through several files, searching for the same text in all
of them.
The first and last parts of the command deal with setting a mark (I
arbitrarily used z
for this) and going back to the mark after the
substitution. Without those, you will often find your cursor moving to
new locations upon writing the buffer. The first normal has to be
wrapped into an execute "normal"
, otherwise the rest of the characters
would simply be read as keys to be pressed in the normal command.
The augroup
command helps group autocommands. The autocmd!
line
deletes out any old autocommands. This prevents the autocommands from
being defined twice, which can happen if you source your .vimrc
file
multiple times.
You can always view my current dotfiles here.