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

How do I create a self-repeating recursive macro that runs until it reaches the end of the file?

Answer

qaq qa...@aq

Explanation

A recursive macro calls itself at the end of its recording, causing it to repeat automatically until an error — such as reaching the end of the file — stops it. This is more flexible than a count-based repeat (10@a) because you do not need to know in advance how many times to repeat the operation.

How it works

  1. qaq — Record an empty macro into register a, effectively clearing it. Without this step, an old value in a could execute prematurely mid-recording.
  2. qa — Begin recording into register a.
  3. {your operations} — Type the keystrokes that perform the task on one line or unit.
  4. @a — At the end of the recording, call the macro itself.
  5. q — Stop recording.

When you run @a, the macro performs your operations and then calls @a again. This recurses until a motion (like j to move to the next line) fails — for example at the last line — which raises an error and stops execution cleanly.

Example

Append a semicolon to the end of every line from the cursor to the end of the file:

qaq            " 1. Clear register a
qa             " 2. Start recording
A;<Esc>        " 3. Append semicolon and return to normal mode
j              " 4. Move to next line (fails at EOF, stopping recursion)
@a             " 5. Call self
q              " 6. Stop recording
@a             " Execute!

Tips

  • The qaq clear step is essential. Skipping it means any leftover content in a will run unexpectedly the moment @a is reached during recording.
  • Any motion that can fail — j, n, w — makes a natural stop condition. The error is swallowed silently when a macro reaches an error mid-sequence.
  • Prefer recursive macros over 999@a when you want the macro to stop exactly at a real boundary rather than a hardcoded count.

Next

How do I open the directory containing the current file in netrw from within Vim?