How do I control which number formats Vim uses when incrementing and decrementing with Ctrl-A and Ctrl-X?
Answer
:set nrformats
Explanation
The nrformats option tells Vim how to interpret numbers when you press <C-a> (increment) or <C-x> (decrement). By default Vim recognises octal and hexadecimal notation, which can produce surprising results. Understanding and tweaking this option is essential for any Vim user who edits source code with numeric literals.
How it works
The option accepts a comma-separated list of format names:
octal— numbers starting with0(e.g.007) are treated as octal.<C-a>on007yields010, not008.hex— numbers starting with0xor0Xare incremented in base 16.bin— numbers starting with0bor0Bare incremented in base 2.alpha— a single alphabetical character is cycled (e.g.a→b,z→a).unsigned(Neovim) — numbers are treated as unsigned when decrementing through zero.
The most common improvement is disabling octal to avoid accidental octal arithmetic on zero-padded numbers:
set nrformats-=octal
To allow cycling through letters of the alphabet:
set nrformats+=alpha
Example
With the default nrformats=octal,hex, placing the cursor on 009 and pressing <C-a>:
Before: 009
After: 010 ← Vim treated it as octal!
After :set nrformats-=octal, the same operation gives:
Before: 009
After: 010 ← Wait, 9+1=10 in decimal, same result here
The difference becomes clear with 007:
With octal: 007 → 010 (octal increment)
Without octal: 007 → 008 (decimal increment)
Tips
- Add
:set nrformats-=octalto your vimrc to avoid subtle bugs when editing zero-padded integers. nrformats+=alphais handy for cycling through list items labelled a, b, c or generating test variable names.<C-a>and<C-x>also accept a count:5<C-a>adds 5 to the number under the cursor.