I.T. Consulting
Tutorials
Sysadmin
How RAID Works What's a RAID? Hardware vs Software RAID Striping and Mirroring RAID 2 and 3 RAID 4 and 5 Conclusion
Software RAID on Linux RAID: Quick Recap Software Tools Creating & Using an Array Monitoring an Array Removing & Re-Assembling an Array The mdadm.conf File Deleting an Array Summary & Cheat-Sheet
Network Security
Squid Proxy Server Basic Configuration Controlling Traffic Blocking Access Monitoring Traffic
SSH: Secure Shell Overview Using SSH Encryption Authentication Keys Configuring SSH Advanced Tricks
Implementing HTTPS What Is HTTPS? Setting Up The Server
Linux Skills
The ed Line Editor First Things First Navigating Entering Text Changing Text Line Maneuvers Text Searches Using ed in Real Life Summary
Regular Expressions Text Patterns Extended Expressions
The vi Editor Introduction Operating Modes Navigation Editing Summary
Intermediate vi Power Editing Cut-and-Paste Modifying Text Searches Tips & Tricks The vi Prompt Indenting
Miscellaneous
Creating an eBook Introduction Create an ePub Create a MOBI Create a PDF

The vi Text Editor

Background

Most operating systems come with at least one text editor to provide users and system administrators a means to modify critical configuration files or to write small programs and command files.

The traditional UNIX text editor is called vi (for "visual"). This is because vi is actually a full-screen front-end to a line-by-line editor named ex (this name is derived from the original line-by-line editor ed which was subsequently extended with extra functionality, thus the name ex).

vi is definitely a programmer's editor. There is no mouse support, no pull-down menus, no help key. It was designed over 30 years ago for the original character-based UNIX environment with the following considerations in mind:

  1. vi had to preserve the inherent features and power of the underlying ed (or ex) editor.
  2. vi had to be usable on any type of terminal (with or without function keys, arrow keys, home/end keys, etc).
  3. Performance was more important than user-friendliness since the target user was the professional programmer, not the end-user.

As a result, vi is one of the fastest and most powerful editors in the industry but is also somewhat difficult to get used to.

If you are not a professional programmer, you may wonder at this point why you should bother making the effort to learn this editor. The reason is simple: vi is present on all versions of UNIX, including of course Linux, and may be the only editor available on some "bare-bones" systems such as firewalls or single-purpose computers.

Similarly, if you are managing Linux systems remotely using SSH or telnet and do not have access to graphical editors, you might have access to simpler editors like pico or joe, but you are guaranteed to have access to vi.

Fortunately, most simple editing tasks can be performed with just a handful of vi commands. This tutorial is designed to get you up and running with the most essential editing functions and to hopefully keep you out of trouble.

Since our focus is on getting you started quickly, this howto has been stripped to the absolute bare bones. You will learn how to move around, insert and delete text, and save your file. If you are an application programmer or a system administrator, you should definitely invest some time to learn more about this editor; the many short-cuts and features available in vi will serve you well for years to come.

Text Editors vs Word Processors

It is important to understand the distinction between a text editor and a word processor. Word processors are designed to produce documents such as letters and books for use by human readers. As a result, most word processors will feature the ability to set fonts, indent paragraphs, or calculate just the right amount of space to leave between words so that the right margin forms a straight line (right justification).

Conversely, text editors work on a different premise: they are used mainly to edit configuration files and programs to be used by the computer, so cosmetic concerns such as font changes or right justification are of no importance and would actually get in the way.

Consequently, text formatting attributes are generally not supported by text editors. However, other features such as line numbering or context-specific text manipulation are critical in program writing and are usually more powerful in text editors than in commercial word processors.

While it is certainly possible to write program code using most word processors or to write simple letters and memos using text editors, each is best used for its own purpose.

The vi editor is a traditional text editor designed to write code. Do not expect pop-up windows or the ability to embolden or italicize characters within that editor; it can only edit regular ASCII text files such as programs, configuration files or short messages.

How to Keep Your Sanity

The vi editor has a reputation for being difficult to learn and use. New users typically invoke it and attempt to type in a few words just to find out that the program beeps at them continuously or behaves erratically. Frustrated, they attempt to leave the program using commonly-accepted methods such as typing exit or quit, or hitting the interrupt key but the "stupid" program just keeps on beeping. Furious, they disconnect from the Linux system and give up in disgust.

If this sounds familiar, it probably happened to you just like it happened to me in the early days. It actually refused to use this aberration for months after my first encounter with it.

Yet, a small amount of extra knowledge about the program would have alleviated all this frustration. The next paragraphs contain these valuable guidelines. Therefore, for your sanity's sake, do not invoke vi until you have read through to the section titled "Invoking vi" (just a few paragraphs ahead).

 

 

Two Operating Modes

Much of vi's bad reputation is due to its unusual user interface. While today's users are accustomed to mouse-driven interfaces, function keys and pop-up menus, vi uses ordinary alpha-numeric key sequences (letters and numbers only) to perform all tasks. This requires the user to toggle back and forth between two modes of operation:

  • a command mode where ordinary keystrokes represent instructions for the editor (for instance, the letter "x" in command mode means "delete a character"); and
  • an insert mode where keystrokes typed are simply entered as text.

When you first invoke vi, you are initially put in command mode. You can then enter insert mode with a number of instructions such as insert (the letter "i"), append (the letter "a"), open line (the letter "o"), and other similar commands (we will examine all of these in detail later). All text typed after issuing one of these commands is entered in the document as typed. To return to command mode, simply hit the escape key (typically labelled "ESC" on the keyboard, and represented in this text as <ESC>). At that point, keystrokes again represent vi commands, not text.

If, while in command mode, you press a key which does not have any special meaning to vi, the program beeps to notify you that the "command" given does not exist or does not apply in this context. This happens frequently with new users who forget they are in command mode and attempt to enter text without first issuing the insert (i) or append (a) instruction.

In such cases, the program will either beep a lot or, depending on the particular keystrokes entered, may take unpredictable actions such as moving to the next page or deleting some lines.

There are actually some very good reasons for this seemingly absurd system, and very sound benefits as well. The original UNIX operating system was designed back in the days of character-based terminals and pioneered the concept of "open system." Unlike the proprietary operating systems of the day (from IBM, Digital and Data General, for instance), Unix was capable of supporting virtually any type of terminal, from the very primitive to the very sophisticated.

Because of this, vi could not make any assumption as to the terminal's capability, such as the number of function keys available or even the presence of cursor keys. For this reason, the author of vi designed an interface which would work on just about any terminal available by using the lowest common denominator available: the alpha-numeric set of keys.

While vi can take advantage of arrow keys and other navigating keys on today's keyboards, we will focus on the alpha-numeric keys for all commands in this article. Touch-typists will actually find this method more convenient than leaving the keyboard to move the mouse or using the arrow keys.

IMPORTANT NOTE
Keep in mind that virtually every key on the keyboard has a meaning to vi. Also be aware that upper-case and lower-case characters have different meanings (although frequently related). For this reason, throughout this tutorial, be careful to consider the case of vi instructions to avoid unpleasant surprises, and make sure the keyboard caps-lock feature is off.

Getting Out of Trouble and Undoing Things

Once you understand the reasons for the vi interface, it becomes a lot easier to accept it and use it properly. Be aware that, in the beginning, you too will occasionally forget you are in command mode and may issue commands which may cause much frustration. Fortunately, these unwanted actions can usually be undone in two simple steps:

  1. Press <ESC> to make sure you are in command mode (if you already were in command mode, vi will simply beep but no harm is done).
  2. Press "u", which is the command to "undo" the last change. This should put you back where you started from. Note that pressing u again will undo the undo, putting thing right back the way they were.

If you ever wonder whether you are in command or edit mode, simply press <ESC>. This will always put you in command mode. If you were already in command mode, vi will beep, but at least you will have come back to a known state.

Invoking vi

Now that you understand vi's two different operating modes, you are ready to invoke vi without significant danger to your mental health or nervous system.

You can invoke the vi editor with the command "vi", followed by the name of the file you wish to edit. If the file exists, it is loaded in memory and displayed on the screen. If the file does not exist, it will be created under that name when you save your text from vi.

For instance, the command: vi memo invokes vi and reads in the file memo. If that file does not exist, the screen will be blank, except for a string of tildes (~) along the left margin, like this:

_
~
~
~
~
~
~
~
~
~
~
"memo" [New file]

vi normally attempts to show a full screen window on the text. However, if the file does not contain enough lines to fill the screen, vi displays tildes at the left margin to represent the empty lines. In the previous example, since memo was empty (it did not perviously exist, as shown by the "[New file]" message), a full column of tildes is displayed. The underscore in the top left corner represents your cursor.

Note that, although most terminals feature at least 24 lines, we will use only 12 in our examples to keep them short.

It is also possible to invoke vi without a filename. In this case, vi will start with an empty file and behave normally, except that you will have to specify a file name when you are ready to save your changes (details in section on "Saving your data").

Getting Out of vi

One of the first things you should learn about any interactive utility is how to get out of it. To exit vi at any time:

  1. Press <ESC> to make sure you are in command mode.
  2. Press the colon (:), which will place your cursor at the bottom of the screen, then type the letter "q" (for "quit") and press ENTER.

IMPORTANT:

If you have made modifications to the file, the ":q" command will not allow you to quit until you have saved your changes. To instruct vi to quit without saving your changes, add an exclamation mark to the command for emphasis. In other words, press the colon, then enter q! and press ENTER.

 

 

Navigation

Creating a Sample File

For the purpose of this tutorial, we will use a sample file named laws containing the following text:

The laws of computer programming:
Any given program, when running, is obsolete.
If a program is useful, it will have to be changed.
If a program is useless, it will have to be documented.

If you wish to follow our examples, you will need to either create this file (using a text editor that you are already familiar with), or cut-and-paste the text above in a text file, or simply download it from this link.

Moving Around

Assuming you have managed to create or download our sample file, we can now pick up the tutorial by invoking vi against this file by typing vi laws to bring up a screen that will look something like this:

The laws of computer programming:
Any given program, when running, is obsolete.
If a program is useful, it will have to be changed.
If a program is useless, it will have to be documented.
~
~
~
~
~
~
~
"laws"

Remember that you are in command mode where almost every key on the keyboard means something to the editor. Some of those keys are navigation keys to allow you to move left and right, or up and down through the text. The navigation keys in vi are these (all lower-case):

Key Meaning Action
h left Move one character to the left
l right Move one character to the right
j down Move down one line
k up Move up one line

While these keys are not mnemonic, they were chosen for their location on the keyboard: they rest under the fingers of the right hand when poised above the middle row, which is the standard resting position of your fingers if you are a touch-typist.

IMPORTANT: All vi commands are case-sensitive. Make sure you use the correct case or you will get unexpected results.

Unlike word processors, vi only allows you to move the cursor over existing text, not over empty space. If you try to move the cursor past the end of a line or down past the last line, vi will "beep" to indicate an invalid action.

If you get stuck...

While honing your editing skills, you may end up messing up your text and not knowing how to undo or fix the problem. If all else fails, simply quit without saving your changes by pressing <ESC> to return to command mode, then entering :q! as seen earlier.

You can move quickly one word at a time using the following keys:

Key Action
w Jump to start of next word (pressing w again jumps to the next word, etc.)
b Beginning of word (pressing b again takes you to the beginning of the previous word, etc.)

To move quickly to the beginning or end of a line, use the following keys:

Key Action
0 (zero) Back to beginning of the line (the 0th character)
$ Go to the end of the line.

To move through a file a full screenful at a time, use the following mneumonic keys:

Key Action
Ctrl-f Move forward one screenful
Ctrl-b Move back one screenful

Note that we cannot try these last two keys yet in our sample file since it is too short to span several screens.

NOTE:

While these navigation keys may seem strange at this point, it's worth the effort to become familiar with them because these same keys are used in other utilities and even some games. For instance, at the Linux prompt, you can set an option (set -o vi) to use these very keys to bring back previous commands and even edit them directly on the command line to fix typos or save time entering repetitious commands. There is even a browser plugin for Firefox that allows you to navigate Web pages using these classic navigation keys! So, the skills you acquire here while learning vi are "recyclable" and well worth the effort.

 

 

Editing Commands

In this section, we are going to learn how to delete text, insert or append text, and save our changes.

Deleting Text

All the commands we have learned so far move the cursor over different amounts of text. Now, this is where you will start to realize that vi is beautifully consistent: by simply preceding any of these commands with the letter "d", the corresponding amount of text is deleted. For instance, dw deletes one word and d$ deletes to the end of the line.

The following chart shows the correspondence between the commands to navigate and to delete text:

KeyActionKeyAction
h Move left dh Delete character on the left
j Move down dj Delete current and next line
k Move up dk Delete current and previous line
l Move right dl Delete character on the right
w Move to next word dw Delete from here to next word
b Beginning of word db Delete from here to beginning of word
0 (zero) Beginning of line d0 Delete from here to beginning of line
$ End of line d0 Delete from here to end of line

In addition, the following shortcuts are also available for convenience:

KeyAction
x Delete next character (same as dl)
dd Delete the current line (i.e. the line the cursor is on)

The command "x" was introduced because it would be rather silly to thave to type two characters to delete one. The command "dd" was introduced to act only on the line the cursor is on, as opposed to "dj" or "dk" which would delete the current line and the line below or above, respectively.

Try these out on a text file. Remember, you can always press "u" to undo a deletion.

Inserting Text

I mentioned earlier that there are a number of ways to enter edit mode. The most common is the insert instruction, represented by the "i" key. To insert text, simply position the cursor (using the navigation letters h, j, k or l) at the desired location, then press "i" (lower-case) and start typing. While in insert mode, you may press the key at the right margin to continue on the next line and add as may lines of text as you wish. To go back to command mode, which you must do in order to perform any other editing task such as deleting text or just moving the cursor elsewhere, press . For instance, let's try inserting a word in the middle of a sentence. Position the cursor over the letter "l" in the word "laws" (first line), then press "i" (for insert) and type the word "universal" followed by a space. Then, press <ESC>. The text should now look like this, with your cursor (shown as " ") positioned right after the word "universal" :

The universal laws of computer programming:
Any given program, when running, is obsolete.
If a program is useful, it will have to be changed.
If a program is useless, it will have to be documented.
~
~
~
~
~
~
~
~

It's that simple to insert new text in the middle of a line.

Backspacing

While entering text, you may use the backspace key to back up over mistakes. Backspacing is different from deleting text; you use the backspace key to go back over text you are currently entering (i.e. while in insert mode) while the delete commands such as "x" or "dw" are used to edit text that has previously been entered.

DO NOT use the left-arrow key for backspacing, however. The left-arrow key is not the same thing as the backspace key. Arrow keys are really function keys that generate escape sequences, so pressing an arrow key while in insert mode may be equivalent to pressing <ESC> followed by a few extra characters, resulting in unintended results.

Modern versions of vi may anticipate this error and recover gracefully, but this is not something you should count on. Bottom line: if you want to backspace over some text you have just entered, the backspace key is what you want to use.

Handling long lines

You may find that, as you insert more text, the line eventually reaches the right margin and "wraps around" to the next line. For instance, consider our sample file:

The universal laws of computer programming:
Any given program, when running, is obsolete.
If a program is useful, it will have to be changed.
If a program is useless, it will have to be documented.
Any given program will expand to fill all available memory.
~
~
~
~
~
~

Now, position the cursor over the first character of the first line, then press "i" (to insert) and type the following text:

According to an anonymous source, the following are

You will see the rest of the line being pushed over to the right, something like this:

According to an anonymous source, the following are The universal laws of computer programming:

It is important to realize that, while that sentence may be displayed as two separate lines, it is still a single line as far as the editor is concerned since you did not enter a carriage-return (ENTER character).

This situation can lead to puzzlement and frustration for new users when they attempt to move the cursor down to the "second line," just to find out it always skips to the third line. In fact, that "second line" is really the same line their cursor is currently on, only wrapped around because of the limited width of their screen or window.

So, how could you get the cursor down below where you want it? Simply move it to the right (using either "l" repeatedly to move one character at a time or "w" to move more quickly one word at a time), following the line until it gets to where you want.

This may be a difficult concept to grasp at first, so it's best to experiment on a file with a few long lines to really get the hang of it. Keep in mind that you can always press "0" (zero) or "$" to jump to the beginning or end of the line, respectively. This can help you identify which screen lines are really just one long wrapped-around line and which ones are individual lines.

Appending Text

Frequently, you need to add text to the end of an existing line. Unfortunately, the command "i" inserts text before the cursor position. As a result, if you position your cursor on the last character of a line and press "i", you will be inserting your text just before the last character instead of adding past the existing text as you intended.

For this reason, vi features the "append" command, represented by the "a" instruction. Appending is virtually the same as inserting, except that the new text appears after the cursor position rather than in front of it.

To try the append instruction, add the following line to our sample file:

Any given program will expand to fill available memory.

Simply move to the last character of the last line (using j repeatedly to move down to the last line, then $ to move to the end of the line), then press a to append past the end of the line.

The first character you should type is ENTER (to start a new line), followed by the text above. Press <ESC> when you are finished entering this new line of text to return to command mode. Your file should then look like this:

The universal laws of computer programming:
Any given program, when running, is obsolete.
If a program is useful, it will have to be changed.
If a program is useless, it will have to be documented.
Any given program will expand to fill all available memory.
~
~
~
~
~
~
~

Opening a line

There is a more convenient way to add text past the end of a line; you can "open" a line below the current line with the "o" command. Pressing "o" while in command mode opens up a new line, pushing all the text below down one line to make room for the new text. This also automatically puts you into insert mode.

Functionally, it is equivalent to what we just did with the "append" command in the previous section but is simpler and easier.

To try this, move back to line one (anywhere on the line), then press o. You will see the rest of the text being "pushed down" by one line and your cursor will be sitting on the new empty line, in insert mode. Anything you type at that point will be entered on this new line. If you don't have any text to insert, just press <ESC> now and you are back in command mode. The new blank line, however, remains.

The universal laws of computer programming:
 
Any given program, when running, is obsolete.
If a program is useful, it will have to be changed.
If a program is useless, it will have to be documented.
Any given program will expand to fill all available memory.
~
~
~
~
~
"laws"

Saving Your Changes

Many vi commands start with the colon (:), followed by one or more characters. When you press the colon key, an input line opens at the bottom of the screen for your commands. This input line can be used for line-oriented editing instructions, such as search-and-replace operations. However, those are beyond the scope of this introductory article, so we will only introduce the commands to save your file and to quit the editor.

To save your file before leaving the editor, issue the command ":w" (for "write to disk"). Your document is saved under the filename given to vi when you invoked it ("laws" in our examples).

If you invoked vi without a filename, you must now provide one on the input line. You must leave a space between :w command and the filename, as in:

~
~
~
:w memo

As mentioned before, you can use the instruction ":q" to leave ("quit") the editor. Remember that you must be in command mode to use these commands, otherwise the characters ":w" and ":q" will simply be entered as text in your document.

As we also mentioned previously, you cannot quit with ":q" if you have made changes to the file and have not saved them (although "q!" overrides this safeguard).

Since saving your changes and quitting the editor is such a common action, vi allows you to enter both commands together for convenience, as in ":wq" for "write and quit."

 

 

Summary

It's time to take a breather and review what we have seen before tackling some more advanced and powerful features.

While it may seem like we have covered an awful lot of confusing commands, a quick "cheat-sheet" can help us wrap our mind around things.

So, here is your first-aid kit when it comes to vi:

Invoking vi: vi filename
 
Quitting vi: :wq Write and quit
  :q Quit only
  :q! Quit without saving
 
Moving the cursor: h Left         k   Up
  l Right       j   Down
  0 Beginning of line
  $ End of line
 
Deleting text: x Delete character
  dw Delete word
  dd Delete line
 
Entering text: i Insert before cursor
  a Append after cursor
  o Open a new line
  <ESC> Return to command mode
 
Undo last change: u  

Now, was that so bad?

What we have done so far is actually the most difficult part. If you have mastered this handful of commands and concepts, the next tutorial (Intermediate vi) will simply build on these concepts in a way that you will find surprisingly consistent and logical.

 

 


Did you find an error on this page or do you have a comment?

Services
Sponsors