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

How do I highlight a pattern without moving the cursor or triggering a search?

Answer

:let @/ = 'pattern'

Explanation

Assigning directly to the search register @/ lets you set the active search pattern — and thus trigger hlsearch highlighting — without moving the cursor at all. This is useful in mappings and scripts where you want to pre-load a pattern for n/N navigation without the cursor jumping to the first match.

How it works

  • @/ is Vim's special register that holds the current search pattern
  • :let @/ = 'pattern' writes a new value into it directly, bypassing the / command entirely
  • Because the cursor never moves, this is ideal for use in macros or custom mappings
  • After setting it, n and N navigate matches, and hlsearch highlights them just as if you had typed /pattern

Example

Suppose your cursor is on line 5 and you want to highlight all occurrences of TODO without jumping to the first one:

:let @/ = 'TODO'

All TODO occurrences are now highlighted and n/N will navigate between them, but the cursor stays on line 5.

You can also capture the word under the cursor into @/ without moving:

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

This mimics * but without the cursor jump.

Tips

  • Combine with :set hlsearch if highlighting is currently off
  • Use \< and \> for whole-word boundaries: :let @/ = '\<word\>'
  • Works in macros: qq:let @/ = 'FIXME'<CR>q records a macro that sets the search pattern
  • To clear highlighting programmatically: :let @/ = ''

Next

How do I set a bookmark that persists across different files and Vim sessions?