Vim - Macros
Vim - Macros for Automation
Section titled “Vim - Macros for Automation”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.
Starting a Macro Recording
Section titled “Starting a Macro Recording”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:
qaAfter pressing qa, Vim will display recording @a in the command line area, indicating that it’s now recording your keystrokes into register a.
Performing Vim Actions
Section titled “Performing Vim Actions”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 toyy)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)
Stopping the Recording
Section titled “Stopping the Recording”To stop recording the macro, simply press q again in Normal mode.
qThe 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 aThis will show the keystrokes recorded in register a.
Playing Back a Macro
Section titled “Playing Back a Macro”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:
@aVim 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@aTo replay the last executed macro, you can use @@.
Appending to a Macro
Section titled “Appending to a Macro”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.