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

How do I highlight a pattern in Vim without jumping the cursor to the next match?

Answer

:let @/ = 'pattern'

Explanation

Writing to the @/ register via :let @/ = 'pattern' sets Vim's last-search pattern directly — without performing a search or moving the cursor. With hlsearch enabled, matches immediately light up across the buffer, giving you a non-intrusive highlight while keeping your cursor exactly where it is.

How it works

  • @/ is the last search pattern register — the same register that /, ?, *, and # write to
  • :let @/ = '...' assigns any string (including Vim regex) to it, bypassing the normal search movement
  • Vim treats the new value as the active search pattern for n, N, hlsearch highlighting, and :%s//replacement/g (the empty pattern reuses @/)

Example

Highlight all occurrences of "TODO" without moving the cursor:

:let @/ = 'TODO'
:set hlsearch

All TODO comments glow, cursor stays put. Then use n/N to jump between them at your own pace.

Set the search pattern to the current word dynamically:

:let @/ = expand('<cword>')

This is like pressing * but without the cursor jump to the next match.

Tips

  • Use in mappings to create a "highlight only" star: nnoremap <leader>h :let @/ = expand('<cword>')<CR>:set hlsearch<CR>
  • Inside macros, :let @/ lets you pre-load a pattern that subsequent n keystrokes will navigate — useful for multi-step macros that need to reposition between recordings
  • :let @/ = '' clears the search pattern, which also stops hlsearch from highlighting anything
  • Read @/ to inspect or reuse the current pattern: :echo @/

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?