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
qaq— Record an empty macro into registera, effectively clearing it. Without this step, an old value inacould execute prematurely mid-recording.qa— Begin recording into registera.{your operations}— Type the keystrokes that perform the task on one line or unit.@a— At the end of the recording, call the macro itself.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
qaqclear step is essential. Skipping it means any leftover content inawill run unexpectedly the moment@ais 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@awhen you want the macro to stop exactly at a real boundary rather than a hardcoded count.