How do I edit an existing macro without re-recording it from scratch?
Answer
:let @a = '...'
Explanation
When a recorded macro contains a typo or needs a small tweak, you can modify it directly via the :let command rather than re-recording the entire sequence. This is one of the most powerful macro debugging techniques available in Vim.
How it works
Vim stores macros in regular named registers. You can read and write these registers just like any other Vimscript variable:
- Inspect the current macro with
:echo @aor:reg a - Edit by assigning a new string:
:let @a = 'new keystrokes' - Alternatively, paste-edit-yank:
"apto paste the macro onto a scratch line, edit it visually, then"ayyto yank the line back into registera
Special key sequences use Vim's internal notation and must be typed literally when using :let. For example, Enter is \n, Escape is \e, and <Ctrl-w> is \<C-w>.
The paste-edit-yank workflow is often more practical for complex macros:
" Paste macro a onto a new line to inspect it
"ap
" (edit the line visually)
" Yank it back into register a
"ayy
" Delete the scratch line
dd
Example
Suppose you recorded qa to add a semicolon to the end of a line and move down:
:echo @a
" Output: A;<Esc>j
You realize you also need to go to the beginning of the next line. Fix it without re-recording:
:let @a = 'A;<Esc>j0'
The macro is updated immediately — run it with @a.
Tips
- Use
"apon an empty line, edit, thenV"ayto yank just the modified content (without the trailing newline) - To save a macro permanently, put
:let @a = '...'in yourvimrc - Uppercase register assignment (
:let @A = 'extra') appends to registerarather than replacing it