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

  1. q{a-z} — Start recording into register {a-z}
  2. Perform your edits
  3. q — Stop recording
  4. @{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:

  1. Begin with 0 or ^ (go to start of line)
  2. Use w, f, / for relative movement (not l)
  3. End with j (move to next line) so the macro works on consecutive lines

Example: Add Semicolons to Multiple Lines

  1. qa — Start recording to register a
  2. A; — Append semicolon at end of line
  3. Esc — Return to Normal mode
  4. j — Move to next line
  5. q — Stop recording
  6. 99@a — Run on next 99 lines (stops at end of file)

Editing Macros

Since macros are stored in registers, you can edit them:

  1. :let @a=' and type the key sequence
  2. 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:

  1. qaq — Clear register a
  2. qa — Start recording
  3. Perform edits + j to move to next line
  4. @a — Call itself (recursive)
  5. q — Stop recording
  6. @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.

Try It — Vim Cheat Sheet

Open full tool