How do I persistently highlight specific patterns with custom colors in Vim?
Answer
:call matchadd('Search', 'pattern')
Explanation
The matchadd() function lets you add persistent highlights to patterns without affecting the search register. Unlike /pattern, these highlights remain visible even when you search for something else, making them ideal for code review or tracking multiple patterns simultaneously.
How it works
matchadd({group}, {pattern})— highlights all matches of{pattern}using highlight group{group}- Returns a match ID that can be used with
matchdelete()to remove it - Common groups:
Search,IncSearch,ErrorMsg,WarningMsg,DiffAdd
Example
:call matchadd('ErrorMsg', '\<TODO\>')
:call matchadd('DiffAdd', '\<DONE\>')
Before: TODO and DONE are plain text
After: TODO highlighted in red, DONE in green (simultaneously)
Tips
- Use
:call clearmatches()to remove all custom highlights - Store the ID:
:let m = matchadd('Search', 'pat')then:call matchdelete(m) - Use
matchaddpos()to highlight specific line/column positions instead of patterns - These highlights are window-local — they only affect the current window