How do I make Ctrl-A and Ctrl-X increment and decrement hexadecimal numbers?
Answer
:set nrformats+=hex
Explanation
By adding hex to the nrformats option, you tell Vim to recognise hexadecimal literals such as 0xFF or 0xDEAD when <C-a> or <C-x> is pressed. Without this, Vim treats those characters as plain text and the increment/decrement has no effect.
How it works
nrformatsis a comma-separated list of number formats Vim recognises for<C-a>and<C-x>.- Supported values include
hex(numbers prefixed with0xor0X),bin(prefixed with0b),octal(prefixed with0), andalpha(single letters). - Once
hexis enabled, placing the cursor anywhere on a hex literal and pressing<C-a>increments it, preserving the0xprefix and hex digit case.
Example
With :set nrformats+=hex:
uint8_t mask = 0x0F;
With the cursor on 0x0F, pressing <C-a> five times produces:
uint8_t mask = 0x14;
Tips
- Add
binas well (:set nrformats+=hex,bin) to also increment binary literals like0b1010. - Many Vim distributions include
hexby default; run:set nrformats?to see your current value. - Use
<C-x>to decrement. A count before either command changes multiple values at once:5<C-a>increments by 5. - To avoid accidentally incrementing numbers like
007as octal, remove octal::set nrformats-=octal.