Vim Macros — Recording, Playing, and Editing Macros
Automate repetitive edits with Vim macros. Learn to record with q, play with @, run on visual selections, and edit macros for complex automation workflows.
Macros
Detailed Explanation
Recording and Playing Macros
Macros let you record a sequence of keystrokes and replay them:
Basic Macro Workflow
q{a-z}— Start recording into register {a-z}- Perform your edits
q— Stop recording@{a-z}— Play the macro
Playback Commands
| Command | Action |
|---|---|
@{a-z} |
Play macro from register |
@@ |
Replay the last executed macro |
{n}@{a-z} |
Play macro n times |
:'<,'>normal @{a-z} |
Run macro on each line in selection |
Macro Design Tips
Make macros robust by starting from a known position:
- Begin with
0or^(go to start of line) - Use
w,f,/for relative movement (notl) - End with
j(move to next line) so the macro works on consecutive lines
Example: Add Semicolons to Multiple Lines
qa— Start recording to register aA;— Append semicolon at end of lineEsc— Return to Normal modej— Move to next lineq— Stop recording99@a— Run on next 99 lines (stops at end of file)
Editing Macros
Since macros are stored in registers, you can edit them:
:let @a='and type the key sequence- Or paste the register content into a buffer:
"ap— Paste register a- Edit the text
"ayy— Yank back into register a
Recursive Macros
A macro can call itself to process lines until an error stops it:
qaq— Clear register aqa— Start recording- Perform edits +
jto move to next line @a— Call itself (recursive)q— Stop recording@a— Start the recursive macro
Use Case
You have a repetitive editing task — like reformatting dozens of similar lines, adding boilerplate to multiple positions, or transforming data — and need to automate it.