Recording and replaying macros

Vim · Advanced · 12 min

Macros automate repetitive, structured edits that are too irregular for a single substitute.

A macro is a recorded sequence of keystrokes. qa starts recording into register a, you perform the edit, and q stops. @a replays it, @@ replays the last macro, and 10@a runs it ten times.

Recipe for robust macros:

  • Normalise the start: begin with 0 or ^ so the macro does not depend on where the cursor was.
  • Use searches and f/t, not counts of l and w, so it adapts to lines of different lengths.
  • End by moving to the next target, often j or n, so repeating it walks through the file.

If a motion fails inside a macro (a search finds nothing, j on the last line), the macro stops. That is a feature: 100@a safely processes "all remaining lines" and halts at the end.

To run a macro over a range instead of a count, use :normal: :'<,'>normal @a runs it once on each selected line, starting at column 0. This is often more reliable than counting.

Because macros live in registers, you can edit them: "ap pastes the macro as text, you fix it, then "ay$ yanks it back (without the newline). You can also define one with :let @a = '0f=i <Esc>'. A recursive macro calls itself at the end (record qaq first to empty it, then end the recording with @a), running until something fails.

Example

" turn lines like  name=Ann  into  "name": "Ann",
qa              " start recording into a
0               " normalise: start of line
i"<Esc>         " opening quote
f=              " jump to '='
s": "<Esc>      " replace '=' with '": "'
A",<Esc>        " close value and add comma
j               " move to next line
q               " stop recording
5@a             " apply to the next 5 lines
:'<,'>normal @a " or: once per selected line

Remember

  • qa ... q records, @a replays, @@ repeats the last macro
  • Start at a known position and use f/t/searches inside
  • :[range]normal @a applies a macro to each line in a range

Watch out for

  • Recording with absolute moves like 7l; the macro breaks on lines of different length.

Check yourself

  1. Why does `999@a` safely stop at the end of the file?
  2. How do you run macro `q` once on each line of a Visual selection?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vimhelp.org/repeat.txt.html#recording