Make Vim macros fun to work with
Vim is a superb tool for repeating changes, and there is even a whole chapter in the user manual about repeating commands. Before we discuss macros, you should master the . dot command first. It repeats the previous change, and no matter how trivial that sounds, this is the command I use a zillion times a day.
It is super useful and saves so much time, but it is limited to the single change. There is a tool to solve this limitation! Macros are sequences of commands and the concept is simple, but the feature is as powerful as your Vim manoeuvring skills. It is a sequence of keystrokes recorded and stored in a register that you can replay later. You record one by pressing q{register} followed by a series of commands and q to stop the recording. The register can be a number of lowercase character.
The example above is not the most complicated macro, but good enough to prove its usefulness. Let’s break the command down.
- qa - start recording a macro to register
a - I - Enter insert mode at the beginning of a line
- const - add a
constkeyword followed by the a single space - Esc - get back to the normal mode
- f_ - go to the
_underscore - x - remove the
_underscore - ~ - convert the character under the cursor to uppercase
- f" - go to the
" - sr"' - surround replace
""with''(enabled by the mini.surround plugin) - A - Enter insert mode at the end of the line
- ; - add a
;semicolon - Esc - get back to the normal mode
- q - stop the macro recording
- j - go one line down
- @a - replay the macro from the
aregister - @@ - replay the most recently executed macro
Trivial example, but imagine the file having hundreds of lines. You can replay the recorded macro manually line by line like I did in the example above, or using two other methods.
- 100@a - Pass a count, in this case 100, to sequentially run the macro 100 times
- :normal @a - Replay in parallel for all selected lines
The remedy for macro pressure
I don’t know about you, but every time I enter a new macro recording, my brain freezes, I forget all my Vim skills and the chance I fuck it up is pretty high. As I said before, a macro is a sequence of recorded commands stored in the register, so luckily we can refine them in the buffer. Paste it using "{registry}p or use a :put {registry} command, amend and save it back using the ^"{registry}y$. Easy!
You may encounter keyboard codes like ^[ for escape, ^M for enter or <80>kb for backspace. This is how Vim represents some keys. The list of these key codes is long, but luckily you don’t need to remember them all. Just type CTRL-v while you’re in insert mode, followed by the key, and Vim will insert the right code. This is a huge helper while crafting more complicated macros.
I hope that helps. Let me know on Mastodon, Bluesky, or in the comments section below if you have any other tips that make working with macros more fun.