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

How do I save the current search pattern into a named register before it gets overwritten by a new search?

Answer

:let @a = @/

Explanation

Vim stores the last search pattern in the special / register (@/). Any new search overwrites it. By assigning @/ to a named register with :let @a = @/, you preserve the pattern for later use — even after performing other searches. This is especially valuable in complex macros or scripts where you need to maintain two separate search patterns simultaneously.

How it works

  • @/ — Vimscript expression for the last search pattern register
  • :let @a = @/ — copies the search pattern into register a
  • Later, retrieve it with <C-r>a in command/insert mode, or restore it with :let @/ = @a

Example

Scenario: Find all functions named process_, then search for TODO comments while keeping the function pattern.

" 1. Search for the target pattern
/process_

" 2. Save it before searching for something else
:let @a = @/

" 3. Now search for TODOs (overwrites @/)
/TODO

" 4. Use the saved pattern in a substitution
:%s/<C-r>a/handle_/g

" 5. Or restore it as the active search pattern
:let @/ = @a

Tips

  • The reverse operation :let @/ = @a restores a saved pattern as the current search — n and N will then jump to matches of the restored pattern
  • In a macro, save with :let @s = @/, do other work, restore with :let @/ = @s to avoid disrupting the search state
  • Use :echo @/ to inspect the current search pattern before saving it
  • This same technique works for other special registers: :let @a = @: saves the last Ex command, :let @a = @. saves the last inserted text

Next

How do I encode and decode JSON data in Vimscript for configuration and plugin development?