How do I add more keystrokes to the end of an existing macro without re-recording the whole thing?
Answer
qQ (or any uppercase register letter)
Explanation
When recording a macro with qq, you can append additional keystrokes to the existing macro by recording into the uppercase version of the same register. In Vim, recording to an uppercase register letter always appends to (rather than overwrites) the contents of the corresponding lowercase register.
How it works
q{lowercase}— starts recording, overwrites the existing register contentsq{UPPERCASE}— starts recording, appends to the existing register contentsq— stops recording
So to add steps to an existing macro in register q:
- Record your initial macro:
qq{commands}q - Run it and realize you forgot a step
- Instead of starting over, press
qQ{additional commands}q - Now
@qruns the original commands followed by the new ones
Example
Suppose you recorded qq^dwq to delete the first word on each line. Later you realize you also need to add a semicolon at the end. Instead of re-recording:
qQ$a;<Esc>q
Now @q runs ^dw then moves to end of line and appends ;.
Tips
- This works with all 26 registers (
a-z):qAappends toa,qBappends tob, etc. - Combine with
:let @q = @q . 'more'for programmatic editing of macro contents - Use
:reg qbefore appending to inspect the current macro contents