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 registera- Later, retrieve it with
<C-r>ain 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 @/ = @arestores a saved pattern as the current search —nandNwill then jump to matches of the restored pattern - In a macro, save with
:let @s = @/, do other work, restore with:let @/ = @sto 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