How do I write a Vim macro that automatically repeats until it fails?
Answer
qa{actions}@aq
Explanation
A recursive macro is one that calls itself as its final action, causing it to repeat indefinitely until any command in the body fails (e.g., j failing at the last line). This eliminates the need to count lines or use a large repeat count like 999@a.
How it works
qaq— Clear registerafirst (records an empty macro). This is essential: if registeraalready holds something, the@ainside the recording would run old content.qa— Begin recording into registera.{actions}— Your editing commands (e.g.,A;<Esc>jto append a semicolon and move down).@a— Call the macro recursively. On the first execution this runs the register (which at record time was empty from step 1, but is overwritten as soon as recording stops).q— Stop recording.@a— Trigger the macro once; it cascades until a command fails.
Vim silently aborts the macro on the first failed motion or command, so no error message is shown and the cursor stops at the last successfully processed line.
Example
Add a semicolon to every line in the file starting from the cursor:
qaq
qa
A;<Esc>j
@a
q
@a
Before:
const a = 1
const b = 2
const c = 3
After:
const a = 1;
const b = 2;
const c = 3;
The macro stops when j can no longer move down past the last line.
Tips
- Always clear the register with
q{reg}qbefore recording, otherwise the recursive call will execute stale content during recording. - Use
<C-c>to interrupt a runaway recursive macro if something goes wrong. - Prefer recursive macros over
999@awhen you don't know the line count; they're self-limiting and leave the cursor at a meaningful position.