Macros: Automated Repetition
[!NOTE] The Power of Automation If you find yourself typing the same sequence of keys more than twice, you should be using a Macro. Macros allow you to record a sequence of commands to a register and replay them instantly.
1. The Macro Workflow
The process is simple: Record → Execute → Stop → Replay.
- Start Recording: Press
qfollowed by a register (e.g.,q). Status bar showsrecording @q. - Perform Actions: Type your commands (e.g.,
^dwA, <Esc>j). - Stop Recording: Press
qagain. - Replay: Press
@qto replay once. Press100@qto replay 100 times.
2. The Golden Rules of Macros
A macro is blind. It blindly repeats keystrokes. To make it robust, you must follow these rules:
1. Normalize Cursor Position
Always start your macro by moving the cursor to a known “anchor” point.
- Good: Start with
^(start of line) or0. - Bad: Assuming the cursor is already where it needs to be.
2. Use Relative Motions
Don’t use 10l (move right 10 times) if the word length varies.
- Good: Use
w(next word),f,(find comma),$(end of line).
3. Prepare for the Next Iteration
The last step of your macro should be to move the cursor to the start of the next item (usually j to go down a line).
Interactive: The Macro Player
We have a CSV list. We want to wrap names in quotes.
Goal: john,doe → "john","doe"
3. Editing Macros
Since macros are just text stored in registers, you can edit them!
- Paste:
"qp(Paste registerqinto the buffer).- Result might look like:
^i"<Esc>f,i"<Esc>j
- Result might look like:
- Edit: Change the text. Maybe you missed a quote.
- Yank Back: Select the line and type
"qyy(Yank back to registerq).
4. Recursive Macros
You can make a macro run until it hits an error (like end of file).
- Clear the register:
qqaq(Record toq, do nothing, stop. This clearsq). - Start recording:
qq. - Do the work.
- Call the macro itself:
@q. - Stop recording:
q.
Now when you trigger @q, it will run, then call itself, then run, then call itself… until it fails (e.g., search not found).
5. Parallel Execution on Multiple Lines
Sometimes recursion is dangerous. A safer way to run a macro on 100 lines:
- Record your macro
@q(ensure it works on one line). - Select 100 lines with Visual Mode (
V). - Type
:norm @q.:normtells Vim to run the following Normal mode keystrokes.- It applies
@qto every selected line independently.
6. Practice Exercise
- Create a list of numbers:
1,2,3on separate lines. - Record a macro
@qon the first line that:- Appends
.jpg(A.jpg<Esc>). - Moves down (
j).
- Appends
- Replay it on the next lines (
2@q).