How do I record a self-repeating recursive macro that automatically stops when it hits an error?
Answer
qa{motions}@aq
Explanation
A recursive macro is one that calls itself at the end of its own recording. When played back, it runs, invokes itself again, runs again, and so on — until a motion fails (e.g., end of file is reached, a search has no more matches, or a required text object isn't found). At that point Vim aborts the macro silently and the repetition stops.
This is a powerful alternative to N@a (running N times blindly) — the recursive approach naturally terminates at the right point without you having to count lines.
How it works
qa— start recording into registera(any register works){motions}— perform the operation you want to repeat (e.g., move to next line, make a change)@a— call registerarecursively at the end of the recordingq— stop recording@a— trigger the first call; the macro runs until it fails
The recursion terminates automatically because Vim stops the whole chain when any command errors (a failed motion, a search with no match, etc.).
Example
Append a semicolon to every line that doesn't already have one:
qa
:s/[^;]$/&;/<CR>
j
@a
q
Then run @a from the first line. The macro processes each line, moves down with j, calls itself, and stops when j reaches the last line and fails.
Tips
- Use
qqthen immediately record — this initializes the register to empty, preventing stale data from a previous recording from being invoked if@qis called during setup - Start with the cursor at the top of the region you want to process
- If the macro runs forever, press
<C-c>to interrupt it - The macro stops on the FIRST failure — design your motions so failure happens at the natural end point