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

How do I persistently highlight a pattern in Vim using a specific highlight group without a plugin?

Answer

:match {group} /pattern/

Explanation

:match, :2match, and :3match give you three independent highlight slots that overlay patterns on the buffer using any highlight group — without touching the search register or requiring a plugin. Each slot is managed separately, so you can highlight up to three distinct patterns at once and clear them individually.

How it works

:match {HighlightGroup} /pattern/   " set slot 1
:2match {HighlightGroup} /pattern/  " set slot 2
:3match {HighlightGroup} /pattern/  " set slot 3
:match none                          " clear slot 1
:2match none                         " clear slot 2

Highlight groups must already be defined (e.g. Error, Search, WarningMsg, Todo) or defined with :highlight. The match is window-local.

Example

Highlight trailing whitespace in red while separately marking lines over 80 characters:

:match Error /\s\+$/
:2match WarningMsg /\%>80v.\+/

Clear trailing whitespace highlight when done:

:match none

Tips

  • :match (slot 1) should be reserved for your most important highlight; :2match and :3match layer on top
  • These are per-window, so different splits can have different active matches
  • For more than 3 simultaneous patterns, use :call matchadd('Group', 'pattern') instead — it has unlimited slots managed by ID
  • Clear all three at once: :match none | 2match none | 3match none
  • Add to your vimrc or an autocmd to make a persistent coding aid without plugins

Next

What is the difference between the inner word (iw) and inner WORD (iW) text objects in Vim?