Wednesday, September 1, 2010

Some copying tips

So we all know how assignments are done. One guy faithfully does the whole thing and the rest copy it and change sentences of the form "Let X be a subset of Y" to "Let Y be a superset of X", etc. Now, very often, you will have to make the same kind of changes several times. Here are some tips on how you can do it efficiently using vim.

We'll deal with 2 examples, each of which use many useful commands.

I)

Suppose I want to change (A) to (B)
(A)
printf("%s is a X\n");
printf("%s is a Y\n");
printf("%s is a Z\n");

(B)
printf("X : %s\n");
printf("Y : %s\n");
printf("Z : %s\n");

What we will do here is to make the changes in the first line and store it in something called a macro. Once you are done, just execute the macro in the other lines.

Steps :
Start in escape mode. You should be at the beginning of the first line when you start.
1. qa : q starts recording the macro. It takes an argument which is the register in which you have to store it. Here we're using 'a'. You can use any letter as the macro.
2. f% : f searches for a character in the same line, starting from the current position. Here we search for '%' to go to that position.
3. d4w : d stands for delete, w for word. Delete 4 words.
4. f\ : Move to the position \. (We want to start editing there).
5. Go to insert mode and start typing normally (add the " : %s"). The recording is still going on.
6. j0 : Move to the next line. 0 moves to the beginning of the line (we want this so that the search for % the next time works properly.)
7. q : Stop recording.

Now your macro is ready in the register a.
8. 2@a : Execute the macro 2 times.

There you go, (A) is changed to (B). Of course, this will be feasible only if you have a large number of lines to do this. The individual commands should be useful even otherwise.

II)

Suppose you are editing an html file where you want to give a drop down box of 30 values as follows.

<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>

and so on until 30.

Steps :
Start in escape mode. Type the first line normally. You should be at the beginning of the first line when you start.
1. qa : start
2. yy : copy the entire line
3. p : paste the line
4. f" : move to "
5. l : move left once.
6. Ctrl-A : This increases the number under the cursor by 1.
7. f : move to the next space.
8. Ctrl-A
9. q

Now 28@a should fill everything upto 30.

No comments:

Post a Comment