Enterprise Software

Why I love vi

The battle of the Linux text editors rages on. In this Daily Drill Down, Judith Samson gives you her reasons for choosing vi.


“Vi is small, fast, and easy to use. Emacs is huge, slow, and easy to use.”—Scott McMahan

“Emacs is a hideous monstrosity, but a functional one. On the other hand, vi is a masterpiece of elegance. Sort of like a Swiss Army knife versus a rapier.”—from The Cult of vi Web site

Like UNIX, the visual editor, vi, takes about five minutes to learn and a lifetime to master. While vi is simple, it’s more versatile and powerful than the most powerful word processor. It's elegant, yet it can be maddeningly frustrating to the uninitiated. Although it fits on a floppy disk, it can be your most powerful tool for administration, programming, word processing, and poetry writing.

The vi/Emacs argument is an old one, and groans may be resounding all over cyberspace as people read the title of this Daily Drill Down, but there are valid reasons for re-airing the argument. The most important reason for readdressing the editor wars is that with the rise of Linux, er, GNU/Linux, thousands of new UNIX acolytes are created every day. Those who have already traveled the path have a responsibility to share their wisdom and experience so that the newbies might avoid the pitfalls and perils that lie before them. One of those pitfalls is the idea that you can use UNIX for any length of time without knowing how to use vi.

Four attributes
The considerable virtues of vi can be boiled down to four attributes:
  • Vi is simple.
  • Vi is small.
  • Vi is comprehensive.
  • Vi is standard.

Let’s look at each of these attributes in detail.

Simple
Vi is a tool that does what it does and nothing else. It doesn't try to be an interpreter, an e-mail client, or anything but what it is—an extraordinarily powerful text editor. But in its simplicity lies its power. You can do anything, absolutely anything, with vi. You can use it to write C programs, Scheme, C++, Lisp, Perl, python, GTK, HTML, SGML, Tex, and even Microsoft Word documents, if you know the codes. You can create a one-line script in it or manipulate thousands of lines of data. Vi is meant to be used with other tools to accomplish tasks. It does not try to be all things to all people. It is what it is. It is vi.

Once you get a few commands down, it is simple to understand and to use, unlike its chief rival, [Esc][Meta][Alt][Ctrl][Shift], or Emacs.

Small
If you run into problems and have to edit files when booting your system from a floppy, vi fits easily on your boot floppy. Emacs does not. Vi starts up fast and works fast; there’s no interminable wait for vi to start up or complete a task.

Comprehensive
The biggest advantage of vi is that you can learn no other editor in your entire UNIX career and still do just fine. It would be difficult indeed to try to accomplish some tasks without knowing how to use vi. It would be nothing short of tragic to start your Linux experience knowing only gEdit or Kwrite. If you know how to use only graphical editors, pay especially careful attention. If you don't know how to use a text-interface editor, the first time your X server crashes and won't restart, you’ll be in serious trouble.

Standard
Vi is the standard text editor across virtually all UNIX systems. That means that no matter where you go, no matter whose system or what flavor of UNIX you use, there is your old friend vi, ready to do your bidding in almost exactly the same way. With only minor differences, vi uses the same commands and the same environment on every UNIX machine.

Although this point may be a bit too whimsical for some, vi is traditional. It has a history. Somehow it's comforting to use a tool that has been around in pretty much the same guise since the ’70s. If Rear Admiral Grace Hopper were to rise from the grave tomorrow and wander on over to Stanford, she could log in to a Slackware machine, open up vi, and start typing away.

Vi is also wonderfully portable. Vi clones are available on all Unices, DOS, Windows 9x/NT, Macintosh, and many other systems.

Disadvantage
To be fair, I must mention at least one disadvantage. Vi is not terribly intuitive—at first. Once you get into the mind-set, however, you'll wonder what was so difficult at the beginning.

Using vi
This Daily Drill Down will cover just the basics of using vi. There are many possible commands and combinations. In fact, books have been written on vi, including Learning the vi Editor, by Linda Lamb and Arnold Robbins (O'Reilly, 1998).

Fortunately, with just a few basic commands and concepts, you can get started with vi after about 10 minutes of study.

Starting a vi session
To start vi, enter vi at a shell prompt. Vi opens with an empty file. You can also type:
vi <newfilename>

to open vi to a new file. Be sure to include the entire pathname of the new file, unless you are already in the directory where you want the new file to go.

To open vi to edit an existing file, type:
vi <existing_filename>

This is important to remember, because if you want to open an existing file and you misspell the filename or get the path wrong, vi will create a new file for you named whatever you typed. If you try to open a file with vi that is actually a directory, a new file will be opened. Some flavors of vi, such as vim, will warn you that the file you are trying to open is actually a directory, but others will just create a file with no error message at all.

Vi does all its editing in a buffer. When you initiate a vi session, one of two things happens:
  • When you open an existing file, a copy of the file is placed in a buffer in /tmp or some other temporary directory.
  • If the file is new, an empty buffer is opened for the session.

A new file in vi looks like Figure A. The name of the new file appears at the bottom of the page. The tildes signify empty lines in the editor. The tildes are important, because a blank line that you create as a blank line isn't really blank—it contains the character for blank.

Figure A
A line with a tilde is truly empty and contains no characters.


Modes
Many people get frustrated by vi at the beginning because of its two modes. Admittedly, it’s difficult to tell which mode you're in since there are often no indicators. Some flavors of vi, however, do have a message at the bottom of the screen to tell you.

The two modes of operation are:
  • Command mode
  • Text mode

Some people divide command mode into two submodes:
  • Visual command mode
  • Colon command mode

In visual command mode, the keys on the keyboard, including the [Ctrl] keys, give directions to vi to do something. Colon commands give directives to vi concerning the entire file. In text mode, the keys on the keyboard are used to add text to the file.

Command mode
The vi editor normally starts in visual command mode. When you're in command mode, your keystrokes are actually commands to the vi editor. Rather than printing the letter or symbol that you typed to the page, vi either does whatever command that keystroke represents or does nothing if the keystroke doesn't represent a command.

To enter colon command mode, enter a colon (:) followed by the command. After vi executes the command, you are automatically returned to visual command mode, unless the command was to quit vi.

At any time in the editor, you can press [Esc] to return to command mode. If you're not sure whether you’re in command mode or text mode, press [Esc] to return to command mode, and you can be sure of where you are.

Text mode
Text mode is also known as add text mode or append mode. Vi starts in command mode, so usually the first thing to do after you open your new file is to send vi a command to open text mode so that you can work on your file. There are many ways to enter text mode from command mode and to enter command mode from text mode. We'll start with the most basic commands you need to know to get started with vi.

Adding text to a file
The basic commands to open text mode are the insert commands. There are many, but we'll start with the most basic:
  • a—Add text after the cursor.
  • A—Add text at the end of the line.
  • i—Insert text before the cursor.
  • I—Insert text at the beginning of the line.
  • O—Open a line above the cursor.
  • o—Open a line below the cursor.

When you’ve finished adding text, exit from text mode and return to command mode by pressing [Esc].
Notice that vi is case-sensitive.
Writing to the file (saving the file)
Once you’ve finished entering text, you must save the changes you’ve made. In vi, saving your work is called writing the changes to the file. Before you write your changes, the original file is still exactly the same as it was, and the changes appear only in the buffer in /tmp. Writing to the file replaces your original file with the file in the buffer. Before you write to the file, make sure that you’re in command mode by pressing [Esc]; otherwise, the command to write to the file will just appear as text in your file. To write to the file, enter colon mode by typing a colon (:), and then write to the file by typing w, as shown here:
:w

You’ll see your command at the bottom of the screen.

After you press [Enter], the following information appears at the bottom of the screen:
  • The name of your file.
  • [New], because it's a new file.
  • The number of lines in the file.
  • The number of characters written to the file.

An example is shown in Figure B. Notice that the number 0,0-1 from Figure A has become 1,27. This number signifies the location of your cursor in the file—0 is the location of the top line before anything has been written. Now that I have written the first line, it is numbered 1. In Figure B, the cursor is at character number 27 on line 1. If you need to find out what line you are on in a long file, these references are particularly useful.

Figure B
As you move the cursor, the character and line numbers change.


Quitting vi
When you want to quit vi, the process is similar to writing to the file. The basic commands for quitting are:
  • :q—Quit vi when no changes have been made to the file.
  • :q!—Quit vi without saving any changes.
  • :wq—Write changes and quit vi.

If you opened a file just to look at it but didn't change anything in the file, you can use :q to quit. If you made a change in the file (even just an extra space by mistake), you will get an error message if you try to use :q to quit. Some versions of vi will give you an error message like the one shown in Figure C; others will simply refuse to quit.

Figure C
If you get an error message, force the quit by entering :q!


Moving around in a file
Vi has dozens of commands that you can use to move from one place to another in your file. We will look at the commands that are used most often. It is a simple matter to move around one character at a time:
  • h or the Left Arrow key moves one character to the left.
  • l or the Right Arrow key moves one character to the right.
  • k or the Up Arrow key moves one line up.
  • j or the Down Arrow key moves one line down.

It's cumbersome to move only one character at a time, so vi also has commands to help you navigate around your file:
  • 0 moves the cursor to the beginning of the current line.
  • $ moves the cursor to the end of the current line.
  • w moves to the next word.
  • W moves to the next big word.
  • b moves back a word.
  • B moves back to the previous big word.
  • e moves to the end of the next word.
  • E moves to the end of the next big word.

To define "big" and "small,'' vi considers an apostrophe, dash, or hyphen to be a small word. For example, in the phrase "bending sickle's compass come," if you were to press w to get from "bending" to "sickle's," first the cursor would land at ”s,'' then at the apostrophe, and then at the last ”s.” If you were to press W, however, the cursor would go from "bending" to "sickle's" to "compass."
  • H moves to the beginning of the top line on the screen.
  • M moves to the beginning of the middle line on the screen.
  • L moves to the beginning of the last line on the screen.
  • [Ctrl]f scrolls forward.
  • [Ctrl]b scrolls backward.

One of the most useful commands for moving around in a file is the line Goto command. Type the line number that you want to go to and a G, and vi goes to the line you specified. For example:
  • 1G goes to the first line in the file.
  • 123G goes to line number 123.
  • G goes to the last line in the file.

Deleting text from a file
Deleting text is also driven by key commands. One of the great things about vi is the many ways you have to delete text. With a little practice, you can delete text much faster and more precisely using vi commands than by dragging over text with a mouse and pressing [Delete].
  • x deletes a single character.
  • dw deletes from the cursor to the end of the word.
  • d$ deletes from the cursor to the end of the line.
  • d0 deletes from the cursor to the start of the line.
  • dd deletes the entire line.
  • :10,25d deletes a range of lines—lines 10 through 25 in this example.

Searching for a pattern
If you are searching for one string in a 2,000-line file, be glad for vi's quick and easy search tools:
  • /search_string searches forward in a file from the cursor.
  • ?search_string searches backward in a file from the cursor.
  • n goes to the next occurrence of the string.
  • N goes to the previous occurrence of the string.

In command mode, typing slash (/) or question mark (?) automatically sends you to the bottom of the page, where you can type in the search string. When you press [Enter], the cursor moves to the first occurrence of the string (case-sensitive, of course) from where the cursor was when you started the search, either toward the end of the file for slash or toward the beginning of the file for question mark. In other words, slash searches forward and question mark searches backward from the cursor.

You can include blank spaces in your search, so if you want to find a separate word instead of a string within a word, put a blank space before (and, if you want, after) the string.

Vi will continue cycling through each occurrence of the search string, either backward or forward, as you type n. To switch the search to the opposite direction, type N. For example, if you were searching backward, to start searching forward, type N.

Changing text
Replacing text is a bit more complicated than anything we’ve done so far. To replace a string with another string, use the :g command. It is best demonstrated with an example. Note the file in Figure D.

Figure D
Here’s the sonnet as Will wrote it.


In Figure E, we replace " the one and truly great " with " the " (notice the spaces before and after the find string and the replace string).
:g/ the /s// the one and truly great

Figure E
The sonnet is easily changed using vi.


Undoing changes
If you make an edit to the file and then decide to undo the edit, there are two basic undo commands you can use:
  • u undoes the last edit.
  • U undoes all changes made on the same line.

Depending on the version of vi you are using, typing u repeatedly either continues to undo changes or puts the file back the way it was before the undo (in other words, undoes the undo).

Conclusion
In this Daily Drill Down, I’ve discussed only the basics of an immensely powerful tool. You can use literally hundreds of commands and combinations of commands to manipulate text in any way you can imagine. There are many editors to choose from in UNIX, and each has its advantages, but in order to be a successful *nix user, you must know at least the basics of vi.

Judith Samson is a technical writer and UNIX consultant who has been writing for the UNIX community for six years. She is also a passionate Linux advocate, and she particularly enjoys introducing newcomers to Linux. Recently, Judith became deeply involved in the GNOME project, and sheis currently working on a book about GNOME. When she is not busy writing, she is focusing on her graduate studies in computer science at Eastern Michigan University.

The authors and editors have taken care in preparation of the content contained herein, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for any damages. Always have a verified backup before making any changes.

Editor's Picks

Free Newsletters, In your Inbox