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

How do I run an Ex command without changing the current search pattern?

Answer

:keeppattern {cmd}

Explanation

Many Ex commands silently overwrite the search register (@/), which changes your hlsearch highlighting and n/N behavior. Prefixing a command with :keeppattern makes it execute normally but preserves whatever pattern was in @/ before the command ran. This is essential in scripts, mappings, and autocommands where you do not want to disrupt the user's active search.

How it works

  • :keeppattern — a command modifier that saves the current value of @/ before the following command executes and restores it afterward
  • Works with any Ex command that might alter the search register: :substitute, :global, :vimgrep, :sort, and others
  • The command itself still works normally — it just does not leave a side effect on the search register

Example

Suppose you searched for /TODO and have matches highlighted. Now you want to strip trailing whitespace without losing your search:

" Without keeppattern — @/ becomes '\s\+$' and TODO highlighting is gone:
:%s/\s\+$//e

" With keeppattern — @/ stays as 'TODO', highlights preserved:
:keeppattern %s/\s\+$//e

Tips

  • Use :keeppattern in autocmd definitions (e.g., auto-strip whitespace on save) to avoid surprising the user
  • Particularly valuable inside functions and mappings where a :global or :substitute would otherwise clobber an active search
  • Can be combined with other modifiers: :silent keeppattern %s/old/new/ge

Next

How do I ignore whitespace changes when using Vim's diff mode?