Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim command to increment number digit ONLY at cursor position in a longer number string?

Tags:

vim

I have a few instances where I want to do the following

In file:

1234

With the cursor at the 1st digit, I want to use Ctrl-A to increment the digit so that I get

2234

instead of

1235

Are there intrinsic vim commands to do this?

Otherwise, should I set up a quick script:

  1. Surround digit with leading and trailing space
  2. Ctrl-A to increment
  3. Delete leading and trailing space

Like so, and then map to a key?

like image 949
Kevin Lee Avatar asked Jul 24 '12 14:07

Kevin Lee


2 Answers

The increment function takes a leading number like most vim commands. 1000 ctrl+a would return 2234 like you wanted. If all your numbers are 4 digits numbers then this would work. Or you could use r2 which replaces the current character under the cursor with a 2, but this may be too specific.

If you need your script you can record a macro.

qaa[space][esc]h[ctrl+a]lx

broken down:

qa - start recording a q macro and save to register a

a[space][esc] - add a space after number

h - move back to number

ctrl+a - add one

lx move right and delete space.

You shouldn't need to add a leading space, because as you noticed the ctrl+a function acts on the number as a whole and will always add 1.

like image 83
Brombomb Avatar answered Sep 30 '22 17:09

Brombomb


You could do this as s<C-r>=<C-r>"+1<Enter>.

You can then map that to something else, like nnoremap g<C-a> s<C-r>=<C-r>"+1<cr> (you'll need to use Ctrl-vCtrl-r to insert the <C-r>s in this normal map).

Step by step:

s - delete the character under the cursor and begin insertion

<C-r>= - begin an expression evaluation.

<C-r>" - put contents of unnamed register in

See :help i_CTRL-r for more information on these.

+1<Enter> - add 1 to the value and complete the command.

like image 29
Conner Avatar answered Sep 30 '22 18:09

Conner