vi tricks

Posted: January 30, 2013 in Linux
Tags:

Vi is one of the top-drawer editor. For beginners , it looks pretty
arduos but once we get hands on

it, we can do unimagninable things. Now, we gonna see one of those
magics here.

Map command is used to map the sequence of keys. Consider a situation
where we are doing a

repetattive task.. Instead of typing the same command again and again we
could do a mapping for that sequence and use the single key stroke.

Let me give an example.. Consider the following text.

welcome
to
shrinath's
blog

Now consider i need to change the above text ,such that i can use that
in php something like : echo ‘welcome’; echo ‘to’; ie. i need to add an echo statement before every
line and i need to close the quotes and put semicolon.

Usually , how we will do this. we will go to the first character we will type echo . we will start the quote . then we will move to end of the character . then we will end the quote . then we will put semicolon. We need to do this 5 times. Here we have 5 line. What if there were 50 lines ?

Here mapping does its magic. Now just think of the key sequence we used.

1. 0 - goes to the starting of the line
2. i - we enter into insert mode
3. echo' - we type echo'
4. <ESC> - we type escape to alter from insert to command mode so that we can move to end of the line easily
5. $ - move to the end of the line
6. a - append the text
7. i - move to insert mode
8. '; - close quotes and semicolon
9. <ESC> - again move to command mode so that we can move to the next line
10. j - move to the next line

after step 10 we again start from 1 . instead of that, use the same
sequence and map that to a single key say ‘s’; Go to the command mode (by pressing escape key ) and
type

:map s 0iecho'<ESC>$a';<ESC>j

now the letter s has this sequence . just press s and see the magic. you get the output like this

echo ‘welcome’;
echo ‘to’;
echo ‘shrinath’s’;
echo ‘blog’;

STEPS :
image

image

image

image

Advertisements

Comments are closed.