How do I run a :g or :s command without overwriting my current search pattern?
Answer
:keeppatterns {cmd}
Explanation
Whenever Vim runs a command that involves searching — :g, :s, :v, or even moving the cursor with / — it overwrites the last search register (@/). This means n/N after an automated command no longer repeats your intended search. Prefixing any Ex command with :keeppatterns prevents that clobber: the search register is left exactly as it was before the command ran.
How it works
:keeppatterns {cmd}executes{cmd}without modifying@/(the last search pattern)- Useful in macros, mappings, and helper functions that use
:gor:sinternally - Also preserves the search history so your earlier entries are not shifted
Example
Suppose your search is set to function and you run a cleanup command:
:g/^\s*$/d
Now @/ is ^\s*$ and pressing n jumps to empty lines — not function. With :keeppatterns:
:keeppatterns g/^\s*$/d
@/ remains function, so n still finds your original pattern.
Tips
- Invaluable inside mappings that silently clean up whitespace or reformat text without "stealing"
n - Works with
:stoo::keeppatterns s/\s\+$//strips trailing whitespace without overwriting the search register - Combine with
:silentfor truly invisible automation::silent keeppatterns g/^$/d - Equivalent concept in Vimscript: save and restore
@/manually withlet save = @/ ... let @/ = save, but:keeppatternsis cleaner and more idiomatic