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.

  1. Start Recording: Press q followed by a register (e.g., q). Status bar shows recording @q.
  2. Perform Actions: Type your commands (e.g., ^dwA, <Esc>j).
  3. Stop Recording: Press q again.
  4. Replay: Press @q to replay once. Press 100@q to 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) or 0.
  • 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"

john,doe,admin jane,smith,user bob,jones,guest alice,wong,admin

3. Editing Macros

Since macros are just text stored in registers, you can edit them!

  1. Paste: "qp (Paste register q into the buffer).
    • Result might look like: ^i"<Esc>f,i"<Esc>j
  2. Edit: Change the text. Maybe you missed a quote.
  3. Yank Back: Select the line and type "qyy (Yank back to register q).

4. Recursive Macros

You can make a macro run until it hits an error (like end of file).

  1. Clear the register: qqaq (Record to q, do nothing, stop. This clears q).
  2. Start recording: qq.
  3. Do the work.
  4. Call the macro itself: @q.
  5. 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:

  1. Record your macro @q (ensure it works on one line).
  2. Select 100 lines with Visual Mode (V).
  3. Type :norm @q.
    • :norm tells Vim to run the following Normal mode keystrokes.
    • It applies @q to every selected line independently.

6. Practice Exercise

  1. Create a list of numbers: 1, 2, 3 on separate lines.
  2. Record a macro @q on the first line that:
    • Appends .jpg (A.jpg<Esc>).
    • Moves down (j).
  3. Replay it on the next lines (2@q).