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

How do I edit the contents of a macro register without re-recording it?

Answer

:let @q = substitute(@q, 'old', 'new', 'g')

Explanation

When a recorded macro has a typo or needs a small tweak, re-recording the entire thing is error-prone. Instead, treat the macro register as a string and manipulate it directly with :let and substitute(). This gives you surgical control over macro contents without touching the rest of the sequence.

How it works

  • @q — reads the contents of register q as a string
  • :let @q = expr — writes a string back into register q
  • substitute(@q, 'old', 'new', 'g') — replaces all occurrences of old with new inside the macro

To inspect the macro first, use :reg q to see its raw contents, or :echo @q to print it.

You can also edit a macro interactively:

  1. Open a scratch line with o<Esc>
  2. Paste the macro: "qp
  3. Edit the text directly
  4. Yank it back: 0"qy$

Or set the macro directly from scratch:

:let @q = 'Iconsole.log("DEBUG: ");hh'

Example

You recorded a macro in q that types console.log(), but you want it to type console.error() instead:

:let @q = substitute(@q, 'log', 'error', 'g')

Then verify with :reg q — the register now contains console.error() in the macro sequence.

Tips

  • Use \n in the substitute pattern to match newlines inside multi-command macros
  • Combine with execute() for complex transformations: :let @q = execute('...')
  • Store macros in your vimrc with :let @q = '...' so they persist across sessions
  • Works for any register, not just q

Next

How do I open a specific buffer in a new split without navigating away from my current buffer?