Skip to main content

Tips on Using VI Editor (continued)

· 3 min read

The most attractive feature that VI has to offer is the block visual mode. It is amazingly powerful, especially for those who do coding. With it you can add characters to or remove characters a block of text in a column fashion. For example, you can add characters to a block of text (Figure 1) instantly (Figure 2).

Figure 1

Figure 2

Of course, with power comes complexity. It's something meant for users whose keyboard (shortcut) dexterity surpasses that of the mouse.

Inserting

To illustrate how to use the function, I shall use a programming example. For instance, in a JavaScript function, I declare the variables as shown in Figure 1 above.

After typing the code, then I realise that I have to add the "var" keyword in front of all the variables. A find-and-replace operation won't do since there's nothing common among these variables.

With VI, you can achieve the effect easily by using the block visual mode.

Enter into this mode by first positioning the cursor at the first character of the first line then press CTL-v

You will see that the cursor changes to a rectangular cursor. This cursor can be moved about using the same navigation keys in command mode (arrow keys or h, j, k, l).

With the cursor at the first position of the first line, press the j key (or the down arrow key) to move the selection to the last line. (Figure 3)

Figure 3

Next type I (uppercase i) to insert text. You will see that the selection disappears and the text cursor comes back. Now type "var " and press the escape key. (Esc) After a short delay, you will be able to see that all the lines will have the word "var " added at the front. Handy, isn't it?

Deleting

Say you want to remove the fourth to seventh characters from several consecutive lines.

Enter into the visual block mode as described above, only this time place the character at the fourth character of the first line and move to the seventh character of the last line. You will see the desired block of text highlighted. (Figure 4)

Figure 4

Now, instead of using I, type X (uppercase x) and the characters will be removed from block immediately. Cool?

Replacing

What if you want to replace the words? Select the visual block (of the words you want replaced) and type 'c' (lowercase C). The cursor will change to a normal text cursor. Type the word you want. Press Esc key. Voila!