vim Manipulating text Incrementing and decrementing numbers and alphabetical characters


Example

In normal mode, we can increment the nearest number on the line at or after the cursor with <C-a> and decrement it with <C-x>. In the following examples, the cursor position is indicated by ^.

Incrementing and decrementing numbers

for i in range(11):
      ^

<C-x> decrements the number:

for i in range(10):
                ^

10<C-a> increments it by 10:

for i in range(20):
                ^

Incrementing and decrementing alphabetical characters

To make increment and decrement also work with letters, either use the ex command :set nrformats+=alpha or add set nrformats+=alpha to your .vimrc.

Increment example:

AAD
 ^ 

<C-a> increments it to B:

ABD
 ^ 

Decrement example:

ABD
  ^ 

<C-x> decrements D to C:

ABC
  ^ 

Incrementing and decrementing numbers when alphabetical increment/decrement is enabled

Notice that enabling increment/decrement to work with alphabetical characters means that you have to be careful not to modify them when you really want to just modify numbers. You can either turn off alphabetical increment/decrement by using the ex command :set nrformats-=alpha or you can just be aware of it and be sure to move to the number before increment or decrement. Here is the "for i in range(11):" example from above redone to work while alphabetical increment/decrement is set:

Let's say you want to decrease 11 to 10 and alphabetical increment/decrement is active.

for i in range(11):
      ^

Since alphabetical increment/decrement is active, to avoid modifying the character under the cursor, first move forward to the first 1 using the normal mode movement command f1 (that is lowercase f followed by the number 1, not to be confused with a function key):

for i in range(11):
               ^

Now, since the cursor is on the number, you can decrement it with <C-x>. Upon decrement, the cursor is repositioned to the last digit of the numeral:

for i in range(10):
                ^