Highlight extra white spaces and fixed length column in VIM

vimvimrc

I want to highlight extra white spaces and fixed length column (e.g., 80 character in a line) using VIM

I created two vimrc rule in my .vimrc file

highlight ExtraWhitespacea ctermbg=darkred guibg=#382424
match ExtraWhitespacea /\s\+$/
highlight OverLength ctermbg=green ctermfg=white guibg=#592929
match OverLength /\%81v.\+/

Now, problem is – these rules run exactly as I want if applied separately, but will not work together.

Am I missing something here? How do I debug this?

Best Answer

The problem is that each :match command overrides the pattern of the previous one; they are not cumulative! Because of that, there are :2match and :3match variants. Use one of them:

highlight ExtraWhitespace ctermbg=darkred guibg=#382424
match ExtraWhitespace /\s\+$/
highlight OverLength ctermbg=red guibg=#525252
2match OverLength /\%81v.\+/

Additional variants can be created with the matchadd() Vimscript function.

Notes

  • Since Vim 7.3, there's a built-in 'colorcolumn' option that enables highlighting of column(s).
  • Your setup in ~/.vimrc only works for the very first window; i.e. a :split will create a window that doesn't have those highlightings. You can fix that via autocmds (or by using the 'colorcolumn' option).
  • There are more robust and elaborate solutions for highlighting trailing whitespace, for example my ShowTrailingWhitespace plugin. (The plugin page has links to alternative plugins.)