How do I programmatically extend or modify a recorded macro without re-recording it?
Answer
:let @a = @a . "\<CR>extra"
Explanation
Vim stores macros as plain text in registers — the same registers used for yanked text. This means you can read, concatenate, and rewrite macro content using :let, giving you surgical control over recorded sequences without re-recording from scratch.
How it works
@ain a Vimscript expression reads the current content of registera- The
.operator concatenates strings - Double-quoted strings like
"\<CR>"represent special keys (the backslash notation is resolved to the actual control character) - Assigning back to
@aupdates the macro register immediately
Example
You recorded a macro in @q but forgot to add a j to advance to the next line at the end:
:let @q = @q . "j"
Append a newline + some text at the end of each processed line:
:let @q = @q . "A;\<Esc>j"
Prepend a step to move to the beginning of the line first:
:let @q = "^" . @q
Tips
- Use
"\<Esc>","\<CR>","\<C-w>", etc. for special keys inside double-quoted strings - To inspect the current macro content:
:echo @q(shows the raw keystroke string) - Combine with
:put ato paste the macro into a buffer for visual editing, then yank it back with"ayy - You can store permanent macros in your vimrc:
let @q = '...'so they survive restarts