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

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 / :3match for quick one-off highlights; use matchadd() when you need many simultaneous patterns or programmatic control
  • clearmatches() removes every match in the current window at once
  • Calling :nohlsearch does NOT affect matchadd() highlights — they persist until explicitly removed
  • Useful in .vimrc autocommands to always highlight patterns like TODO, FIXME, or HACK across any file type

Next

How do I permanently add a word to my personal spell file so Vim stops marking it as misspelled?