Increment/Decrement Numbers in Vim

Vim is primarily a code editor, though once you get acclimatized to it, you’ll find yourself wanting to use it for any and all text editing. But when you’re editing code, you’re probably going to have numbers somewhere in your code. Sometimes you’re going to want to change those numbers. Maybe you’ll need to completely replace a number with another number, but other times you’re going to want to nudge that number up or down.

Take CSS for example. You have a margin that is set at 10px and it needs to be a bit larger. You can position your cursor over the 0 and press r to replace and 1 to change the total value to 11px. See how it looks, do the same thing to change it to 12 or 13. Hmm… Maybe it would be better smaller. Delete the whole 13 and replace it with 8.

There’s an easier way. And an even easier one.

Put your cursor on the line in question - anywhere before the number, and hit Control-A. The cursor jumps to the next number in that line and increments it. Continue hitting Control-A and the number keeps going up one-by-one. And Control-X does the same thing in reverse - decrementing the next number on the current line.

As useful as that is, a mapping can make it even easier.

1
2
3
" increment/decrement numbers
nnoremap + <C-a>
nnoremap - <C-x>

Really simple one. Normal mode mapping of + to Control-A for increment and - for Control-X for decrement. Makes things a lot more convenient. Of course, you might want to choose some other keys - < and > maybe. Whatever works for you.