Gaut
Gaut

Reputation: 1397

vim: insert successive numbers in a row

Let's say I want to initialize this tuple:

t = (
    #(id, name)
     (1, 'aasd'),
     (2, 'bsfd'),
     (3, 'asf'),
         ...
     (21, 'aefae'),
)

I am sure I can do as follow with vim.

1/ Type this:

t = (
    #(id, name)
     (, 'aasd'),
     (, 'bsfd'),
     (, 'asf'),
         ...
     (, 'aefae'),
)

2/ Visual select comma row, and type a tricky key sequence which would write successive number

Does anyone know what is the tricky key sequence I should type?

Upvotes: 7

Views: 3080

Answers (3)

Christian Brabandt
Christian Brabandt

Reputation: 8248

Instead of using VisIncr newer vims (starting with Version 8) support incrementing in visual mode. So I would go with:

  • Press Ctrl-V and mark the column with the commas
  • I1ESC to initialize each column to 1
  • Visually block select the second to last row (using e.g. gvj)
  • press gCtrl-A to have each row sequentially incremented.

Upvotes: 21

Sato Katsura
Sato Katsura

Reputation: 3086

Using the VisIncr plugin:

  • press Ctrl-v and mark the column with the commas (that is, where you want the numbers)
  • Shift-i1Esc - this should insert a column of 1s
  • gv - mark the column of 1s
  • :I - this should change the column of 1s into numbers 1 ... 21.

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172520

This can be solved with a macro

  1. Position the cursor on the first number: 3Gf1
  2. Start recording: qq
  3. Yank the number lyT, go one down j, paste P, increment ^A (Ctrl+ A), stop recording q.
  4. Execute the macro for the remaining lines: 20@q

All together: 3Gf1lyT(jP^Aq20@q


To avoid the counting, and apply the increment until there are no more lines, you can also turn this into a recursive macro:

  1. Position the cursor on the first number: 3Gf1
  2. Clear macro register q and start recording: qqqqq
  3. Yank the number lyT, go one down j, paste P, increment ^A (Ctrl+ A), re-invoke macro @q. All together: lyT(jP^A@q

Upvotes: 4

Related Questions