How do I increment or decrement a number under the cursor?
Answer
<C-a> / <C-x>
Explanation
Pressing <C-a> increments and <C-x> decrements the number under or after the cursor. Vim automatically finds the next number on the current line if the cursor isn't directly on one.
How it works
<C-a>adds 1 to the number<C-x>subtracts 1 from the number- Accepts a count prefix:
5<C-a>adds 5,10<C-x>subtracts 10
Example
With the cursor on the line margin: 10px;:
<C-a>→margin: 11px;5<C-a>→margin: 15px;<C-x>→margin: 9px;
Number formats
Vim recognizes several number formats:
:set nrformats=bin,octal,hex,alpha
| Format | Example | Prefix |
|---|---|---|
| Decimal | 42 |
(none) |
| Hex | 0xff |
0x |
| Octal | 077 |
0 |
| Binary | 0b1010 |
0b |
| Alpha | c → d |
(with alpha) |
Gotcha: Octal numbers
By default, Vim treats 007 as octal. To make it treat all numbers as decimal:
:set nrformats-=octal
Tips
- Works in visual mode: select multiple numbers and
<C-a>increments all of them - In visual block mode,
g<C-a>creates an incrementing sequence (covered in a separate trick) - Great for CSS values, array indices, port numbers, version numbers
- Combine with macros: record a macro that uses
<C-a>and replay it to increment across multiple lines