vi's purpose

vi's sole purpose, IMNSHO, is to edit the Makefile to build emacs, The One True Editor.

To this end, here are the vi keys you need to know:

  • The most important is, :q! this will quit without saving, for when you delete a whole line on accident.
  • The next most important is, i this is the insert command, and it will allow you to type text at the cursor position until you hit ESC.
  • a for Add is the bastard cousin of i. a will move the cursor one spot to the right before you insert text. Also terminated with ESC.
  • Deleting is tricky. It's a two key sequence, the first key, d starts the delete, the next key determines which character to delete. I basically I only use two, dl will delete the character under the cursor, dd will delete the whole line. I sometimes use d$ to delete until the end of the line.
  • Last thing you need to know is, saving. :w will save, and :w! will force a save (if you are owner but don't have write promission). :wq Will save and quit.
Now you're ready to compile emacs.

An Introduction to Vi

Vi is probably the most widely used editor out there. The vi version that comes with most modern operating systems is nvi, which I will discuss here. I hear vim is much preferred by many people because of it's tremendous extensions to the original vi.

Vi is a screen based editor, i.e. when you start it the whole screen will be filled with your text file. Its core, however, is nex. A line oriented editor.

Vi may seem confusing to new users, because it differentiates between a "command" and an "edit" mode. But believe me, it's worth learning how to use it. Once you know how to use vi, you practically edit files on any system, because vi is so widely used (yes, there is even a version for MS-DOS available).

You can start vi by typing "vi <file>". I recommend you type: "vi ~/.exrc" so we can make vi look more friendly. You will now see a screen filled with tildes (~), and maybe some lines of text at the top.

To describe vi commands we will use the following conventions:
^] means "press the ESC key"
^M means "press the RETURN key"
^.. means hold CTRL while pressing .., where .. is a letter.

This annotation is used in many vi related documents, so you might as well learn about them now. Now type in the following:

iset showmode^M
set ruler^M
set showmatch^M
^]:wq^M

Good. Now when you start vi again, you'll notice that at the bottom of your screen a line and column number will have appeared. In the bottom right corner of the screen there will be "Append", "Insert", "Replace", or "Command". When you start vi it will say "Command".

Open a non-existant file now. In the bottom left corner you will see something like: "myfile: new file: line 1". Press SPACE. Your screen will "blink", or you will hear a bell. Don't worry about that. The aforementioned line has now disappeared and will have been replaced by "1,1 *Command". This means you are on the first line, in the first column, you have changed the file (*) (not really, but you pressed space, so vi will think you have), and that you are in "Command" mode.

To start typing press: "i". Notice how "Command" turns into "Insert". Now go ahead and type something. Notice how the line and column numbers change as you type. Now press "^]". You are back in command-mode and you can move around the file now, using the following commands:

k - up
j - down
h - left
l - right

Practice moving around for a while. Okay. You may have noticed that you can use the arrow keys too. Forget that. The arrow keys are "weird" keys. If you are working on an old terminal, or via ssh, or whatever, you may find that the arrow keys won't work. So it's good practice to use only the hjkl-keys. And it helps prevent RSI, because you won't have to move your arm.


Back to Linux For Monkeys, or back to Editing text on UNIX.
This has always been a valuable little vi reminder list. I would hate to lose it.

Handy "vi" Guide 

CURSOR POSITIONING 

Ctrl-F  go forward a page
Ctrl-B  go backward a page
Ctrl-U  go up half a page
Ctrl-D  go down half a page
j       go down one line (faster than Cursor-Down)
k       go up one line (faster than Cursor-Up)
H       go to the top of the screen
M       go to the middle of the screen
L       go to the bottom of the screen
G       go to the bottom of the document
1G      go to the top of the document
nnnG    go to line number 'nnn' of the document
          Note: most positioning and modification commands can be  
          repeated 'nnn' times by using a repetition prefix; use 
          ESC to abort entering the prefix)
w       go forward one word
b       go backward one word
0       go to the first column of the current line
$       go to the last column of the current line
^       go to the first non-whitespace character on the line
Ctrl-L  repaint current screen  (is Ctrl-R on some systems)

TEXT MODIFICATION 

u       undo the last change
U       undo all changes made to a line since you last moved to the line
i       enter text-insertion mode (ESC to finish)
Ctrl-V  insert character(s) of a keystroke verbatim, while in insert mode
A       append text to the end of a line (ESC to finish)
x       delete the character under the cursor
cw      change current word
cc      change the entire current line (ESC to finish)
r       replace current character with the next character you type
R       overwrite the current line from the current position (ESC to finish)
J       join the next line of text to the current one
~       alter the case (upper/lower) of the letter under the cursor
.       repeat the last modification operation
ma      set marker 'a' to the current location (you can name markers 'a'--'z')
'a      go to marker 'a'
y'a     yank (copy) text from current location to marker 'a' into the kill buf.
yy      yank the current line into the kill buffer
d'a     delete text from current location to marker 'a' into the kill buffer
dd      delete the current line into the kill buffer
p       put (insert) the text in the kill buffer after the current line
P       put (insert) the text in the kill buffer before the current line
:r fn   read file 'fn' into the document after the current line
        (commands that start with ':' are finished by pressing Return)

SEARCHING 

/str    forward-search for the text string 'str' (can be a regular expression)
?str    reverse-search for the text string 'str'
n       find the next occurrence of the last-searched-for string (fwd/backwd)

FILE OPERATIONS 

ZZ      exit and save the document if modified
:w      write text to a file (:w! to force)
:w fn   write text to file 'fn' (without changing document name) (:w! to force)
:q      quit (:q! to force)
:vi     go back into full-screen mode after going into ':' mode
Source: http://www.student.math.uwaterloo.ca/~cs338/vi_guide.html

VI is also an acronym that stands for virtual instrument. This is what LabVIEW calls its programs and functions.

vgrep = V = video toaster

vi /V-I/, not /vi:/ and never /siks/ n.

[from `Visual Interface'] A screen editor crufted together by Bill Joy for an early BSD release. Became the de facto standard Unix editor and a nearly undisputed hacker favorite outside of MIT until the rise of EMACS after about 1984. Tends to frustrate new users no end, as it will neither take commands while expecting input text nor vice versa, and the default setup on older versions provides no indication of which mode the editor is in (years ago, a correspondent reported that he has often heard the editor's name pronounced /vi:l/; there is now a vi clone named `vile'). Nevertheless vi (and variants such as vim and elvis) is still widely used (about half the respondents in a 1991 Usenet poll preferred it), and even EMACS fans often resort to it as a mail editor and for small editing jobs (mainly because it starts up faster than the bulkier versions of EMACS). See holy wars.

--The Jargon File version 4.3.1, ed. ESR, autonoded by rescdsk.

vi (usually, /usr/bin/vi or /usr/ucb/vi) is a text editor on Unix systems. To be exact, it is an editor mode ('visual mode', hence the name) added to the standard Unix editor ex.

vi was written in 1976 by the 17-year old Berkeley undergraduate Bill Joy and added to Berkeley's local copy of the Unix OS source, the BSD Unix distribution.

ex, an extended version of the basic ed editor, is line oriented, which is the best you can do if your output device is a line printer; vi is screen oriented, showing a whole screenful of text at a time, with cursor-based navigation and operations. A logical step if you want to take advantage of the capabilities of terminals such as DEC's vt100.

vi's user interface was designed to minimize typing. Commands are single, mostly lowercase characters; arguments to commands, usually to indicate a position or range in the file, are often single characters as well, and follow the command. As a special case - to minimise typing further - the current line is indicated by duplication. For example, d is the deletion command; dd deletes the current line, d{ deletes to the start of the current paragraph, dG deletes to the end of this file.

The brevity of its commands makes them hard to memorise, and the relative lack of visual feedback makes them hard to use. You have to do it right the first time, and you have to do it all by heart. This is a problem for everyone but a 17-year old computer whizkid, which explains vi's bad reputation.

Another bad problem with vi and ex is the fact that its interface is modal: to insert characters you go into input mode, and to issue commands again, you have to leave it first. This often results in commands being added to the text, or worse, in long sequences of commands being issued that vi will happily execute without the user even knowing what they mean.

However, vi/ex is the only universally available editor on Unix-like systems, so if you switch systems a lot, a working knowledge of vi really helps to get basic editing done.

It must be added that many vi-likes have developed, such as nvi, elvis, and the most popular and most bloated one, vim. These are vi compatible as far as common commands go, but add many new commands and features of their own. vim even has a menu interface.

I once even ran into a system (a halfway installed Debian distribution, years ago) that managed to install as /usr/bin/vi an editor (ae) that is not vi at all. This of course spoils the idea that wherever you go, there will always be the dreadful vi to help you get by. It is also the reason I've never used Debian.

A short tutorial on vi

So you want to learn the vi editor, eh? Congratulations! Contrary to popular belief, vi still has many uses, and judging by its still-high popularity, Emacs has not made the editor obsolete yet. vi takes time to master, but once you are familiar with the keystrokes you will likely find that the editor is intuitive and natural. And, once you're familiar with it, you can use vi on practically any operating system, from *nix (on which it is almost always pre-installed) to Windows and Mac OS.

Make no mistake, however - vi takes time to master. You must practice with it. It's not as maddening as, say, learning to use the Dvorak keyboard layout, but vi is no Windows Notepad - it is a powerful programmer's editor. Like Unix itself, its keystrokes are terse and at first confusing. Fortunately, the editor is forgiving; its undo feature will likely prove tremendously helpful. Recent versions of vi, such as vim, have also made the editor easier to use, but the author recommends to users of graphical versions of vim, such as gVim for Windows, to avoid becoming too dependent on the menu system. The menus are easy to use, but without the quick keyboard commands vi doesn't have much of an advantage over Notepad!

This writeup will walk you through creating a simple file in vi. Along the way, I will demonstrate some of its most-frequently-used commands. After completing this tutorial, you should be able to use vi to compose simple plaintext documents and source files. The more esoteric, advanced features of vi are left for the reader to discover (and they vary from implementation to implementation).

First, make sure you have a copy of the vi editor. On Unix (which includes Mac OS X), you will almost certainly already have it; type vi foo.txt in any shell (sometimes called a Terminal window or a command prompt). On Windows, vi doesn't come installed by default. Visit http://www.vim.org/ and download gVim, a graphical version of vim that can be launched from the Start menu. The File > Open... menu item is usually the easiest way to access a file on Windows, since Windows likes to use long path names that are cumbersome to type out by hand. In this case, however, we want to create a new file. Choose File > Save, navigate to a temporary folder, and save to foo.txt.

Whatever version you decide to use, your screen should look something like this:


~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
foo.txt: new file: line 1

The status line at the bottom informs you that vi has just created a new file named "foo.txt". We're going to enter some text into this file. To begin, press i to enter insert mode. In insert mode, you can enter text into the file. Most of your time will be spent in insert mode, in which you can type and edit text.

Type the following: Jackdaws love my big sphinx of quartz.[Enter][Enter]The quick red fox jumps over the lazy brown dog. Now, press [Esc] to leave insert mode and return to command mode. The text should be displayed. If you made any errors, you can go back and fix them at the end of this tutorial, once you've learned how to!

You've returned to command mode. In command mode, your keys have different meanings - each key invokes a different vi command. Since vi has more commands than there are letters on the keyboard (even with Ctrl and Shift), some less-frequently-used commands are prefixed with :. We will now invoke one of these commands, one of the most important commands in the editor. Type :wq and press [Enter].

By now, you're likely thinking, "Hey, the editor just disappeared!" That's correct - :wq corresponds to the command "write and quit," which saves your file to the disk and quits the program. As it turns out, :wq has several variants: :w, which saves the file, :q, which quits the program if there aren't unsaved changes, and :q!, which quits vi even if there are unsaved changes. :q! is a potentially dangerous command; in general, think twice before executing any command with an exclamation mark in it. In vi, ! is a warning symbol.

Now, restart vi, and reload the foo.txt file. When vi starts up, you will see the contents of your file, followed by ~ characters to indicate the end of the file, and a status string at the bottom of the screen. Your screen should look something like this:

Jackdaws love my big sphinx of quartz.

The quick red fox jumps over the lazy brown dog.
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
~
foo.txt: unmodified: line 1

We're now going to make some changes to this file. In this section, you'll be working with many keys in command mode, and it's easy to hit the wrong one. Thankfully, vi has an undo command for just these situations. Simply press u to undo the last change and u again to redo it.

Before we can make changes, however, we need to learn how to move the cursor around. The simplest way to do this is with the one-letter cursor keys, h j k l, which correspond to left, down, up, and right respectively, or, on most implementations of vi, the keys on your keyboard. Obviously, most people prefer the latter; however, many claim that h j k l is significantly faster. You're free to use whichever you prefer, but it's useful to at least remember the existence of h j k l, in case you end up using a version of vi that doesn't support the arrow keys. (I personally alternate between the two.)

Play around with the cursor movement keys to get a feel for them. When you're done, return to the first line. We're going to add a popular E2 meme to the end of the first line. However, the first line is somewhat long; holding down the right arrow key to move to the end of the line would prove to be a nuisance. Fortunately, vi has a shortcut. Press $ on your keyboard to jump to the end of the first line. Your cursor should now be over the period at the end of the line.

You might think that we can simply press i to go into insert mode now and add to the line, but there's a problem. Insert mode inserts text before the character over the cursor. We want to add text after the cursor. Instead of i, we need to use a (append), which puts us into insert mode as before but adds text after the cursor. Press a, and enter the text SOY! SOY! SOY! Soy makes you strong! Strength crushes enemies! SOY!. Satisfied with your handiwork, press [Esc] to return to command mode.

This long line provides several good opportunities to try out vi's many movement keys. Press ^ to return to the beginning of the line. Then, press w several times in succession. Notice how the cursor moves from word to word. You can back up by pressing b. Try ) and ( as well; notice how the cursor moves from SOY! to SOY! These commands move to the next sentence and previous sentence, respectively. Try out the following movement keys on this file, and see how they work:

  • fc: move forward to character c
  • Fc: move backward to character c
  • w: move to next word, stopping at punctuation
  • W: move to next word, skipping punctuation
  • b: move to previous word, stopping at punctuation
  • B: move to previous word, skipping punctuation
  • e: move to the end of the word, not counting any ending punctuation
  • E: move to the end of the word, counting any ending punctuation
  • }: move to next paragraph
  • {: move to previous paragraph
  • ^F (use Ctrl): scroll forward one page
  • ^B: scroll backward one page

Don't panic. You don't have to memorize these keystrokes right away. vi reference charts come in very handy here; see the end of this writeup for details.

Now, we're going to make some changes to the third line. Press 3G (holding down Shift to access the capital G) to go to the third line; this is a useful command that programmers will appreciate. Press ww to go to the third word, "red." We want to remove this word. Press dw and watch the word vanish! dw is one of the "edit-movement" keys. d, which specifies to delete, must be followed by a movement key. In this case, we chose w to delete the current word. As you might expect, the d command can take many forms; for instance, d$ (delete to end of line), dfa (delete everything up to the letter a), and d→ (delete next character; a synonym is x). (As a special case, the edit-movement keys can be repeated to specify the entire line; e.g. dd deletes the entire line.)

We're now left with "The quick fox jumps over the lazy brown dog," which doesn't quite sound right. Wouldn't it sound better if the fox were brown? We can move the word "brown" immediately before "fox" with just a few keystrokes. First, press fb to move forward to the first occurrence of "b," which, lucky for us, is right at the start of the word "brown." Then, type dw to delete the word.

"Wait!" you might ask. "We wanted to move the word, not delete it!" This brings us to a subtlety of the d command in vi. "Delete," as it turns out, is something of a misnomer. The d command not only deletes text, but it also adds it to the clipboard. The "delete" command is actually analogous to the "cut" command in most GUI applications. Incidentally, vi's version of the "copy" command is y, for "yank." It works in exactly the same manner as d, but it doesn't delete text.

The rest is simple. Use ^ to return to the beginning of the line, press ww to go to the spot where we want to paste the word, and press P (holding down Shift) to paste in "brown." Note that we use P instead of p, since P pastes before the cursor and p pastes after the cursor. Think of P as similar to i and p as similar to a.

The rest of this guide covers some miscellaneous commands that may prove useful in your vi editing escapades.

c (change), another edit-movement command, is a shortcut for d followed by i. It allows you to change portions of text easily. For instance, cw changes the current word. Press [Esc] once you're done making your change.

/ (search) is vi's powerful search tool. It uses regular expressions (regexes), which will be familiar to you if you're accustomed to Perl, sed, or awk. If you're not familiar with regexes, you can still use / as a simple search command, but be advised that it is case-sensitive by default; if you want to search case insensitively, add /i to the end of your search. For example, if you wanted to match "everything2," "Everything2," or "EvErYtHiNg2", type /everything2/i [Enter]. To continue your search (Find Next), simply type / [Enter].

? is exactly like /, but it searches backward instead of forward.

:%s/old/new/g is vi's search and replace command. It replaces all occurrences of old with new. It has many options, but the most common are as follows: omit the % to restrict the search to the current line; add an i to the end of the line to search case insensitively; add a c to the end of the line to prompt for confirmation before making each change. A proper description of vi's search and replace commands is beyond the scope of this writeup!

This concludes the vi tutorial. As you continue your many happy and joyous vi adventures, you may want to refer to one of the following references:

  • your local manpage (on Unix, type man vi)
  • vi's help file (try :help [Enter] inside vi; be warned that this may not be present in all versions)
  • one of the many quick reference sheets out there; I suggest the one at http://dcfonline.sfu.ca/ying/linux/vi/ (apologies for the previously broken link), which is currently taped next to my computer.

Happy editing!

Log in or registerto write something here or to contact authors.