If you’re a text neat freak like me, then trailing whitespace — extra space characters at the ends of lines — can make your blood boil. The hallmark of an untidy developer, trailing whitespace can clutter up diffs, visually disrupt the viewport, and make moving around editors cumbersome.
There are a few related tricks for dealing with trailing whitespace in Vim that I’ll bundle up here. But remember that if you’re working in version control, such as Git, there are things like pre-commit hooks that can also deal with trailing whitespace.
First off all, you can display trailing whitespace in Vim with listchars. Try the following:
set listchars=trail:-
This will display trailing whitespace characters as a hyphen, subtly displaying them to you as a visual indicator.
You can remove all the trailing whitespace in a file with a substitution:
:%s/\s\+$//e
If you want to remove all the trailing whitespace from a certain filetype automatically, add this to your .vimrc
:
autocmd BufWritePre *.rb :%s/\s\+$//e
You could use simply *
there for all filetypes but I wouldn’t recommend it. There are probably some filetypes where trailing whitespace is necessary. Instead, use specific file types.
The main disadvantage to these substitutions is that it will leave your cursor in a different place. Toggling display of whitespace off and on isn’t easy either. That’s why there are also many plugins that deal with trailing whitespace in more elegant ways. One of the nicest is Trailer Trash. After installing the plugin, your trailing whitespace will be automatically highlighted in red. Plus, you’ll have several commands:
:TrailerTrim
- Trims trailing whitespace from current buffer. Puts the cursor back to where it was and resets the search highlight.:TrailerToggle
- Toggles trailing whitespace display. Great for when you’ve given up on fighting with your coworkers.
Here’s a short gif demonstrating the substitution method and the plugin method. Notice the difference in where your cursor lands. I’ve also made a video version of this tip, check it out on YouTube. (…like and subscribe! 🤘)
Was this useful? Help us improve!
With your feedback, we can improve VimTricks. Click a link to vote:
This was a great tip, but the 'set listchars' suggestion didn't work for me until I also added 'set list'.
Could use winsaveview() and winrestview() to restore cursor position.