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 include alpha, octal, hex, and bin.

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 0b or 0B is considered binary.
  • If it starts with 0x or 0X it’s considered hexadecimal.
  • Vim considers any number that starts with 0 an octal.

With that in mind, here’s a few example of what you can do with these:

  • Start with 0b1101 and press <ctrl-a> and it becomes 0b1110
  • Start with 0b1110 and press 5<ctrl-x> and it becomes 0b1001
  • Start with 0xFA and press <ctrl-a> and it becomes 0xFB
  • Start with 0xFB and press 8<ctrl-x> and it becomes 0xF3
  • Start with 007 and press <ctrl-a> and it becomes 010

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 – Remove octal from the nrformats list

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.

How useful was this tip?

Average rating 4.5 / 5. Vote count: 59

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Andy Libby

36 Posts

Rider of bicycles. Writer of code. User of Vim.
View all posts