( modified from: http://www.tc.cornell.edu/Edu/Tutor/Basics/vi/ )
UTK-Math171 - Alexiades

DO NOT PRINT this page

vi Tutor
Now you are reading (a copy of) the file vi_tutor.html, which 
has been loaded on the browser.  To save a copy of the file to 
disk follow these steps:

1. Click on "File" on the browser.  A menu will drop.
2. Click on "Save As...".  A popup will open, displaying 
   your directory and file names.
3. Click on "v" at far right of "Files of type:", and choose "Text Files".
   Change the name of the file to be saved to "vi_tutor.txt"
4. Click on "Save".  In a flash, you got the file to your disk!

  Once you have your own copy of the vi_tutor.txt file, you can
start up vi on that file.  Move the mouse to an open window,
preferably a large one, or open another (xterm) window for the 
vi editing session.

There you are talking to Unix.  Anything you type at the Unix
prompt is interpreted as a Unix command.  One of the most
useful commands is "ls", which lists the names of the files 
in the current directory (see the HOW-TO handout). 

At the Unix prompt, type:  ls   

Do you see "vi_tutor.txt" listed ?  Now type:

   vi vi_tutor.txt     to start up vi on the file vi_tutor.txt

The editor gets a copy of the file and displays its contents
in the xterm so you can edit it.
Remember the two modes of vi ?  You will be in command mode,
so anything you type vi interprets as a command.

You can scroll down and up with the commands:

        Ctrl-F      Scroll forward  a full screen
        Ctrl-B      Scroll backward a full screen

More essential commands are given below.  
Now go to the xterm where you are vi'ing the file "vi_tutor.txt",,
move down to below this point ( Ctrl-F or by pressing j )
and start reading and doing !  
Then get back to Assignment 1 on the browser.

------------------ end of HTML part ------------------


			My Buddy vi
 
vi is the standard Unix text editor.  This tutorial will only give 
the basics of using vi.  There are many web sites on it,
so you are directed to them for more thorough explanations 
(see links on the course page).
 
You should try out the commands as they are presented.  This tutorial 
assumes that you have already copied this file to one of your own 
directories, so that you can vi the file yourself and save any
changes you make.
 
Remember, to move around in the file, you can enter:
 
	Ctrl-F		Scroll forward a full screen
	Ctrl-B		Scroll back    a full screen
 
Try them now.
 
More commands for moving around are given below.
 
 
TERMINAL TYPES WITH vi  ( SKIP AT FIRST READING )
----------------------
 
One of the most common stumbling blocks encountered when using vi is
making sure the system knows what type of terminal you are using or
emulating.  You specify this through the TERM enviroment variable.
Typically, this is set automatically upon login.  But sometimes it is
not, (as when you login via a modem connection).  
 
Under X Windows, the terminal type is xterm.
Vi also works well for terminal type vt100.

To see what TERM is set to, enter AT THE UNIX prompt:
printenv TERM		 (DON'T enter this while in vi).  

If the TERM variable is incorrect, use the setenv command to
change the variable TERM. For example, at the Unix prompt, enter:
 
setenv TERM xterm	 (AT THE UNIX prompt, NOT in vi).  
This sets the TERM variable to xterm.  
Try it !


STARTING & STOPPING vi
----------------------
 
To start editing a file named "taxes", enter: vi taxes
If the file does not exist, it will be created as a blank file.
 
If vi complains about not knowing about your terminal, or your 
screen is messed up, quit out of vi with a
 
:q!   <----(That's 3 seperate characters, colon, q, exclamation)
 
This is a useful emergency exit out of vi. If you get massively 
confused while vi'ing the file, hit the ESCAPE key twice, then 
issue the command above.
Note that this method of exit quits WITHOUT saving changes.

Then, change or set your TERM variable as above to the proper
terminal type.
 
There are several ways to get out. 
   ZZ 	saves and quits the editor (yes, that is 2 capital Z's)
   :wq	write (save) and quit (same as ZZ)
   :q! 	exits without saving, even when changes have been made.
 
 
NOTATION
--------
 
In the commands below, the notation: ctrl-x means to hold down the
CONTROL key while simultaneously pressing the x key.  Also, 
refers to the arrow keys available on some keyboards.  refers
to the carriage return key. ESCAPE or ESC refer to the escape key.  
If your keyboard does not have an ESCAPE key, you can use ctrl-[.
 
 
vi COMMANDS
-----------
 
vi differs from many other editors in that there are two different
modes: command mode and input mode.  When you are in command mode,
all your keystrokes are interpreted as commands and ARE NOT entered
into the file.  While in input mode, all your keystrokes are treated
as input, and ARE entered into the file.  You get from input to
command mode by hitting the ESCAPE key.  You do not need to hit the
return key for most vi commands.  They execute as soon as you enter
the command.
 
TIP: IF YOU ARE NOT SURE WHERE YOU ARE (COMMAND OR INPUT MODE), 
     HIT THE ESCAPE KEY TWICE.  
     THEN, YOU ARE SURE YOU ARE IN COMMAND MODE.
 
You can get from command to input several ways, but first let's 
see how you move around.
 

MOVING AROUND
-------------
 
There are several commands to move around, depending on how far you
want to go.  Remember, you must be in command mode to issue these.
 
Most vi commands can be prefixed by a number, n, that specifies 
that the command should be repeated n times. For example, 5w means 
move 5 words forward.
 

MOVING THE WINDOW UP AND DOWN
-----------------------------
 
ctrl-f	Window moves FORWARD by a screen full.
ctrl-b	Window moves BACK by a screen full.
ctrl-d	Window moves DOWN by half a screen.
ctrl-u	Window moves UP by half a screen.
 
Try them !
 
 
MOVING CURSOR WITHIN THE WINDOW
-------------------------------
	(note: at rest position, your right hand fingers are over 
	 j k l ;   that's why h j k l are used as arrow keys!)
 
 h or 	Moves cursor left one character
 j or 	Moves cursor down one line
 k or 	Moves cursor up one line
 l or 	Moves cursor right one character
 		to beginning of next line

 w			(word) to beginning of next word
 b			(back) to beginning of previous word
 e     			(end)  to end       of current word

 0 (zero)		to beginning of current line
 $			to end of current line

 H			(High) to top of screen
 L			(Low)  to bottom of screen
 
NOTE: IF YOUR ARROW KEYS DON'T WORK AS THEY SHOULD, YOUR TERM 
      VARIABLE MAY BE SET TO AN INCORRECT VALUE.  YOU MAY HAVE 
      TO EXPERIMENT WITH DIFFERENT VALUES.
 

MOVING TO A POSITION OUTSIDE THE CURRENT WINDOW
-----------------------------------------------

G	move to end of file
nG	move to line n 	(so, 1G takes you to begining of file)
:n	move to line n  (so, :35 takes you to line 35)
:.=     tells you the line number of the current line
 
   Try :.=  to see the line number of this line.
   Try going to line 498.  You'll be told how to get back here.
 

SEARCHING
---------
Note: For the searching commands, you have to hit a return to 
execute the command.  Searches are circular.  The search starts 
at the current location and proceeds down or up the file.  If the 
end or beginning of file is reached, the search goes to the 
beginning or end of file and continues from there.  If the search 
makes it back to the location it started from, it stops and lets 
you know it didn't find anything.
Searches are case sensitive!

/stringy        search forward for string stringy
?stringy        search backward for string stringy

If you want to continue searching for the string, you can use the
following commands:

n       continue search in the same direction as the original search
N       continue search in the opposite direction as the original
search

Try searching for the string Gary.  To return to this point search for
the string SEARCHING, which is the name of this section.  Try searching
for the string consisting of your first and last names.  Most likely,
you'll get the "Pattern not found" message.  Note that it is all right
to have spaces in your search strings.


INSERTING TEXT --------------

The following commands will take you from command mode to input mode.
All the characters you type in will be put into your file, until you
hit the ESCAPE key.

i       Insert text immediately before the cursor.  
a       append text immediately after the cursor.  
o       Open a new line immdiately after the current line.  
O       Open a new line immdiately before the current line.
	(Note this is an uppercase o, not a zero)

REMEMBER to hit ESC as soon as you are done entering text !!!

Try inserting another word after dog that's in alphabetical order in 
the line below:
 
apple bat cub dog fox grape
 
Fill in the list of recent presidents below by going to the line 
numbered 3, opening a line after it, and typing in the preceding 
president. Then, go back to line 3, open a line before it, 
then type in the following president.
  (remember to hit ESCAPE when your're done inputting):

1. Bill Clinton
3. Ronald Reagan
5. Gerald Ford
 
 
DELETING TEXT
-------------
 
Text can be deleted by character, word, or line.
 
x	Deletes character under the cursor
dw	Deletes a word (including space after it)
D	Deletes from the cursor until the end of line
dd	Deletes the current line
 
Remember, these and most other commands can take a number as a prefix
to perform multiple actions.  So, 5dd deletes 5 lines.
 
Try these commands out on the following two paragraphs: 
 
     The ls command writes to  standard output the contents of
     each specified  directory or  the name of  each specified
     file, along with  any other information you  ask for with
     the flags.  If you do not specify a file or directory, ls
     displays the contents of the current directory.
 
     By  default, ls  displays all  information in  alphabetic
     order by file name.  
 

REPEATING PREVIOUS COMMAND
---------------------------

. (dot) Repeats the previous command (that altered the buffer)
	So, you don't have to redo an editing command: 
		ESC .   will redo it
	it's a great time saver, remember to use it !
 

CHANGING and REPLACING TEXT
---------------------------

cw 	change word (till ESC).  
	e.g. change red  to  yellow.
R  	replace  (till ESC).     
	e.g. replace from here to here with anything
r	replace single character (no need for ESC),
	e.g. replace 5 with 9.
~	change case of character under cursor
	(lower to upper and upper to lower)
	e.g. MAKE THIS LOWER CASE
	(the best way: move cursor on M, press ~, then .... )
 

UNDOING PREVIOUS COMMANDS
-------------------------
 
Changes can be undone to a certain extent.
 
u	Undoes last change. 
	Note that 2 undo's will undo the undo (nothing changes)
	[this applies to standard vi, but VIM may act differently...]

U	Undoes all changes on a line.  Must be done before changing to
        another line.
 

FIND - CHANGE - REPEAT
----------------------

To change many occurancies of a string, you need to type the change 
only once and use "." (dot).  Combine: search, change, . : 
	/string  cw new ESC  n  .  n  .  n  .
[this is one of the greatest features, extremely useful]

e.g. let's change "book" to "class" in:

	This book is great. A book like this is rare. Love the book.

Move anywhere above the previous line and enter:
/book		cursor will move to 1st "book"
cw class ESC 	first "book" changes to "class"
n		cursor will move to 2nd "book"
.		2nd "book" changes to "class"
n		cursor will move to 3rd "book"
.		3rd "book" changes to "class"

Another way of doing this is described below (substitute command).


CUT & PASTE
-----------
 
When you delete characters, words, or lines, the items are not
immediately gone forever.  The discarded string is put into a buffer
and is available to be placed somewhere else.  The buffer remains
intact until another item is discarded or copied into the buffer.
 
The buffer also holds text you want to copy to another location.  The
following commands will place a copy of the item in the buffer which
can then be placed in other locations.
 
nyy	yanks n lines into the buffer starting at the current line
nyw	yanks n words into the buffer starting at the current word
	(Remember, n represents a number, not the letter "n")
 
The next two commands put the contents of the buffer in the file.
 
p	puts contents after current line or cursor position
P	puts contents before current line or cursor position
 
Since the deletion commands put the discarded text into the buffer,
the p and P commands can be used to place the text elsewhere.
 
Try these cut & paste commannds on the following lines.  Yank or delete
lines or words, then put them somewhere else. Then use . to repeat.
 
This is the 1st line in the bunch.
This is the 2nd line in the bunch.
This is the 3rd line in the bunch.
This is the 4th line in the bunch.
This is the 5th line in the bunch.
This is the 6th line in the bunch.
This is the 7th line in the bunch.
This is the 8th line in the bunch.
This is the 9th line in the bunch.
 

LINE NUMBER COMMANDS
--------------------
Yanking, deleting, putting can be done on a massive scale by using
line numbers.  Internally, vi numbers the lines as 1,2,... so each
line can be referred to by its number, and commands can be applied
to a range of lines.
The current line can be referred to as "." (period), and the last line
can be referred to as "$" (dollar sign).  Relative references can also 
be made by adding or subtracting a number onto a line number.  
For example:
 
1,$	line 1 to end of the file (entire file)
.,$	current line to the end of file
5,.	line 5 to the current line
.,.+5	current line to 5 lines down from current  (relative reference)
.-2,.	2 lines above current line to current line (relative reference)

You can duplicate a range using 'y' (yank) and 'p' (put):

:.,.+3y   yanks from current_line to 3 lines down from current (4 lines)
p         puts them after the cursor (move the cursor before 'p')

You can move a range of lines using 'd' (delete) and 'p' (put):

:.,.+33d   will delete from current_line to 33 lines down from current
p          will put them after the cursor

You can write a range of lines into another file using 'w' (write):

:1,.w newfile	   writes lines 1 through current line into "newfile"
:.,$w newfile	   writes lines from current to last into "newfile"
:13,20w newfile	   writes lines 13 to 20 into "newfile"

 
SEARCH & SUBSTITUTE
-------------------
 
Another important function of any editor is to replace a string with
another one.  The form of the vi command that does this is:
 
:s/string1/string2/		applies to current line only.
:n1,n2s/string1/string2/	applies to lines from n1 to n2
 
Where:
n1,n2 is the range of lines where you want the substitutions to occur. 
 
string1	is the string to be replaced
string2 is the string that replaces string1
 
REMEMBER: The current line is the one with the cursor in it.
 
The substitute command in this form will only change the first
occurence of string1 in the range of lines.  If you want to change
every occurence of string1 in a line, append a g to the end of the
command, as in:
 
:s/string1/string2/g
 
Try the substitute commands out on the lines below. As a first
exercise, try substituting only the first occurence of Mickey in 
each line to Minnie.  Then try changing every occurence of cheese 
to velveeta.  Try using relative references to limit the range of 
lines of the substitutions.
 
Mickey likes to eat cheddar cheese. Mickey also likes swiss cheese.
Goofy will eat a lot more colby cheese than Mickey will.
Donald eats Mickey's feta cheese, but Mickey won't eat Donald's cheese.
 
The DANGER with such massive substitutions is unintended changes
(the same string1 may appear in a context you didn't mean to change...)
The previous FIND-CHANGE-REPEAT method is safer.


WRAPUP
------
 
This tutor should give you enough information to get started.  vi has
many more features.  There are a variety of papers available describing
these additional features, many Unix books cover vi in some depth,
and there are web sites dedicated to vi !  See the Unix-Vi resources
on the main web page.
 
 
 
 
END OF TUTOR
 
 
 
 
 
 
 
 
 
 
 
 
 

To get back to where you were before, go to line 215.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Here are some test strings that are used in the search demos.
Gary thinks Linux is wonderful.
To get back to the searching section, search for the string SEARCHING
You can use either a forward or backward search.











You should be here after executing the G command.