Replace with incremented count

I’m often creating a series of entries in an enum or such and their names only differ by a number, e.g:

enum
{
      THING_1
    , THING_2
    , THING_3
    ...
    , NUM_THINGS
}

I copy and paste an entry the number of times needed, but it’s tedious to have to touch each line and replace the number with the next one. There’s got to be an easy recipe for replacing multiple selections with an incrementing value.

good news, there is! In insert mode, hit ctrl-r, then #. It’ll insert the selection index (starting from 1.) So I’d use…

  • <a-i>{ to select inside the braces
  • s\d+ to select the digits,
  • c to delete each selection and enter insert mode
  • <c-r># to replace with the index
4 Likes

in cases where I’ve needed the selection to start from 0, I use <a-s-)> to rotate the selections forward after the replacement, then just replace the first value with a 0 manually. There’s probably a better way, though!

Thank you. I haven’t fully explored the ctrl-r menu yet, but I’ve used it for pasting in the current search or yank buffer.

After pasting the selection index with <c-r># you can write -1 in the buffer and pipe to bc to make them start from zero. Make sure the 1-1, 2-1, 3-1 and so on are selected and use |bc<ret>.

2 Likes

For incrementing and decrementing selections, you can do something like that:

map -docstring 'increment selection' global normal <c-a> ': increment-selection %val{count}<ret>'
map -docstring 'decrement selection' global normal <c-x> ': decrement-selection %val{count}<ret>'

define-command -override increment-selection -params 1 -docstring 'increment-selection <count>: increment selection by count' %{
  execute-keys "a+%sh{expr $1 '|' 1}<esc>|{ cat; echo; } | bc<ret>"
}

define-command -override decrement-selection -params 1 -docstring 'decrement-selection <count>: decrement selection by count' %{
  execute-keys "a-%sh{expr $1 '|' 1}<esc>|{ cat; echo; } | bc<ret>"
}
1 Like