I’ve been using Vim for about three years now and I’ve only now started to understand how macros work. I’ve gotten by up until now without them. But today I encountered a case where I need them. In CoffeeScript, the only multi-line comments are supposed to be that should be preserved when minifying (for example, copyright notices). So, that means I need to be able to comment and uncomment out a bunch of lines at once.

This stack overflow answer by user Svante explained it succinctly.

Macros are like marks in that you have them from a-z and you create one by pressing the button for it followed by the letter you want to use. Marks are m, macros are q. So if you want to make a macro a, you press qa. You’ll then see that you’re in recording mode.

Screenshot of vim in recording mode

Now you can do pretty much any editing you want. In this example, I’ll remove all those #’s to uncomment this code. I’ll press xj to remove a character then go down a line, followed by q to exit recording mode. Now I have a macro in the a register that contains the actions xj. To call a macro, you use @ followed by the register. And since vim lets you repeat things by putting a number in front of it, you can say 8@a to output xjxjxjxjxjxjxjxj, or “delete a character then go down a line” 8 times.

Screenshot of vim having used a macro

Sweet! One more tool taken from the Vim featureset on the toolbelt.

##Update

In the comments Alec asked about using visual mode to select lines on which to run a macro. I found a good Stack Overflow response to this question.

In my dead-simple contrived example, instead of moving down a line, the macro would just be x. Then you would select the lines you want to delete the comment from and press : to jump to the vim command prompt,with some auto-filled command that says “for everything I selected”. Then enter a catch-all regex g/^/ followed by norm for normal mode, then @a to fire the macro. Thanks Dave Kirby for the explanation!