vimtricks.wiki Concise Vim tricks, one at a time.

How do I highlight a custom pattern with a priority so it wins over other overlapping highlights?

Answer

matchadd('Group', 'pattern', priority)

Explanation

matchadd() accepts an optional third argument: a priority integer that controls which match wins when two patterns cover the same text. The default priority is 10. Higher values take precedence, lower values lose to higher ones. This makes matchadd() more powerful than :match and :2match, which have fixed priorities and are limited to three simultaneous matches per window.

How it works

  • matchadd({group}, {pattern}) — default priority 10
  • matchadd({group}, {pattern}, {priority}) — explicit priority
  • Matches with higher priority numbers win over those with lower ones
  • Each window maintains its own match list; use getmatches() to inspect and matchdelete(id) or clearmatches() to remove

Example

Highlight TODOs at priority 20 so they always show over any background syntax:

call matchadd('Todo', 'TODO\|FIXME\|HACK', 20)

Then add a softer warning highlight at priority 5 (won't override the TODO highlight):

call matchadd('WarningMsg', '\bDeprecated\b', 5)

If both patterns match the same text, the higher-priority Todo group wins.

Tips

  • The built-in search highlight (hlsearch) uses priority 0, so any matchadd() call at priority ≥ 1 overrides it
  • Store the return value (a match ID) to remove specific matches later: let id = matchadd(...) | call matchdelete(id)
  • getmatches() returns a list of all active matches in the current window with their IDs and priorities
  • Add to autocmd WinEnter * to restore matches in new windows, since they are window-local

Next

How do I encode and decode JSON data in Vimscript for configuration and plugin development?