How to use Vim macros (a use case)

Recently, I had an interesting case where the power of Vim, especially macros, really shines. Let's start an adventure and dig deeper into this interesting and fascinating world.

I have strong feelings about multi-line comments formatted as a sequence of single-line comments. In my view, if you need to explain something briefly, write a very short single-line comment. If this comment starts to bloat, this is an obvious sign that you should provide more information and write a thorough and detailed multi-line comment.

Browsing through a new legacy code base, I found a few comments formatted in this weird way. So, my task was to change the comments’ formatting in the minimum amount of time. Probably, in Vim exists a plugin that does it automatically (let me please know in the comments), but I didn’t find a way to fully automate it. But I've found a way to do it semi-automatically.

If you use any of JetBrains products, you have the possibility to change the comment style around the commented lines with the Comment with Block Comment action. If you don’t, you have to wrap the sequence of comments manually. I ended up with something like this (the example goes with line numbers).

15  /*        
16  // this is a comment
17  // this is the same comment
18  // this is the same comment
19  */

That’s not ideal because of the single-line comments in the middle. Besides, I don’t want to waste my time updating every line manually. And this is the exact case, where the Vim’s macros are real time savers. If you never heard of macros, take a look at the Vim Wiki or read the documentation.

I wrote a macro which substitute the two forward slashes with an asterisk. If you want to use this macro you need to assign it to a Vim register. This Ex (colon) command assigns the macro to the c register:

let @c="^c2l *\<esc>"

Now, the macro can be executed at any line where the cursor is by pressing @c. But this is not the coolest thing. The coolest thing is the flexibility of using it.

It can be applied to the selected lines. Select the lines in Visual mode, then use Ex (colon) command:

<,'> norm @c

It can be applied to the specific lines.

16,18 norm @c

There are many more ways how it can be applied. And, this is is the power of Vim!

Note: works in IdeaVim too.