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

How do I run a substitute command without overwriting my current search pattern?

Answer

:keeppatterns

Explanation

Normally, any command that uses a pattern — including :substitute, :global, and :vimgrep — replaces the current search register @/ with the new pattern. This means your carefully crafted search highlight disappears the moment you run a :s command. :keeppatterns is a command modifier that tells Vim to restore the previous search pattern afterward, leaving your @/ register (and hlsearch highlighting) untouched.

How it works

  • Prefix any Ex command with :keeppatterns to prevent it from overwriting the search register
  • :keeppatterns s/trailing_space \+$// — strip trailing whitespace without changing @/
  • :keeppatterns g/^$/d — delete blank lines while preserving your active search
  • Works with any Ex command that internally uses patterns, including :global and :vimgrep
  • Especially useful in .vimrc and scripts where silent cleanup should not affect user workflow

Example

You search for a function name (highlighted across the file), then realise you need to strip trailing whitespace:

/myFunction

Without :keeppatterns:

:%s/ \+$//e

This strips trailing spaces but your myFunction highlight is gone — n now jumps to trailing-space matches.

With :keeppatterns:

:keeppatterns %s/ \+$//e

Trailing spaces removed, myFunction still highlighted, n still navigates to the next match.

Tips

  • Put it in your BufWritePre autocommand for on-save cleanup without disrupting your search
  • Combine with :silent! for completely invisible cleanup: :keeppatterns silent! %s/ \+$//
  • The /e flag on :s suppresses the "no match" error; together they make a robust, non-intrusive formatter

Next

How do I match a pattern only when it is preceded or followed by another pattern, without including that context in the match?