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

How do I set the search register programmatically so that n and N jump to my pattern?

Answer

:let @/ = 'pattern'

Explanation

The search register "/ always contains the last search pattern. Setting it with :let @/ = 'pattern' is equivalent to typing /pattern<CR> — after setting it, n/N, hlsearch highlighting, and gn all use the new pattern, without moving the cursor or adding a jump to the jumplist.

How it works

  • :let @/ = 'pattern' — set the search register to pattern
  • Immediately activates hlsearch highlights for that pattern
  • n and N will jump to next/previous occurrences
  • :echo @/ — display the current search pattern
  • Useful in mappings and functions where you want to set a search without the side-effect of a / search moving the cursor

Examples

Highlight all occurrences of the word under the cursor without jumping:

:let @/ = '\<' . expand('<cword>') . '\>'
:set hlsearch

Search for text from a register:

:let @/ = @a

Now n jumps to whatever was in register a.

Clear the search highlight and pattern:

:let @/ = ''
:nohlsearch

In a mapping — mark the word under cursor and highlight it:

nnoremap <leader>h :let @/ = '\<' . expand('<cword>') . '\>'<CR>:set hlsearch<CR>

Tips

  • Unlike /pattern<CR>, :let @/ = '...' does not move the cursor or create a jump entry
  • The pattern is literal Vim regex — use \< and \> for word boundaries, \V for literal strings
  • setreg('/', pattern) is the function equivalent — same effect: call setreg('/', @a)
  • Combine with hlsearch: :let @/ = 'TODO' | set hlsearch in a mapping to highlight all TODOs at once

Next

How do I run a search and replace only within a visually selected region?