How do I create a recursive macro that repeats itself until it fails?
Answer
qqqqqq{edits}@qq
Explanation
A recursive macro calls itself at the end of its sequence, creating a loop that automatically repeats until a motion or command fails (such as hitting the last line or finding no more matches). This eliminates the need to guess a repeat count — the macro runs exactly as many times as needed and stops on its own.
How it works
qqq— clear registerqfirst (critical: prevents the old macro from running when@qis encountered during recording)qq— start recording into registerq{edits}— your actual editing commands (must include a motion that will eventually fail)@q— call registerqrecursively (the macro calls itself)q— stop recording@q— execute the macro to kick it off
The macro stops automatically when any command in the sequence fails — typically a motion like j on the last line or n with no more search matches.
Example
Add a semicolon to the end of every line from the cursor to the end of the file:
qqqqqqA;<Esc>j@qq
@q
Before:
let x = 1
let y = 2
let z = 3
After:
let x = 1;
let y = 2;
let z = 3;
Tips
- Always clear the register first with
qqq— if registerqalready contains a macro, the@qinside your recording will execute the old one mid-recording - The fail-and-stop behavior relies on Vim aborting a macro when any command errors — this is by design
- Combine with search:
qqqqqqn{edits}@qqprocesses every search match until none remain - Prefer recursive macros over
999@q— they are self-terminating and more precise