13

I am editing a .sql file in Vim:

INSERT INTO apps_forms (app_id, form_id) VALUES
(1, 1),

What I'm looking to do is yank the (1, 1), line and paste it 137 times; however, I want the second number in parenthesis to be incremented each time. The output would look like:

INSERT INTO apps_forms (app_id, form_id) VALUES
(1, 1),
(1, 2),
(1, 3),
...
(1, 137),

Is there a way to do that in Vim and, if so, what command would I use?

Thanks!

10

Put your cursor on the (1, 1), line then type :

qaVypt)<C-a>q135@a

Explanation :

qa begins the recording of a macro inside the register a (you could choose another letter).

Vyp duplicates the current line, by selecting the whole line (V), copying it (y) and then pasting it below (p).

t) move the cursor just before the next closed parenthesis, so that it's on the second number.

<C-a> (Ctrl and a) increments the number.

q ends the recording of the macro.

135@a replays the macro stored in the register a 135 times.

Edit : Peter Rincker has a shorter command :

qqYpW<c-a>q135@q

The differences are :

it uses the register q to store the macro (faster to type qq than qa because it's the same key),
it copies the line with only one keystroke Y (instead of two Vy),
and it moves the cursor to the second number with only one keystroke W (instead of t)).

  • 4
    Vim golf: qqyypW<c-a>q135@q. Even shorter if you use Y instead of yy. – Peter Rincker Nov 11 '15 at 0:16
9

Recent Vims have learned about incrementing visual selected regions as well as creating a sequence. So you can do this after pasting your line 137 times:

1) visually block-select the second 1 starting from line 3.

2) press gCtrl-A

I have recorded a screen cast here

Disclaimer: This needs a Vim 7.4.900 or so.

  • Successfully tested in Vim 7.4.826 on Debian/sid. – Dubu Nov 17 '15 at 13:38
  • Your screencast has disappeared but this method is AWESOME! Thanks. – david_nash May 10 at 4:06
2

The easy to understand / easy to remember / easy to adapt to other situations way to do it: use the VisIncr plugin (if you'd rather use a version that actually plays nice with the package managers from this century as opposed to dealing with vimballs, you can get it from GitHub). With it:

  • go to the (1, 1), line and yank it: Vy
  • paste it 136 times: 136p
  • go to the second column of 1 and mark it vertically: C-vGf)h
  • run the increment: :II
  • read the manual to find out about the other goodies: :help visincr.

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.