Working Code
Imagine you have to wrap these 5 items in quotes:
apple
banana
cherry
date
elderberry
Editing line by line means repeating the same work five times. A macro lets you show Vim the work once.
qa ← start recording to register a
0 ← move to start of line
i" ← insert a quote in front
Esc
A" ← append a quote at the end
Esc
j ← move to the next line
q ← stop recording
Now press 4@a and the remaining four lines are done at once:
"apple"
"banana"
"cherry"
"date"
"elderberry"
Try It Yourself
The semicolons are missing at the end of every line in this JavaScript. Add them with a macro:
const name = "dale";
const age = 30;
const city = "seoul";
const lang = "ko";
const role = "dev";
- Place the cursor on the first line and press
qato start recording. - Press
A;to append a semicolon at the end of the line. - Press
Escandjto move to the next line. - Press
qto stop recording. - Run
4@ato apply the macro to the remaining lines.
Try transforming some CSV data too:
name,age,city
dale,30,seoul
kim,25,busan
To replace commas with tabs on each line: qa0f,r\tjf,r\tjq — this is how you combine searches and substitutions inside a macro.
"Why?"
A macro is Vim's record button. Think of a cassette recorder — press record (q), play, press record again to stop. Playback (@) can repeat as many times as you want.
Why start with 0? Macros replay exactly what was recorded. If you record from the middle of a line, playback starts from wherever the cursor is. 0 moves to the start of the line, normalizing the starting position so the macro works identically on every line.
Why end with j? You need to move to the next line at the end so 10@a applies to each line in sequence. Without j, the macro keeps running on the same line.
What's a register? In qa, the a names the slot that stores the macro. You have 26 registers from a to z, so you can keep several macros on hand.
Deep Dive
Macro essentials
| Command | Action |
|---|---|
qa | Start recording into register a |
q | Stop recording |
@a | Play the macro in register a |
@@ | Replay the last macro |
10@a | Play macro a 10 times |
:reg a | Inspect the content of register a |
What if the macro stops midway?
Macros halt automatically when an error occurs. For example, a macro that uses f, to jump to a comma stops on a line without a comma. You can exploit this: call 100@a without worrying — it stops on its own when there's nothing left to process.
Write a macro that converts plain text into an HTML list.
Before:
Apple
Banana
Cherry
After:
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
Hint: record with qa0i<li>EscA</li>Escjq, then run 2@a.
question: Which keys record a macro into register b? answers:
question: How do you replay macro a twenty times? answers:
question: Why start a macro recording with 0? answers: