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

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

Answer

:call setreg("a", substitute(getreg("a"), "old", "new", "g"))

Explanation

The getreg() and setreg() functions let you read and write register contents as plain strings, making it possible to surgically edit a macro without re-recording it. This is especially valuable when a macro is long or complex and only needs a small correction.

How it works

  • getreg("a") returns the raw keystroke contents of register a as a string
  • substitute(str, pat, repl, flags) applies a regex substitution on that string, just like Vim's :s command
  • setreg("a", result) writes the modified string back to register a, ready to be replayed with @a

Example

Suppose you recorded a macro in register a that runs :s/function/method/<CR> on a line. You later realize you want to make the substitution case-insensitive. Instead of re-recording:

:call setreg("a", substitute(getreg("a"), "/g", "/gi", ""))

To inspect the raw macro contents before editing:

:echo getreg("a")

You can also paste the macro to a buffer line, edit it visually, then yank it back:

"ap      " paste register a as a line
" ...edit the line...
"ayy     " yank line back into register a

Tips

  • setreg() accepts a third argument for register type: 'c' (characterwise), 'l' (linewise), 'b' (blockwise) — use 'l' when the macro should replay as a sequence of Ex commands
  • Use getreg('a', 1, 1) to get the register content as a list of lines, which makes multi-line macro inspection easier
  • This technique works on any named register, including those holding complex multi-line macros

Next

How do I add more keystrokes to the end of an existing macro without re-recording the whole thing?