7

Sometimes I need to insert some similar lines in a file which differ only in a sequence number. For example,

print "func 1";
print "func 2";
print "func 3";
print "func 4";
print "func 5";

Using vim, I end up copy pasting the first line using [yypppp] and then changing the last four lines. This is really slow if you have more lines to insert.

Is there a faster way to do this in vim?


An example of this is:

Initial state

boot();
format();
parse();
compare();
results();
clean();

Final state

print "func 1";
format();
print "func 2";
parse();
print "func 3";
compare();
print "func 4";
results();
print "func 5";
clean();
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Lazer
  • 90,700
  • 113
  • 281
  • 364

3 Answers3

12

Record a macro. Here is the workflow for your particular example:

Copy-paste the first line. Then,

qa       : Start recording macro to register a
yy       : Yank current line
p        : Paste current line in line below
/\d      : Search for start of number (you can skip this command, the next command automagically moves the cursor to the number)
C-A      : Control-A increments the number
q        : Stop recording macro
3@a      : Replay macro 3 times

You can replace 3 with any number to keep generating new print lines with incremented numbers.

For your second example, you can just add

j        : Moves one line down

after the yy command, to get alternating lines of commands and print's.

Chetan
  • 46,743
  • 31
  • 106
  • 145
  • 3
    You don't actually need to do `/[0-9]\+`, VIM Automagically moves the cursor to the number – Hasturkun Oct 21 '10 at 08:25
  • You can replace `/[0-9]\+` with a much better `/\d` (you do not need to get the whole number into a match, you need only to place cursor on a number, so `\+` is an overkill here. `\d` is a shortcut to `[0-9]`. It is faster, but this does not matter here. It also minimizes number of keys that should be pressed.). – ZyX Oct 21 '10 at 15:54
1

You have plugins that do it. For example, visincr. Visually select your column of numbers, and run :I.

Another way to do it is to record a macro. run qx to start recording macro to register x, yiw to yank word under the cursor, j to go one line down, viwp to paste it, CTRLA to increment the new number, q to stop recording, and then @x to replay contents of register x.

Benoit
  • 76,634
  • 23
  • 210
  • 236
0

For this particular case, you could use a macro. There's a good write-up of how to do sequence numbers in this post.

You need to change the example in the post to write out the entire line first and then record a macro that copies the line and updates the counter.

Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317