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

How do I refactor a recorded macro by rewriting its keystrokes with substitute()?

Answer

:let @q = substitute(@q, 'foo', 'bar', 'g')

Explanation

Recorded macros are plain text stored in registers, which means you can refactor them instead of re-recording from scratch. This is useful when a macro is almost correct but needs one repeated token changed everywhere, such as a delimiter, a field name, or a motion. Using substitute() on the register gives you a fast, reproducible way to patch macro logic.

How it works

  • :let @q = ... reassigns register q, where your macro is stored
  • substitute(@q, 'foo', 'bar', 'g') rewrites every foo occurrence in the macro text
  • @q on the left side overwrites the original macro with the edited version
  • 'g' applies replacement globally within the register string

This pattern works because macros are just keystroke strings. You are not editing buffer text here; you are editing the macro program itself.

Example

Assume macro q currently inserts TODO markers like this:

TODO(api): fix endpoint

You decide the macro should emit NOTE instead of TODO. Run:

:let @q = substitute(@q, 'TODO', 'NOTE', 'g')

Now replaying @q inserts:

NOTE(api): fix endpoint

without rerecording any motions or insert-mode steps.

Tips

  • Inspect a macro with :echo @q before and after rewriting
  • Use escape() when replacing characters that have regex meaning
  • Keep a backup first, for example :let @z = @q

Next

How do I open the alternate buffer in a new split while keeping my current window unchanged?