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

How do I set the search pattern to the current word literally without executing a search in Vim?

Answer

:let @/ = '\V' . escape(expand('<cword>'), '\')

Explanation

This pattern lets you prepare a precise search target without jumping the cursor or triggering an immediate search motion. It is useful when the word under cursor may contain regex metacharacters and you want the next n/N search cycle to treat them as plain text.

How it works

  • @/ is Vim's search register (the same pattern used by / and ?)
  • expand('<cword>') gets the word under the cursor
  • escape(..., '\') escapes backslashes in that value so the pattern remains stable
  • '\V' prefixes very-nomagic mode so regex punctuation is interpreted literally
:let @/ = '\V' . escape(expand('<cword>'), '\')

After running this once, use n or N to navigate matches with your newly prepared literal pattern.

Example

Given this text and cursor on foo.bar:

foo.bar
fooXbar
foo.bar

Set the search register with the command above, then press n:

foo.bar
fooXbar
foo.bar

The next jump lands on the second literal foo.bar, skipping fooXbar because . is treated as a character, not a wildcard.

Tips

Pair this with :set hlsearch so you can preview all literal matches immediately after setting @/.

Next

How do I save only modified files across the argument list in Vim?