Frequently Asked Question

What are Vim macros and how do I record one with q?

A macro is a recorded sequence of keystrokes that you can replay on demand; Vim's answer to the "do this same thing on every line" problem. To record, press q in normal mode followed by a register letter (any letter from a to z). The status line shows recording @a. Now perform the edit exactly as you would by hand: move, delete, type, navigate to the next position. Press q again to stop recording.

To replay, press @a (or whatever register you used). Prefix with a count to repeat: 100@a runs the macro a hundred times, and @@ repeats the last macro you used. Macros are stored in the same registers as yanks, so "ap pastes the macro into the buffer as text, you can edit a misrecorded macro, then yank it back with "ay$ and run it again.

Macros become powerful when combined with line-range commands. :5,20normal @a runs the macro on every line from 5 to 20. :g/TODO/normal @a runs it on every line matching TODO. The trick is to make the macro idempotent on its starting position, usually by beginning with 0 (go to start of line) and ending with j (move down to set up the next iteration). For one-off bulk edits, this is often faster than writing a regex substitution and easier to reason about.

Further reading and video