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

How do I replay macro q from command-line mode without changing @/?

Answer

:keeppatterns normal! @q<CR>

Explanation

When you replay macros from Ex commands, Vim can overwrite @/ (the last search pattern) depending on what the macro does. Wrapping macro execution in :keeppatterns lets you run automation while preserving your current search context, highlight behavior, and n/N navigation target. This matters in real cleanup passes where you alternate between scripted edits and manual search jumps.

How it works

  • :keeppatterns tells Vim to execute the following command without changing the search register.
  • normal! runs Normal-mode keys literally, ignoring user mappings, which keeps macro playback deterministic.
  • @q replays the macro stored in register q.
  • Combined, :keeppatterns normal! @q executes the macro once while keeping @/ intact.

Example

Assume you already searched for:

TODO

and recorded macro q to normalize spacing on the current line. Running:

:keeppatterns normal! @q

applies the macro but preserves the existing TODO search pattern, so n still jumps to the next TODO rather than a pattern introduced by the macro.

Tips

  • Use a range to replay on multiple lines: :10,30keeppatterns normal! @q.
  • Prefer normal! over normal for scripts so mappings do not change behavior across machines.
  • If the macro itself depends on prior cursor position, test on a small range first, then scale up.

Next

How do I open another file without changing the alternate-file mark (#)?