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!