vimtricks.wiki Concise Vim tricks, one at a time.

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

  1. qaq — Clear register a first (records an empty macro). This is essential: if register a already holds something, the @a inside the recording would run old content.
  2. qa — Begin recording into register a.
  3. {actions} — Your editing commands (e.g., A;<Esc>j to append a semicolon and move down).
  4. @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).
  5. q — Stop recording.
  6. @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}q before 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@a when you don't know the line count; they're self-limiting and leave the cursor at a meaningful position.

Next

How do I rename a variable across all its case variants (camelCase, snake_case, SCREAMING_CASE) in one command?