I’d had an issue with my Vim config where when I started a new instance of Vim my trailing whitespace highlighting would work, but then after a period of time it would stop working. This had bothered me for a while, but I finally decided to just dedicate the time and figure out what was happening.
When I looked at how it was implemented in my .vimrc file, I found a solution that is commonly suggested, such as in this stackoverflow post, or the first solution at this wikia post. Basically it looked like this:
" Highlight trailing whitespace highlight ExtraWhitespace ctermbg=darkgreen guibg=darkgreen match ExtraWhitespace /\s\+$/
The first `Highlight` command sets up the colors that I want to use to highlight the whitespace, and the second `match` command setups up a regex to identify the whitespace, and binds it to the `ExtraWhitespace` highlight group.
There’s a problem with using the `match` command like this though. The `match` command is generally meant to be used for more temporary purposes (for example if you only temporarily wanted to highlight your trailing whitespace). It is only ever possible to track 3 matches at a time (using `match`, `2match`, and `3match` respectively), and it would be common for other parts of your vim configuration, or 3rd party plugins, to overwrite this configuration for their own purposes.
There is a better way! By using syntax highlighting along with an autocmd, we can perform a similar match, but in a much more persistent manner. This is what I modified my .vimrc to be now:
" Highlight trailing whitespace highlight ExtraWhitespace ctermbg=darkgreen guibg=darkgreen autocmd Syntax * syn match ExtraWhitespace /\s\+$/ containedin=ALL