joshtronic

in Software Development #Vim / Neovim

Incrementing and decrementing numbers in Vim

I live on the command-line, and a huge chunk of that time is spent in Vim. Well, Neovim, actually. I do everything from writing code, to writing for my blog, as well as other prose that I have in the works.

One thing that comes up pretty regularly, thanks to one of my projects, is the need to increment and decrement numbers. Usually just by +1/-1 but sometimes a bit more or less.

While it doesn't take much to change a bit of text, that only really works if you're inserting the same value for every line. Take for example:

1
2
3

If I wanted to change 1 to 2, 2 to 3 and 3 to 4, I would have to go through each line individually and change the text.

No thank you.

With Vim, you can use Ctrl+A to increment (add to) the number under the cursor, and Ctrl+X to decrement it (subtract from).

Select all of the lines, or the numbers themselves, and hit the hotkey for the direction / math you'd like to apply.

Want to add or subtract more than one? Like most Vim commands, you can tap a number before the command to apply it X number of times.

To increment by five, select the numbers, tap 5 and then Ctrl+A and you're good to go!