Skip to content

Vim - Macros

Vim’s macro feature allows you to record a sequence of Normal mode commands and replay them. This is incredibly powerful for automating repetitive editing tasks. Macros are stored in Vim’s registers.

This chapter covers:

  • How to start recording a macro.
  • Performing Vim actions to be recorded.
  • How to stop recording.
  • How to play back (execute) a recorded macro.

To start recording a macro, press q in Normal mode, followed by a letter (a-z) that will serve as the name (register) for your macro. For example, to start recording a macro into register a:

qa

After pressing qa, Vim will display recording @a in the command line area, indicating that it’s now recording your keystrokes into register a.

Once recording has started, perform any sequence of Normal mode commands, Insert mode typing, or Ex commands you want to be part of the macro. Vim will record these actions.

Example: Let’s say you want a macro that takes a line, duplicates it, and prepends ‘DEBUG: ’ to the new line.

  • After qa:
  • Y (yank the current line - alternative to yy)
  • p (paste the line below)
  • O (open a new line above the current line and enter Insert mode - cursor is now on the pasted line)
  • Type DEBUG:
  • Press Esc (return to Normal mode)

To stop recording the macro, simply press q again in Normal mode.

q

The recording @a message will disappear from the command line. The sequence of commands you performed is now stored in register a.

You can view the contents of a register (and thus your macro) using the :registers command or :reg <registername>. For example:

:reg a

This will show the keystrokes recorded in register a.

To play back (execute) the macro stored in a register, use the @ command followed by the register name. For our example macro stored in register a:

@a

Vim will execute the sequence of commands. To execute the same macro multiple times, prefix the command with a count. For instance, to execute the macro in register a 10 times:

10@a

To replay the last executed macro, you can use @@.

If you want to add more commands to an existing macro, you can record using an uppercase letter corresponding to the register. For example, to append commands to the macro in register a, you would start recording with qA.

Practical Application: Macros are invaluable for tasks like: transforming a list of items, applying a consistent formatting change to multiple lines, refactoring repetitive code patterns, or generating boilerplate code. For example, if you have a list of function names and you want to convert each into a Javadoc-style comment stub.