Editing text files can often require repetitive actions, which can be slow and error-prone. Vim includes a powerful macro system that extends upon named registers introduced in the previous chapter.
So what is a macro? Interacting with Vim to perform a task involves typing a sequence of keys. Those keys can be concatenated together into a string, which defines the specific sequence of keys required to perform our task. This string can be stored in a named register, just like any string.
The difference between a macro and any other string is how that string is interpreted when retrieved from the register. When we execute a macro, Vim interprets the string in the specified register as a sequence of commands as if we were typing them.
Macros are quite powerful, and are useful for solving quick one-off editing tasks as well as for executing common tasks across multiple files.
One of the nice things about Vim macros is the ease with which they can be created.
The first step to creating a macro is to plan the individual steps that will be recorded. After the steps have been planned, it is time to record the macro.
To start recording a macro, simply type q followed by the name of the named register you would like to store the macro in. After that, proceed through the sequence of steps that you would like to record, then when you are done simply type q again to stop recording.
Lets walk through an example. Starting with the buffer in the first tab below, suppose we want to wrap each line in HTML "p" tags. This can be approached in a few ways, but lets try it this way: first we will use o to insert a line below the current line and enter insert mode, then we will type the text for the closing tag, then finally return to normal mode.
Lets watch each step:
So far so good. Now, for the opening tag we will use O to insert a line above the current line and enter insert mode, then type the opening tag, and finally return to normal mode. Here are those steps:
Finally, we need to join the join the lines by executing J twice:
These steps achieve our goal, so it is time to record the macro.
We want to store this macro in the a register, so hit qa to start recording, repeat the steps, then type q to stop recording.
Next, we will learn how to execute the macro.