Learn Practice Daily golf Reference

How to record and play a macro in Vim

Press qa to start recording into register a, make the edit once, then press q to stop. Press @a to play it back, @@ to play it again, or 10@a for ten more.

Try it here

Quote a list

Record the edit on apple: qa, I'Esc, A',Esc, j to step to the next line, q. Then 2@a does the other two. The veg list below needs the same edit, and the macro is still in register a.

1 of 2Record on apple, then play it twice with 2@a
1const fruits = [
2 apple',
1 banana',
2 cherry',
3];
4const veg = [
5 leek
6 onion
7 carrot
8];
NORMALLoading the editor…1/20.0s2:3

This editor needs a keyboard. Read on, and play it at your computer.

KeysWhat it does
qaStart recording into register a (any letter from a to z works).
qStop recording (in Normal mode).
@aPlay the macro in register a.
@@Play the last macro you played again.
10@aPlay it ten times. It stops early if a step fails, such as j on the last line.
:5,20normal @a ↵Play it once on each of lines 5 to 20, starting at the beginning of each line.
:'<,'>normal @a ↵Play it on each line you selected (press : in Visual mode and Vim types the range).
:g/TODO/normal @a ↵Play it on every line that contains TODO.
qARecord more onto the end of macro a (a capital letter appends).
:reg a ↵Show what is in register a.

Recording one that works every time

A macro replays your keys exactly, so record moves that work on any line, not just this one. Start from a known place: 0 or ^ for the start of the line, I and A to type at either end. Find things by what they are rather than counting: f( or /name instead of 8l. And end on the next line (j or +), so that @a and a count just carry on down the file.

When the lines aren't next to each other, or a count is hard to judge, use :normal instead: :g/pattern/normal @a runs the macro on exactly the lines you name.

Fixing a macro without recording it again

A macro is just text in a register, so you can edit it. Paste it on an empty line with "ap, fix the keys, then copy the line back into the register with 0"ay$ and delete the line. To add steps to the end, record with the capital letter: qA appends to what qa recorded.