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

How do I load the search register with a literal <cword> pattern?

Answer

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

Explanation

Sometimes * is too opinionated: it uses keyword boundaries and interprets regex metacharacters. When your token includes punctuation or mixed syntax, it is often safer to write directly to the search register with a very nomagic literal pattern. This command builds that pattern from <cword> so your next n/N search steps work immediately without hand-escaping.

How it works

  • :let @/ = ... writes directly to Vim's search register
  • expand('<cword>') grabs the word under the cursor
  • escape(..., '\\') escapes backslashes inside that text
  • '\V' prefixes the pattern with very nomagic mode, making nearly everything literal
  • .. concatenates the pieces into one final search pattern

After running it, the search state is updated exactly as if you had typed /... yourself. That means n, N, :set hlsearch, and other search flows continue to work normally, but with a predictable literal pattern.

Example

Suppose the cursor is on this token:

path\to\module

Run:

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

Now press n and Vim searches for that exact literal token, without regex surprises.

Tips

  • Swap <cword> for <cWORD> when tokens include punctuation-separated segments
  • Use :echo @/ after setting it if you want to inspect the exact pattern

Next

How do I append new keystrokes to an existing macro register without re-recording it?