How do I highlight a custom pattern in the current window without affecting the search register?
Answer
:call matchadd('ErrorMsg', 'TODO')
Explanation
matchadd() lets you highlight arbitrary patterns using any highlight group — without touching the search register or search highlighting. Unlike :match (which allows only three layers, overwriting each other), matchadd() is stackable: every call adds a new independent highlight on top of existing ones, and each match can be removed individually by ID.
How it works
:call matchadd('{group}', '{pattern}')adds a new highlight match and returns a numeric match ID- The first argument is any highlight group (e.g.,
ErrorMsg,Todo,Underlined,WarningMsg) - The second argument is a Vim regex pattern
- An optional third argument sets priority (higher priority draws on top)
- Matches are scoped to the current window and survive buffer switches in that window
matchdelete({id})removes a specific match;clearmatches()removes all
Example
" Add two simultaneous highlights
let id1 = matchadd('ErrorMsg', 'FIXME')
let id2 = matchadd('Todo', 'TODO')
" Remove only the second one
call matchdelete(id2)
" View active matches
echo getmatches()
Tips
- Use
:match/:2match/:3matchfor quick one-off highlights; usematchadd()when you need many simultaneous patterns or programmatic control clearmatches()removes every match in the current window at once- Calling
:nohlsearchdoes NOT affectmatchadd()highlights — they persist until explicitly removed - Useful in
.vimrcautocommands to always highlight patterns likeTODO,FIXME, orHACKacross any file type