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

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 :g or :s internally
  • 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 :s too: :keeppatterns s/\s\+$// strips trailing whitespace without overwriting the search register
  • Combine with :silent for truly invisible automation: :silent keeppatterns g/^$/d
  • Equivalent concept in Vimscript: save and restore @/ manually with let save = @/ ... let @/ = save, but :keeppatterns is cleaner and more idiomatic

Next

How do I create my own custom ex commands in Vim?