document updated 12 days ago, on Feb 10, 2025
custom highlights in Vim
custom syntax rules
Using search highlighting can allow you to MUCH more quickly scan and grok code. It's so useful that it's worth knowing about all the tiny variants-on-the-theme:
- :nohlsearch
Clears the highlighting that remains from the last basic search.
- :match, :2match, :3match
Highlight a pattern, without affecting the search result. By using :match, :2match, and :3match, up to three can be active simultaneously.
Use :hi to list all available {group} colors. Example call:
:match ErrorMsg /foobar/
:match Err^^ {group}
- matchadd()
(requires Vim 7.1.040, released 2007-07-26)
The lower-level version of :match that allows unlimited matches to be added.
Example call:
:call clearmatches()
:call matchadd('DiffAdd', '^ERROR.*')
:call matchadd('S^^ {group}
Again, use :hi to list all available colors. The exact colors will vary based on the color scheme you have loaded.
Sometimes I add this to my .vimrc:
" <leader>l = lock in the current-search pattern
" <leader>L = clear all locked-in search patterns
nnoremap <leader>l :call matchadd('Visual', @/)<cr>
nnoremap <leader>L :call clearmatches()<cr>
- MultiSearch extension (improved version)
An extension that allows you unlimited number of simultaneously active searches+highlights.
getting more precise control over highlights
Some useful commands:
" display the list of current matches
:echo getmatches()
" use a hard-coded match ID, so we can overwrite just that specific match regex later
:silent! call matchdelete(100001) | call matchadd('IncSearch', 'my_custom_regex', 10, 100001)
" ^^^ This is my preferred solution right now. It works well!
" remember the match ID, so we can overwrite just that specific one later
:let w:match_database = matchadd('IncSearch', 'regex')
" (TODO: the above line isn't functional yet -- we need to add the 'matchdelete' somewhere)
related configuration settings
- wrapscan — whether the search wraps around to the top of the file after hitting the bottom
(it's too bad Vim doesn't do the "intelligent wrapping" that things like Visual Studio do... i.e. wrap only ONCE, and STOP searching after you get back to the original point that you began searching at. i.e. never duplicate search results)
plugins
Plugins that work with hilighting: