17

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!

4 Answers 4

15

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)).

1
  • 4
    Vim golf: qqyypW<c-a>q135@q. Even shorter if you use Y instead of yy. Commented Nov 11, 2015 at 0:16
12

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 (Ctrl-V) 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.

2
  • Successfully tested in Vim 7.4.826 on Debian/sid.
    – Dubu
    Commented Nov 17, 2015 at 13:38
  • Your screencast has disappeared but this method is AWESOME! Thanks.
    – david_nash
    Commented May 10, 2019 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.
1

I'd play with g^a.

Try 137i0^v137kg^a.

1
  • 1
    Welcome to Vi and Vim! I’ve formatted your answer using markdown. It would be even better if you edit to explain how this answers OPs question.
    – D. Ben Knoble
    Commented Dec 8, 2019 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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