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

How do I anchor a search or substitution pattern to the current cursor position?

Answer

\%#

Explanation

The \%# atom in Vim's regex engine matches the exact position of the cursor — zero-width, between characters. Unlike character-based atoms, it tests where the cursor is, not what character is there. This makes it possible to write substitutions and matchadd() patterns that are relative to the cursor rather than a fixed text anchor.

How it works

  • \%# is a zero-width assertion — it matches the cursor position without consuming any characters
  • It can appear anywhere in a pattern: before, after, or between other atoms
  • Works in / searches, :s substitutions, and matchadd() calls
  • The cursor position is evaluated at the moment the command runs

Example

Insert a marker string at the cursor position without leaving Normal mode:

:s/\%#/>>MARK<</

Before (cursor is on q in quick):

the quick fox

After:

the >>MARK<<quick fox

Wrap the word starting at the cursor in brackets:

:s/\%#\(\w\+\)/[\1]/

Tips

  • \%# matches a position, so it must be combined with other atoms (it alone selects no characters)
  • Related column and line anchors: \%l (specific line), \%c (byte column), \%v (virtual column)
  • Useful in autocmd CursorMoved + matchadd() to create dynamic, cursor-relative highlights
  • Because it anchors to the live cursor, the same :s command behaves differently depending on where your cursor is

Next

How do I programmatically set a register's content in Vimscript to pre-load a macro?