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

How do I highlight a custom pattern persistently in a window without changing the search register?

Answer

matchadd()

Explanation

The matchadd() function adds a persistent highlight for a pattern in the current window without touching your search register or interfering with n/N navigation. Unlike /pattern (which sets the search register) or :match (which only supports one highlight at a time), matchadd() supports multiple simultaneous highlights and returns an ID you can use to remove specific ones later.

How it works

:call matchadd('Group', 'pattern')
  • 'Group' — any highlight group, e.g. 'Search', 'ErrorMsg', 'Todo'
  • 'pattern' — a Vim regular expression to match
  • Returns a match ID (integer) used to later remove this specific match
  • Optional 3rd argument: priority (default 10; higher overrides lower)

To remove highlights:

:let id = matchadd('ErrorMsg', '\s\+$')  " highlight trailing whitespace
:call matchdelete(id)                      " remove that specific match
:call clearmatches()                       " remove ALL matches in this window

Example

Highlight all TODO comments and trailing whitespace simultaneously:

:call matchadd('Todo', 'TODO\|FIXME\|HACK')
:call matchadd('ErrorMsg', '\s\+$')

Both patterns are highlighted at once. Your search register remains unchanged, so n/N still navigate your previous search.

Tips

  • Use :echo getmatches() to list all active matches and their IDs
  • Matches are window-local; use :windo call clearmatches() to clear all windows
  • Great for permanent per-session highlights in your vimrc via autocmd BufWinEnter
  • Neovim users may prefer vim.fn.matchadd() from Lua for the same effect

Next

How do I open the directory containing the current file in netrw from within Vim?