I want trailing and leading whitespaces to be highlighted by vim. I created a ~/.vimrc file and appended this:

" highlight trailing and leading whitespaces
highlight TrailingWhitespaces ctermbg=red
match TrailingWhitespaces /\s\s*$/
highlight LeadingWhitespaces ctermbg=red
match LeadingWhitespaces /^\s\s*/

For some reason /\s+$/ and /^\s+/ didn't work at all it matched the + literally - i.e. /\s\+$/

Furthermore, only the first one, Trailing- or LeadingWhitespaces is being applied: enter image description here

As you can see, leading whitespaces are highlighted but trailing ones are not. Once I put the LeadingWhitespaces at the top, only trailing whitespaces are highlighted:

enter image description here

What am I not doing right?

I don't think there is a conflict with any other options in my ~/.vimrc file but just in case, here is the whole file.

  • You can only have one :match at a time. Use :2match for the second match, or combine the two regular expressions. – Rich Apr 7 '18 at 10:28
  • 2
    Use listchars instead – D. Ben Knoble Apr 7 '18 at 22:26

The main issue with your code is that you can only have one :match at a time, so your second call overwrites your first call. (See :help :match — a few paragraphs down.)

Vim provides a :2match command for the purpose of highlighting a second pattern:

match TrailingWhitespaces /\s\s*$/
2match LeadingWhitespaces /^\s\s*/

Alternatively, you could use the matchadd() function, or (ab)use the :syntax highlighting to provide multiple regular expressions:

syntax match TrailingWhitespaces /\s\s*$/
syntax match LeadingWhitespaces /^\s\s*/

Or you could combine the two regular expressions with \|: (See :help /\|.)

match TrailingAndLeadingWhitespaces /\s\s*$\|^\s\s*/

A couple of other notes:

  1. Even with two match commands, you don't really need two highlight groups, since you're using the same colour for both matches.

  2. Unless you're using a very magic search (see :help /\v) then + does indeed match a literal plus character. You need to use \+ to match "one or more of the preceding atom". You appear to have figured this out though, because you actually include a working regular expression in your question: /\s\+$/, so I'm not sure why you didn't use this in your matches?

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.