How do I make a macro repeat itself until it reaches the end of the file?
Answer
qqq qq{commands}@qq @q
Explanation
A recursive macro calls itself at the end of its recording, causing it to repeat automatically until a motion fails (like j at the last line). This eliminates the need to count lines or guess a repeat count — the macro just runs until it naturally stops.
How it works
qqq— clear registerqfirst (this prevents the old macro from running during recording)qq— start recording into registerq{commands}— perform your editing operations, ending with a motion that will fail at the boundary (likejto move down)@q— call the macro recursively (since we cleared it first, this does nothing during recording)q— stop recording@q— play the macro; it runs, moves down, calls itself, runs again... untiljfails on the last line
The key insight is clearing the register first with qqq. Without this step, @q during recording would execute whatever was previously stored in q.
Example
Add a semicolon to the end of every line from the cursor to the end of file:
qqq
qqA;<Esc>j@qq
@q
This appends ;, moves down with j, and repeats. When j fails on the last line, the macro stops automatically.
Tips
- Always clear the register first (
qqq) to avoid unexpected behavior during recording - The macro stops when any motion in the sequence fails, so use
j,n,w, orfas natural terminators - For more control, use
}to jump by paragraph or]]to jump by section