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

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

Answer

:keeppatterns {command}

Explanation

The :keeppatterns modifier runs an Ex command — typically :s, :g, or :v — without modifying @/ (the last search pattern) or the command history. This means your current hlsearch highlight, n/N navigation target, and search history all remain untouched after the command completes.

How it works

  • :keeppatterns is a command modifier, placed before any Ex command that uses a search pattern
  • Without it, :s/foo/bar/ would replace @/ with foo, breaking your previous search highlights
  • With it, @/ is restored to its original value after the command runs

This is especially useful in scripts, mappings, and autocmds that perform housekeeping substitutions.

Example

Suppose you're actively searching for TODO items (they're highlighted across your buffer). You want to strip trailing whitespace without losing that context:

" Without keeppatterns — destroys your TODO search:
:%s/\s\+$//e

" With keeppatterns — TODO stays highlighted and n/N still work:
:keeppatterns %s/\s\+$//e

A practical autocmd to strip trailing whitespace on save without disrupting any active search:

autocmd BufWritePre * keeppatterns %s/\s\+$//e

Tips

  • Combine with :silent to suppress both the substitution count message and the pattern side-effect: :silent keeppatterns %s/\s\+$//e
  • Works with :global too: :keeppatterns g/debug/d deletes debug lines without altering @/
  • Check your current last search pattern anytime with :echo @/

Next

How do I use PCRE-style regex in Vim without escaping every special character?