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

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 contents
  • q{UPPERCASE} — starts recording, appends to the existing register contents
  • q — stops recording

So to add steps to an existing macro in register q:

  1. Record your initial macro: qq{commands}q
  2. Run it and realize you forgot a step
  3. Instead of starting over, press qQ{additional commands}q
  4. Now @q runs 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): qA appends to a, qB appends to b, etc.
  • Combine with :let @q = @q . 'more' for programmatic editing of macro contents
  • Use :reg q before appending to inspect the current macro contents

Next

How do I replace only part of a matched pattern using \zs and \ze in a substitution?