Home » Featured, Unix/Linux

Very useful VI commands handbook

27 July 2009 1,285 views One Comment

Useful Vi editor commands.

If you are using Unix then you must have used the VI editor for text edition. Vi Editor is the best editor in my view. If you have practiced enough and mastered the frequent command then you can understand its power.

I have summarized the basic commands and some useful command one should know to speed up VI editor use. I will not go in to details of how commands work.

There are mainly three modes of commands in VI editor, Insert mode, Command mode and colon mode. Generally insert mode can be bring by pressing i, a, o etc. And Esc is pressed to go back to Command mode. Colon mode can be started by pressing colon “:” in command mode.

Cursor movement:
h : to move cursor 1 position left
j : to move cursor 1 line down
k : to move cursor 1 line up
l : to move cursor 1 position right
G: to move cursor to end of the file (nG can be used to go to nth line in the file)
gg : to move cursor to start of the file
$ : to move cursor to end of the line
^ :to move cursor to beginning of the line.
b : to move cursor to beginning of the current/previous word.
w : to move cursor to beginning of the next word.
e : to move cursor to end of the next word.
f : f is used to find the character. It is used with the character to be found. E.g. fn will find the first n character from the current position.
F : F is same as f but searches character on the reverse direction.

^f : to scroll full page down
^d : to scroll half page down
^u : : to scroll half page up
^b : : to scroll full page up

Can be used with numbers as 10h to move cursor 10 position left.

Deletion of text:
x (dl): to delete the current character under cursor.
dw : to delete the current word.
dd : to delete the current line.
d$ (D) : to delete the text from current position to end of line.
d^ : to delete the text from start of line to current position.
dG : to delete the content below the current position.

Can be used with numbers as 10dd to delete 10 lines.

Replacing the charater:
r : to replace the current character under cursor. Current character is replaced by the immediate typed character.

Copying (yanking):
yy : to copy the current line
yw : to copy the current word

$, ^, G can be used in combination just as used above with d.
Can be used with numbers as 10yy to copy 10 lines.

In fact, When we use d commands for deletion, it also copies the deleted contents.

Paste the copied content:

p : is used to paste the content copied by y command or deleted by d command at current cursor position.

Commands to get in Insert mode:

i : to start editing from before current cursor position
a : to start editing from after current cursor position
o : A new line is added below the current line and cursor is now placed to start of new line.
O : A new line is added above the current line and cursor is now placed to start of new line.
s : deletes the character at current cursor position and edition is started from there.

Searching the pattern:

Mainly / and ? are used for pattern matching in vi editor. To search the string or word , press / or ? in command mode and type the pattern to be searched and press enter.
Both work in the same way except the direction of the search. / searches the pattern in forward direction and ? searches the pattern in reverse direction. When command is executed all found occurrence of pattern can be traverse by n and N. In case of / was used to search the pattern then n is used to move to next occurrence and N is used to move to previous occurrence. For ? n and N works in opposite manner.

Wild card characters can be used to enhance the search, e.g.

/ABC$ can be used to search string ABC at the end of line.

/^ABC can be used to search string ABC at the start of line.

* can be used to search the current word. This can be very handy to use.

Indenting the code:

<< : is used to shift the current line to left by one shift width
>> : is used to shift the current line to right by one shift width

shift width can be specifying by :set sw=4 or it can be set in .vimrc file (will cover later).

Parenthesis matching:
% : if the cursor is on the parenthesis ( (,{,[ ) then it will jump to matching parenthesis.

Visual mode:
Some times there is a case when you want to copy large number of lines and you do not know the number of lines, Visual mode can rescue you. Press v to enter the visual mode. Move the cursor whatever text you want to select. Selected text is highlighted. Press y to copy the selected text and paste it wherever you want it.

Buffers in vi editor:
Vi editor uses buffer to store different copied content (like clipboard in windows). There are two types of buffers, temporary buffer and lettered buffer. By default by temporary buffer is used by vi editor so each time you copy buffer is overwritten.
Lettered buffer are used in case you want to paste the more then one content frequently.

Lettered buffer are denoted by “ and followed by alphabet. E.g. “a means buffer a. Total 26 different buffers can be used (a-z).

“ayy : to copy a line to buffer a
“ap : to paste the content of buffer a
“a3yy : to copy 3 lines to buffer a

Different combination of copy paste can be used with buffers also.
If same buffer is used to store the content then previous value is overwritten. Capital letters can be used if you want to amend the content, e.g.

“Ayy : Amends to buffer a.

Copy till marked position:

This is almost same way of copying text as visual mode. In this we first mark the position from where we want to copy and then move to the position till we want to copy.

ma : marks current position as a
y’a : copy from current position to marked position a

Colon mode commands:

:q : to quit the file
:q! : to forcefully quit the file (changes will be lost)
:w : write the file
:wq : write and quit the file
:r filename : reads the specified file.
:h : to display help of vi editor (specify the help file to read by :h helpfilename)
:n : no move to next file if more then one files are open.
:s : to search and replace by pattern matching (substitution)
syntax for substitution is : :ranges/pattern/pattern/options
Range : this can be provided as comma separated line numbers e.g. :10,20s/ptn1/ptn2/g. This will search from line 10 to 20 and replace ptn1 with ptn2

% can be provided as range if you want to search in entire file.

Pattern : Pattern is basically a string. Variety of regular expressions can be used to specify the pattern.

Options: I don’t know much options to use here but mainly I use g and c/

g : to replace all occurrences of the pattern in a line. If it is not specified then only first occurrence is replaced.
c : to confirm the change.

Some example of substitute command,

:10,20s/aaa/bbb replaces first occurrences of aaa from line 10 to 20 with bbb.
:10,20s/aaa/bbb/g replaces all occurrences of aaa from line 10 to 20 with bbb.
:10,20s/aaa/bbb/gc replaces all occurrences of aaa from line 10 to 20 with bbb after confirmation of the change.
:%s/aaa/bbb/g replaces all occurrences of aaa with bbb in entire file.
:%/^aaa/bbb/g replaces all occurrences of aaa which are in start of line with bbb.
:%/$/bbb/g replaces end of each line with bbb.

Options from colon mode
:set all Display all options
:set Display current settings of options
:set nooption Unset option
:set ai Set Auto Indentation during text entry
:set ic Set Ignore Case during searches
:set nu Show line Numbers
:set sm Show Matching ( or { when ) or } is entered
:set wm=10 Set Wrap Margin 10 spaces from right edge of screen

This all options are only valid for the current session of vi, they are lost as soon as you exit the editor. To set your desired options by default, .vimrc file is used.

Create .vimrc file in your home directory and specify all options you want here. Now each time you open the vi editor your favourite options are set.

Abbreviations:

This is a cool feature provided by vi editor. You can provide an abbreviation for frequently used word and make you like easier. Take an example that I have to enter my full name many times in my files so I can create an short abbreviation for it and use it everywhere. Vi editor will automatically replace it with my full name.

Syntax is
:ab fn Nikunj Lodhia

Now in insert mode when I type fn and then press space or enter then fn is changed to Nikunj Lodhia (I use this feature a lot).
Frequently used abbreviations can be set in .vimrc file.

:una is used to remove the abbreviations e.g. :una fn

Auto Complete:

Yes, vim has also auto complete feature. You have to be in insert mode to use this feature.

^n : This will auto complete the current word with matching word. If more then one matching words are found then press ^n again to move to next match.
^p : it works same but in reverse direction.

Suppose in your file you have word myVariable. In insert mode type myV and press ^n, vi will change it to myVariable. (this is also a cool feature to use)

Repeating the insert:

If you press CTRL-A, the editor inserts the text you typed the last time you
were in Insert mode.
Assume, for example, that you have a file that begins with the following:

"file.h"
/* Main program begins */

You edit this file by inserting "#include " at the beginning of the first
line:

#include "file.h"
/* Main program begins */

You go down to the beginning of the next line using the commands "j^". You
now start to insert a new "#include" line. So you type:

i CTRL-A

The result is as follows:

#include "file.h"
#include /* Main program begins */

The "#include " was inserted because CTRL-A inserts the text of the previous
insert. Now you type "main.h" to finish the line:

#include "file.h"
#include "main.h"
/* Main program begins */

The CTRL-@ command does a CTRL-A and then exits Insert mode. That's a quick
way of doing exactly the same insertion again.

completing file names

Let's take CTRL-X CTRL-F as an example. This will find file names. It scans
the current directory for files and displays each one that matches the word in
front of the cursor.
Suppose, for example, that you have the following files in the current
directory:

main.c sub_count.c sub_done.c sub_exit.c

Now enter Insert mode and start typing:

The exit code is in the file sub

At this point, you enter the command CTRL-X CTRL-F. Vim now completes the
current word "sub" by looking at the files in the current directory. The
first match is sub_count.c. This is not the one you want, so you match the
next file by typing CTRL-N. This match is sub_done.c. Typing CTRL-N again
takes you to sub_exit.c. The results:

The exit code is in the file sub_exit.c

If the file name starts with / (Unix) or C:\ (MS-Windows) you can find all
files in the file system. For example, type "/u" and CTRL-X CTRL-F. This
will match "/usr" (this is on Unix):
the file is found in /usr/

If you now press CTRL-N you go back to "/u". Instead, to accept the "/usr/"
and go one directory level deeper, use CTRL-X CTRL-F again:

the file is found in /usr/X11R6/

The results depend on what is found in your file system, of course. The
matches are sorted alphabetically.

Set max characters in one line

Vi editor also provides a way to set maximum characters in one line. In many project there is a requirement that not more that 80 characters should be in one line. It can be done by,

:set textwidth=xx

Here xx is number of characters. When you insert characters more then specified in
textwidth, Vi editor automatically creates a new line for it.

Alignment of text

Yes you are right alignment of text is available in Vi editor also. This could be least known feature to users hence many users don’t know about it. It will align the text in center, right or left side.

:{range}center [width]
:{range}right [width]
:{range}left [width]

Here range is standard range used in vi editor commands like `s`. Width is optional argument which specifies the width in which text will be aligned. If it is not specified then textwidth is used instead.

Justifying text

Vim has no built-in way of justifying text. However, there is a neat macro
package that does the job. To use this package, execute the following
command:

:runtime macros/justify.vim

This Vim script file defines a new visual command “_j”. To justify a block of
text, highlight the text in Visual mode and then execute “_j”.

Making change in many files

Suppose you have a variable called “x_cnt” and you want to change it to
“x_counter”. This variable is used in several of your C files. You need to
change it in all files. This is how you do it.
Put all the relevant files in the argument list:

:args *.c

This finds all C files and edits the first one. Now you can perform a
substitution command on all these files:

:argdo %s/\/x_counter/ge | update

The “:argdo” command takes an argument that is another command. That command
will be executed on all files in the argument list.
The “%s” substitute command that follows works on all lines. It finds the
word “x_cnt” with “\“. The “\<" and "\>” are used to match the whole
word only, and not “px_cnt” or “x_cnt2″.
The flags for the substitute command include “g” to replace all occurrences
of “x_cnt” in the same line. The “e” flag is used to avoid an error message
when “x_cnt” does not appear in the file. Otherwise “:argdo” would abort on
the first file where “x_cnt” was not found.
The “|” separates two commands. The following “update” command writes the
file only if it was changed. If no “x_cnt” was changed to “x_counter” nothing
happens.

There is also the “:windo” command, which executes its argument in all
windows. And “:bufdo” executes its argument on all buffers. Be careful with
this, because you might have more files in the buffer list than you think.
Check this with the “:buffers” command (or “:ls”).

Maping the key:

:map keys sequences

e.g. map ^N iNikunj

now when I press ^N then I will be in insert mode and Nikunj will be added before the cursor

Miscellaneous commands:

^a : if the cursor is on a number then it will be incremented by 1.
^x : if the cursor is on a number then it will be decremented by 1.
gd : move to the declaration of the variable under cursor. (should be locally declared)
. : repeat last command
u : undo last change
J : join next line to end of current line
~: switch the case of character
^g : show current file name and status
:! : to run shell commands e.g. :!ls

These are only summary of the commands. I will improve the details of commands as soon as I get time. Hope this page is helpful to you.

Be Sociable, Share!
(1 votes, average: 0.00 out of 5)
Loading ... Loading ...

One Comment »

  • Debt Settlement Program said:

    charming post. simply one detail where I bicker with it. I am emailing you in detail.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.