Incrementing non-decimal numbers
We previously covered using <ctrl-a> or <ctrl-x> to increase or decrease numbers. In Increment and decrement numbers, we showed how a quick tap of either will move your cursor to the next number on the line and increment or decrement it. If you precede that with a number it will increment or decrement that many times: Press 10 <ctrl-a> to add 10 to the next number on the line.
But did you know you can make this tip also work with binary, octal, and hexadecimal numbers? Check your nrformats setting to see which are currently enabled:
:set nrformats?– Shows which increment formats are enabled. Available options includealpha,octal,hex, andbin.
By default, nrformats will equal bin,octal,hex. Binary support was not added until Vim 8, so if you’re using an older version, you might want to upgrade. With these default options, you can use <ctrl-a> or <ctrl-x> to increment binary, octal, and hexadecimal numbers. Here’s how Vim knows which number format is which:
- Any number that starts with
0bor0Bis considered binary. - If it starts with
0xor0Xit’s considered hexadecimal. - Vim considers any number that starts with
0an octal.
With that in mind, here’s a few example of what you can do with these:
- Start with
0b1101and press<ctrl-a>and it becomes0b1110 - Start with
0b1110and press5<ctrl-x>and it becomes0b1001 - Start with
0xFAand press<ctrl-a>and it becomes0xFB - Start with
0xFBand press8<ctrl-x>and it becomes0xF3 - Start with
007and press<ctrl-a>and it becomes010
Wait, what? That last one is weird. Shouldn’t it be 008? Well, since it starts with a leading 0, Vim considers this an octal number and increments it to 010. That’s probably not what most people want, so I’d recommend adding the following your .vimrc:
set nrformats-=octal– Removeoctalfrom thenrformatslist
If you use Tim Pope’s Sensible plugin, a set of sane defaults for Vim, it will do this for you.
There’s one more format that’s not in nrformats by default, and that’s alpha. This will allow incrementing any alphabetic character to the next letter in the alphabet. You probably don’t want this enabled, as it will essentially break incrementing numbers unless your cursor is already on the number exactly.
But there is one specific use where alpha might be helpful: incrementing a list of bulleted items that are each preceded with a letter such as a.) b.) c.), etc. There’s a demo of this in the screencast below.