Vi

Introduction
This text is a copy with some modifications of the Learning the vi editor. All text is available under the terms of the GNU Free Documentation License.

Links

 * Learning the vi editor
 * http://www.texteditors.org
 * http://thomer.com/vi/vi.html
 * An introduction to the vi editor
 * Functions of VI editor
 * vi Editor Basics

Overview
vi is a powerful editor that is ubiquitous amongst Unix and Unix-like operating systems, but is available on many other operating systems, even on MS-DOS, Windows and the Macintosh. If not the original vi, there is usually at least a good clone available that runs on your system. Even if you use another editor you must have a passing knowledge of vi as an administrator. Sometimes vi is the only editor available when your computer crashes leaving a minimal system for you to repair.

vi, pronounced like 'vee eye', was originally written by Bill Joy for BSD Unix in Berkeley in 1976 and became quickly part of many vendor-specific versions of the (at that time) original AT&T Unix. It was later directly added to AT&T's System V Unix, too. Bill Joy later went on to co-found Sun Microsystems, and became the company's Chief Scientist at that time. vi stands for visual and was an enormous improvement of the classic Unix editor called ed. ed is a line-editor. If you are still familiar with MS-DOS, then you may know the MS-DOS edlin editor. ed is similar, although more powerful than edlin, which doesn't mean much.

vi also has a line-mode, called ex. In fact, one can argue that the program is indeed two editors in one, one editor called vi, another called ex. It is possible to switch between line and visual mode during editing. It is also possible to choose the mode during startup. However, pure usage of ex is rare. The visual mode is the prevailing mode.

Although vi stands for visual, classic vi is mainly operated via the character keys, and not via the mouse or the cursor keys. Once you are used to this, it becomes extremely convenient, because there is less movement of the hands to the cursor keys or mouse involved.

vi also served as a kind of incubator for Unix's terminal control capabilities. Because of vi's need to control the terminal and the many different types of terminals at that time, the termcap (terminal-capabilities) database was introduced (later replaced with the more flexible terminfo database). vi's internal high-level screen control library was later separated, and became curses - the Unix standard library for CRT screen handling.

Conventions

 * 
 * Indicates that the Escape (Esc) key on your keyboard should be pressed.


 * 
 * Indicates that the Return (Enter) key should be pressed.


 * 
 * Indicates that the Tabulator key should be pressed


 * ^x
 * Indicates that the Control key and the 'x' key should be pressed simultaneously. 'x' can be almost any other key on your keyboard.

unix-command(section)
 * Sometimes references to Unix commands are used in this book. On first occurrence such a name of a command is written in the typical Unix style. This style consists of the command's name followed by the section of the manual pages in which the command description can be found, in brackets. E.g. sed(1) refers to Unix's sed command which is usually documented in section 1 of the Unix manual pages (sed is the Unix stream editor; a tool for manipulating text without user interaction).

Getting vi if you don't have it already
If you're running a Unix system, or a Unix-like system (for simplicity from now on we will refer to both as a "Unix system"), such as a BSD or Linux distribution, or even Mac OS X, you're sure to have vi or one of its variants on your system.

If you're running Windows, you can get a version of vi called "vim" or "elvis". If you're on an older Mac OS (pre-OS X) system, you can get MacVim Classic here.

Noted vi variants
As mentioned, vi has a number of variants. They have been created because vi was only available on rather expensive Unix operating systems. Although vi itself, as well as nvi was created in Berkeley for the free BSD Unix variant, usage of BSD Unix required an original AT&T Unix license (this has later changed, see below). Original vi, for example, used code from AT&T's ed(1) editor.

Over time, BSD replaced many of the original AT&T code up to the point where today there is no such code anymore in BSD, and an original Unix license is no longer needed. As part of the effort to replace all AT&T code in BSD, Keith Bostic undertook the work to create a clone of vi that was free of AT&T code, called nvi. nvi then became BSD's standard vi instead of the original vi. Another vi clone is Elvis, which was written by Steve Kirkendal.

Over time, nvi was enhanced – for example, supporting multiple windows – but originally it was not supposed to be an enhancement, 'just' a pure clone.

BSD's original vi (with the ed code inside) lives on as the vi which is distributed with System V Unix, because AT&T decided a long time ago to take it from BSD and add it to the official Unix. Of course AT&T didn't have a problem with an AT&T Unix license, so they probably never replaced the ed code inside the original vi.

Yet, some find nvi still to be too minimal, and so vim was born. vim (vi-improved), is another effort to extend vi's capabilities. Unlike nvi, vim goes even further to extend vi's capabilities. However some find that vim is often too much. vim comes in two variants, a text-only version, and a GUI version, the latter is called gvim.

Other vi clones are the already mentioned elvis and stevie. These clones were born in the CP/M and home computer area to bring the editor to these platforms, too. Of course, they were later ported to MS-DOS and Windows. These days, however, vim seems to be the prevailing vi-clone on free/open platforms and proprietary platforms as well.

You should choose the version you feel most comfortable with – if you have an editor you feel displeased with, it will affect your productivity.

Starting the editor
If you are running a Unix system, you can start up vi by typing

vi

at the command line. If you are running X, with a desktop like GNOME, KDE, CDE/Motif or OpenLook you may have a launcher button handy to start the editor - if you have such a setup, you can just click the icon.

If you are running Windows or DOS with elvis, you can start up the Windows editor by double-clicking "winelvis.exe", or in DOS, you can start the editor by typing in "elvis" at the command line.

You will be greeted with a screen similar to:

~ ~ ~ ~ ~ ~ "No File"

Quitting the editor
To quit for now, press the Escape key (the editor should beep), then enter the three characters and press :

:q!

Just before you type the final  the screen will look similar to

~ ~ ~ ~ ~ ~ :q!

You should be dropped back to your operating system (or, rather, the shell from where you started).

There are other ways to quit, e.g. pressing (shift+zz) will save any unsaved work and quit the editor. Typing will always save, even if there are no unsaved changes, and then quit the editor. will write if there are no unsaved changes, and it will quit. and requires that you had previously provided a file name, so it will not work for the above simple example. Typing will quit if there have been no changes made; if changes have been made, vi will print a warning similar to "No write since last change".

Don't worry
Many first time vi users stop at this point, and never touch vi again. If you tried to enter some text after you started, you will most likely have been greeted with a series of beeps and rather erratic behavior. Don't worry. This is perfectly normal for vi, and the editor is not broken. You will soon see why this is normal vi behaviour.

Continue
Now that you know how to start the editor and quit it, let's move on to getting things done in vi.

Basic tasks
Now that we know how to invoke the editor and quit it, we can get acquainted with how to use the editor.

Alternatively, you can use the ViM tutor which comes with many modern vim distributions. It contains, essentially the same information as the text below. You can invoke the tutor by entering vimtutor at your shell.

vi is a modal editor
The vi editor can do two things:
 * accept a command, such as deleting a line
 * accept text, written by you

In the vi editor, each of these tasks is achieved by putting the editor into a particular mode of operation (normally just called a mode). When you wish to give vi a command, you enter command mode, and when you want to enter text, you enter insert mode. We'll cover how to do this below.

It is important to set the correct mode before you begin writing, but this is simple to do. When you first start vi, it is automatically in command mode.

Entering text
Entering text is the most basic task an editor can do! From command mode (in which the editor starts), press to enter insert mode, and you can begin typing. You can use the key to correct mistakes you make. If you make a mistake after a few sentences, leave these errors for now, we will look at correcting them later. To leave insert mode once you're done typing, and return to command mode, press the key on your keyboard (or type ).

Exercise
Let's have an exercise:


 * 1) Start the editor.
 * 2) Enter insert mode.
 * 3) Type some text
 * 4) Return to command mode.
 * 5) Quit the editor.

Solution

 * 1) We can start the editor as in the previous section.
 * 2) Since the editor starts in command mode, we must press the  key before we can start typing.
 * 3) You can make some text up yourself!
 * 4) Press the Escape key.
 * 5) If you want to quit the editor, you need to be in command mode. Since pressing Escape puts you in command mode, you can just use the method in the previous section to exit: type

Command mode
Command mode allows you to perform many useful tasks within vi.

Moving around
Say you have been writing for some time, and have forgotten something. Pressing, erasing previous work is not the best solution! We would like to move around the document freely, moving the cursor.

We can move around in the editor by first entering command mode, and then using the, , , and keys.


 * Note: your arrow keys may be set up to work, and you can use them if you like, but for proficiency and for advanced work later, you should learn to use the letter keys.


 * The key, in command mode, moves the cursor one character left.
 * The key, in command mode, moves the cursor one character down.
 * The key, in command mode, moves the cursor one character up.
 * The key, in command mode, moves the cursor one character right.

If you have trouble remembering this, keep in mind that is leftmost, the letter goes down below the line, the letter pokes up above the line, and the  key is rightmost. (J also resembles an arrow pointing downward, if you squint a bit.)

After you have moved the cursor using those keys, you can enter insert mode again by pressing. When you do this, you insert text at the cursor, inserting text between the character to the left of the cursor and the current position of the cursor. Let's practice this in an exercise.

Exercise
You can repeat this exercise with your own sentences. Make sure you are proficient doing this before you continue.


 * 1) Start the editor.
 * 2) Enter the text: "The quick fox jumps over the dog"
 * 3) Insert the word "brown" between "quick" and "fox".
 * 4) Insert the world "lazy" between "the" and "dog".
 * 5) Quit the editor.

Solution

 * 1) Use the method in the previous section.
 * 2) Press, then enter The quick fox jumps over the dog normally.
 * 3) Press, then press  until the cursor is at the letter "f" of "fox". Press , and then type "brown ".
 * 4) Press, then press  until the cursor is at the letter "d". Press , and then type "lazy ".
 * 5) Press  again, then type.

More on movement
Using, , , and is ok, but vi understands more than rows and columns. These are some commands that move by text objects:
 * moves forward to the beginning of the next word.
 * moves backwards to the beginning of the previous word.
 * and move by sentences, either backward or forward.
 * {{keys|{}} and move by paragraphs.

Deleting things
If you have made a mistake after a few lines, for instance, pressing until you have erased the mistake and starting again isn't always the best solution. We need a method of deleting mistakes that happen in the normal course of editing.

vi allows you several methods of deleting text, based on how much you want to remove. Now that you are familiar with moving around, once you've moved the cursor to where your error is:
 * the key deletes one character
 * pressing deletes one word.
 * pressing deletes one line

Exercise
From now on, we will omit the steps for you to start and quit the editor - you should be already familiar with those.


 * 1) Enter the following text: Sad I been here, I wouldnt ever ever leave.</tt>
 * 2) Change the word "Sad" to "Had".
 * 3) Add an apostrophe after "wouldn".
 * 4) Delete the extra "ever".
 * 5) Delete the line.

Solution

 * 1) Type the text normally. (You should already be familiar with entering insert mode and leaving it.)
 * 2) Enter command mode, use  to get to the start of the line, and then press  to delete the S. Press  to insert the H, then leave insert mode by pressing Escape.
 * 3) Now position the cursor on the t, and press  to insert the " ' ". Leave insert mode.
 * 4) Position the cursor over the first "e" in the word "ever" (choose whichever one you like). Type  to delete the word.
 * 5) Type  to remove the entire line.

Making your work easier
Currently, you should by now know the rudiments of using vi</tt>. However, to really make vi</tt> work for you, it may be helpful to know the following to make your work easier for you.

More on commands
Say you are editing a document, and you wish to delete ten lines - as of now, the only way to do this is to enter ten times. Or if you want to delete seven characters exactly - you would have to enter seven times. There must be a better way!

Undo
To undo the last modification type.

Repetition
Fortunately, vi lets you augment most of the commands in case you want to repeat that command a certain number of times. This is done by typing in the number of times you want that command repeated, followed by the command.

So, if you want to delete ten lines, you would type. Or if you want to delete seven characters, you would type.

You can also repeat the last action done by typing (this is a single period keystroke), the single-repeat operation over the location you want to repeat the previous operation.

So if you wanted to repeat the deletion the ten lines in the previous example, you could repeatedly press to perform this operation over and over again.

Exercise
1. Type the sentence Good morning Doctor, how are you today?</tt>. Delete "Good morning".

2. Now using the single-repeat operation delete "how are".

Motion
vi allows you greater flexibility over motion as well. There are a few commands to allow you to quickly jump around your document, such as :
 * moves to the immediate beginning of the line
 * moves to the immediate end of the line
 * moves to the first non-whitespace character of the line

acts in the following way, if the line was hello how are you</tt> and your cursor is on the u, if you would enter, the cursor would be upon the h.

Furthermore, the command allows you to jump directly to some pattern in the file. For example, if you're looking for the next occurrence of the word "pomegranate" in your text, if you hit, then type in pomegranate (you need not enter insert mode) and hit enter, the cursor will jump to the next occurrence of the word, if it exists. If you want to search backwards, you would perform the same procedure, but use the command. To repeat either search, enter, , or alternatively, type or  and hit Enter.

Commands and motion
We know now that vi lets you enter a number to specify how many times to do something. Consider this example now: you want to delete everything after a certain point on a line - you could enter for each word from the cursor position to the end of the line, or hold down, but these are cumbersome examples. vi thankfully lets you do something much faster.

With certain commands, vi allows you to specify a position, using the methods in the previous sections. The position is specified after the command. For example, to delete up to the end of the line, you would enter.

Other examples:
 * will delete until the next semicolon (This is helpful in languages like C and perl that use semicolons to finish statements).
 * to delete the next two paragraphs.
 * to delete the previous four words (alternatively, you could enter ).

Copying and Pasting
Copying and pasting tasks are done with three keys, (for "yank"),  (for "delete"), and  (for "paste"). In general, you type or  to tell vi that you're at the position where you want to start yanking or deleting some text. Then you need to tell vi where to stop, using cursor movement or other commands.

A Word
To delete a single word, move your cursor to the first letter, then type. To yank a single word, move your cursor to the first letter, then type.

Other Methods
Move to the character past the last letter and type.

To delete a word like "can't", which has an apostrophe, move to the first character and type. Note the capital W. This tells vi to go all the way to the first whitespace character after the word.

Likewise, try.

A Line
To delete a single line, type.

Other Amounts
One of the great things about vi is that it lets you select a bunch of text without having to move your hand to your mouse.

Type. This will mark the current position that your cursor is at. You can go back to this position anytime you want from now on by typing. (<TT>`a</TT> means "move to the character that has been marked as a")

Now move to some other position. Type. This will delete everything from the current position to the position you marked as a.

To the next occurrence of a pattern
This is particularly useful when editing HTML files with d/&lt;.

Adjusting the Screen
vi, as a visual screen-oriented editor has a number of useful commands to redraw or adjust the screen in case you find yourself somewhere where you don't want to be.

If you run in a Unix shell, it is possible that some background process writes to the same terminal. This will disturb vi's screen layout. In order to force vi to redraw the complete screen, press (Control-L) or  (Control-R). Both commands do the same.

If you want to adjust what is currently displayed, then the command is rather useful. It's a kind of Swiss army knife, and has a rather complex syntax:

[/pattern/][m][n](<CR>|.|-)

([ ... ] denotes optional items, (...|...) denotes alternatives)

Before we explain the syntax in detail, here are some common applications of the command:

Scroll the screen so the current line becomes the middle line of the screen. The cursor remains on that line:

Scroll the screen so the current line becomes the top line on the screen:

Scroll the screen, so the current line becomes the bottom line of the screen

If a /pattern/</tt> or a number m is given the cursor is moved further after the adjustment. /pattern/</tt> indicates to move the cursor to the first match of that pattern. m indicates to move the cursor to the mth line on the screen. So, for example,

/while/z<CR></tt>

would first scroll the screen so the current line becomes the top line on the screen, and then move the cursor to the first 'while' in the text from that position on.

The number n is a rather obscure parameter. If provided, it tells vi to behave as if the screen is just n lines high. The result is that only n number of lines are adjusted, and the rest of the screen is either ignored or cleared, presumably useful on slow terminals to avoid redrawing the screen unneccessarily.