How to show trailing spaces on line with background color?

Viewed 28

How can I in VIM show the trailing spaces/tab before the line end with a different background color? Is this possible?

So something like this:

Trailing lines in background color

2 Answers

I'm not sure about the background, but to make trailing spaces visible, you can use

set list listchars=trail:x

where x is the character shown in place of each one of the trailing spaces.

This means that if you use a "full block" character (see here), you obtain pretty much the result you want. enter image description here Except that I have no idea how to control its color.

trailing spaces

Here is a quick and dirty solution:

augroup TrailingSpaces
    autocmd!
    autocmd winEnter,BufEnter * call clearmatches() | call matchadd('ColorColumn', '\s\+$', 100)
augroup END

Comments:

  • The autocommand is triggered on :help winEnter and :help bufEnter. This is not optimal but necessary to handle some corner cases.
  • :help matchadd() allows us to add any number of matches in the current window.
  • :help clearmatches() will clear everything that was added with matchadd(), including stuff from plugins. Once again, this is not an optimal approach and you may encounter side-effects.
Related