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

How do I record a macro that processes one line and moves to the next?

Answer

qa0f:dwj0q

Explanation

How it works

When recording a macro that you plan to repeat across multiple lines, the key technique is to end the macro positioned on the next line, ready for the next iteration. This pattern makes the macro repeatable with a count like 10@a.

The command qa0f:dwj0q breaks down as:

  • qa -- start recording into register a
  • 0 -- move to the beginning of the current line
  • f: -- find the first colon on the line
  • dw -- delete the word (from colon to next whitespace)
  • j -- move down to the next line
  • 0 -- move to the beginning of that line
  • q -- stop recording

The important principles are:

  1. Start at a known position -- use 0 or ^ at the beginning to ensure consistent behavior
  2. End on the next line -- include j (or +) so each replay processes the next line
  3. Return to column 1 -- the trailing 0 ensures the cursor is ready for the next iteration

Example

Given a file with lines like:

name: John
age: 30
city: London

After recording qa0f:dwj0q on the first line, running 2@a on line two processes the remaining lines. The result:

name John
age 30
city London

This pattern of ending on the next line is fundamental to writing robust, repeatable macros.

Next

How do you yank a single word into a named register?