Tutorial hero
Lesson icon

Macros and Incrementing Numbers in Vim

Originally published August 09, 2023 Time 3 mins

I’ve been using Neovim for a while now but there are a few blind spots I’ve been avoiding. One of those blind spots is performing repeated actions/multi-line editing. I recently faced a situation where I needed to edit a lot of text that would benefit from this, so it was either time to learn or time to suffer.

So, here’s what I learned this week - there are two main things. First, is macros. Recording macros in vim were previously something I did by accident (apparently by hitting the q key in normal mode by accident), and would freak out wondering how to get the macro to stop recording. What’s worse is when I accidentally played one of those macros I accidentally recorded.

It turns out they are pretty easy to use.

Here’s the scenario. I needed to make this change to my data:

Editing data in vim

To do this, I could yank the text I want to paste at the beginning of each line and then repeat: j (go down a line) 0 (go to start of line) P (paste before cursor). Then I would just have to manually do this for every line. I did this for a little while until I decided to bite the bullet and learn how to use macros properly - this is a very repetitive task that is well suited to a macro.

All I needed to do instead was press: qw (this starts recording a macro in the w register), repeat the same actions above, q (stop recording the macro).

With the macro recorded I can now repeat it by pressing @w this will repeat it once, or I can do 10@w to repeat it 10 times or however many times I need.

This sped things up a great deal, but you might be able to tell that I actually wanted these numbers to increment on each line, not just be a bunch of zeroes. After failing to do this with a macro, I found that you can simply select the numbers as a block with Ctrl-V:

Block select

Then hit g Ctrl-A - this will increment all of the numbers:

Incrementing in vim

Ctrl-A will increment, Ctrl-X will decrement, and prefixing with g is what increments each line by an increasing number (rather than just incrementing them all by the same amount).

This turned an incredibly annoying task into one that was… still pretty annoying to be honest, but I got it done way faster. And now that I’ve been forced into using this stuff, I’ll also be able to make use of it in smaller day-to-day situations where I’ve otherwise been avoiding it and just doing things manually.

Learn to build modern Angular apps with my course