How to use macros in Vim
Note#60
Record a macro
- Press
q followed by a letter to start recording.
- Perform the desired operations.
- Press
q again to stop recording.
Running a macro
- Press
@ followed by the letter of the macro.
- Press
@@ to run the last executed macro again.
Apply a macro to a set of lines
- In visual mode, select the lines.
- Press
: followed by normal @ and the letter of the macro.
Viewing a macro
- Type
:registers or :reg to see the contents of all registers.
- Type
:reg <letter> to see the contents of a specific register.
Saving a macro
- Type
:let @<letter>='macro_contents', replacing <letter> with the register and macro_contents with the actual content of the macro.
- To insert the contents of an existing macro, type
:let @<letter>=' and then press Ctrl-R Ctrl-R <letter> to insert the contents literally.
- Add the above line to your
.vimrc file to load the macro automatically when Vim starts.
Appending to a macro
- Press
q followed by the capital letter of the macro to start appending.
- Perform the additional operations.
- Press
q again to stop appending.
Editing a macro
- Paste the macro contents into a new buffer or just a blank line using
"ap (replace ‘a’ with the appropriate letter).
- Edit the macro as needed.
- Yank the modified macro back into the register using
"ay$ (replace ‘a’ with the appropriate letter). Compared to "ayy, this will avoid yanking a trailing newline character.