Trim trailing whitespace

3.5
(209)

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! 🤘)

How useful was this post?

Average rating 3.5 / 5. Vote count: 209

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

60 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts

1 thought on “Trim trailing whitespace”

Leave a reply

Your email address will not be published. Required fields are marked *