waitingkuo
waitingkuo

Reputation: 93754

How to increase/decrease all integers in the same line in Vim?

In Vim, ctrl+a is to increase an integer and ctrl+x is to decrease an integer.

For example, to modify the following code to append 1, 2, 3 to the array, I can simply put ctrl+a once in line3 and twice in line4:

array = []      # line1
array.append(1) # line2
array.append(1) # line3
array.append(1) # line4

Then it will becomes:

array = []      # line1
array.append(1) # line2
array.append(2) # line3
array.append(3) # line4

But it's not convenient while I want to increase more than one integer in a line. For example, I want to change:

rank1 = 1
rank1 = 1
rank1 = 1

to:

rank1 = 1
rank2 = 2
rank3 = 3

My question is, is it a convenient way to increase all the integer in the same line via one keystroke?

Upvotes: 2

Views: 1606

Answers (3)

Smylers
Smylers

Reputation: 1713

This command should do it:

:s/\d\+/\=submatch(0) + 1/g

Upvotes: 2

Smylers
Smylers

Reputation: 1713

In Vim version 8 (which didn't exist when this question was first asked) you can use g Ctrl+A to increase a column of numbers by 1 more each time. So starting with the above example of:

rank1 = 1
rank1 = 1
rank1 = 1
rank1 = 1
rank1 = 1

Move to the second line and press V to visually highlight it. Move to the last line, then type g Ctrl+A. That increases the first 1 (on the second line) to 2, the one on the line after to 3, and so on, giving you:

rank1 = 1
rank2 = 1
rank3 = 1
rank4 = 1
rank5 = 1

To then increase the column of 1s at the end of the lines, you need to select a block which doesn't include the numbers earlier on the line. For instance, with the cursor still on the second line, type $ Ctrl+V 3j. Then do g Ctrl+A again, and you get:

rank1 = 1
rank2 = 2
rank3 = 3
rank4 = 4
rank5 = 5

That still involves doing each number on a line separately, but because it does all lines at once, it only involves doing it twice in total, so should still be quicker.

Upvotes: 6

pktangyue
pktangyue

Reputation: 8524

You first type the following two lines:

array = []
rank1 = 1

Then put you cursor in line 2. Then type the following by order:

qa
yy
p
shift+v
:
s/\d\+/\=submatch(0)+1/g
q
5@a

And here '5' can change to how many repeat you want.

Ok, this works, but it becomes more complicated.

Upvotes: 2

Related Questions