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
:keeppatterninautocmddefinitions (e.g., auto-strip whitespace on save) to avoid surprising the user - Particularly valuable inside functions and mappings where a
:globalor:substitutewould otherwise clobber an active search - Can be combined with other modifiers:
:silent keeppattern %s/old/new/ge