3

One thing I need to do frequently is to increment the 2nd number on a line. Increasing the first is very comfortable by just pressing Control-a, but I just can't find a nice way to increase the 2nd.

There is no useful substring (as in, a word or a token or whatever) in that line that I can use for searches or jumps by text objects.

3

I mean, it's basically a hack, but assuming you're at the start of the line with the number on it:

<C-A><C-X>w<C-A>

Go to the next number, increment it, decrement it, go to the start of the next word, increment the next number. This jumps past and increments the second number. Unfortunately it's not easy to chain as you need to repeat most of the keys again.

  • 1
    If you want to repeat it, you probably could record it as a macro. – EvergreenTree Mar 9 '15 at 23:50
2

I'm not sure if this is the 'best' way, but 'a' way would be to create a mapping like this:

noremap <Leader>a ^/\d\+<CR>n<C-a>
  • ^ to go to the start of the line
  • /\d+<CR> to search for the first number
  • n to go to the next (second) match
  • <C-a> to increment the number under the cursor, which should be the second number now.

Or perhaps a slightly better way is to use a script

fun! IncSecond()
    normal ^
    call search('\d\+')
    call search('\d\+')
    execute "normal \<C-a>"
endfun
noremap <Leader>a :call IncSecond()<CR>

Calling search() doesn't set the / register and doesn't start highlighting if you have hlsearch set.
You could cram those lines in a keybind without a function:

noremap <Leader>a ^<Bar>:call search('\d\+')<Bar>:call search('\d\+')<Bar>:execute "normal \<C-a>"<CR>

But I would go for the readability of the function...

  • Thanks. I'd go with <kbd>Control-a</kbd> <kbd>Control-x</kbd> <kbd>l</kbd> <kbd>Control-a</kbd>, since I don't like to add nonstandard keybinds, but this would surely be they way to do it if I had to do it really often. Thanks! – PhilippFrank Mar 10 '15 at 11:31
  • @PhilippFrank Yeah, that's the better answer :-) Even if you wanted to make a keybind out of this, you're probably best off basing it on that ;-) – Martin Tournoij Mar 10 '15 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.