Welcome to vi Boot Camp!

Your Host: Dr. Morrison

If you are of the faint of heart Find another place to be! Otherwise strap on your seat belt for 90 minutes of intense fun and learning!

MAGGOT!!!

Crank your lappy in Linux or Mac!

Open a terminal window!

And leave your mouse at home with your diapers!

Purpose and Orientation You should be familiar with Linux and have used vi. If you are an intrepid buck-beginner, we invite you to try and follow along.

We are going to bulk up your vi skills to make you faster and better at vi. If you ascend its learning curve, you can save many hours of work. We will review some fundamentals so we all speak the same language, then we will have a punishing test of your skills.

The vi editor will give you speed and efficiency when processing and searching text. This skill is very useful to programmers, data miners, HTML/CSS authors, and users of TeX/LaTeX. What, you don't use LaTeX? You are wasting your life away fighting stupid Microsoft Word! LaTeX eliminates the version headaches of word processors because all files are stored as plain text.

All pink boxes are UNIX sessions. A generic UNIX prompt is represented with a $. Yours will vary depending upon how your machine is configured.

Attention Ubuntu Users! Make sure you install vim and that you are not stuck in the tiny world of vi-tiny. If you are, here is the cure. Open a terminal window and enter it.

$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install vim

Attention Mac Users! Make sure you turn on syntax coloring. To do this, follow these instructions to the letter!

  1. Open a terminal window. If you have never used terminal before, it is in Applications/Utilities. Drag its icon onto your app dock. Now type
    $ sudo vi /usr/share/vimrc
    
  2. Enter your password when prompted to do so.
  3. Type G.
  4. Type o.
  5. Enter these lines of text exactly as shown, including spacing, or you will be punished by vexatious error messages. Do not put spaces around the = sign!
  6. syntax on
    set tabstop=4
    set et
    
  7. Hit ESC.
  8. Type :wq

You are ready now.

Before you begin, make a directory called BootCamp to hold all of the examples you create today. Also, bookmark this page for your future reference.

Starting vi The vi command takes as argument a file name. If the file exists, it is opened by vi; otherwise, an empty file by the name specified is created.

$ vi fileName

We will now create a file named program.c. At the UNIX command line, enter the following. We will do a little preview of what is to come.

$ vi program.c

When the new vi session opens, it looks like this. We will type some stuff here and get a preview.

~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
"program.c" [New File]

On the Importance of File Extensions UNIX cares not a whit about file extensions, unlike its dumber cousin Windoze. However, vi uses file extensions to determine file type and provide that godsend, syntax coloring. Said coloring saves tons of stupid mistakes and gobs of work. This table shows a small sample of coloring schemes that are available. There are tons of these.

Available Syntax Coloring
ExtensionFile Type
.cC language source code
.hC/C++ header file
.javajava source code
.jsJavaScript source code
.cppC++ language source code
.pyPython source code
.texTeX/LaTeX source code
.htmlHTML document source
.cssCascading Style Sheet
.shUNIX Shell Script.

Are you in the mode tonight? The vi editor has there modes, which we describe here.

This picture depicts the modes of vi and their relationships.

     $ UNIX 

     -------------vi fileName ↓----------------------------------
     |                                                          |
     |     -----iaoIAO, etc ↓-------    ------------------      |
     |     |                       |    | visual mode     |     |
     |     |                       |    |-----------------|     |
     |     |  insert mode          |    | character:      |     |
     |     |  Enter text by        |    |   select        v     |
     |     |  typing.              |    |   textically    ←    |
     |     |                       |    |-----------------|     |
     |     |                       |    | line:           V     |
     |     |                       |    |   select text   ←    |
     |     |                       |    |   by whole lines|     |
     |     |                       |    |-----------------|     |
     |     |                       |    | block:          ctrl-v|
     |     |                       |    |   select a      ←    |
     |     |                       |    |   block of      |     |
     |     |                       |    |   text          |     |
     |     ------ESC↓---------------    -------ESC↓-------|     |
     |                                                          |
     |     Command Mode:  mobiility, search, replace            |
     |     copy, paste, change editor settings                  |
     |                                                          |
     ------------------------------------------------------------

Introducing Command Mode

When you enter vi, it is in command mode. This is the mode that greets you each time you have a vi session. Hence we will introduce it first and return to it several times. We begin with some basic commands. Obtain the file sampler.txt; we are going to open this file using vi and try some stuff in it.

First, let us learn some mobility commands. Now open this file by typing the following.

$ vi sampler.txt
KeystrokesAction
GGo to the end of the file.
ggGo to the top of the file.
:numberGo to the chosen line number.
number + arrow keyGo number spaces in the direction of th arrow key.
^Go to the beginning of the cursor's line.
$Go to the end of the cursor's line.
control-bGo backward one screenful.
control-uGo backward one half screenful.
control-fGo forward one screenful.
control-dGo forward one half screenful.

A little Text Manipulation We show a few useful coommands for maipulating text in command mode.

KeystrokesAction
~change the case of the character the cursor is on and move over one. Non-alpha characters are unaffected.
JJoin the line the cursor is on with the next line.

Insert Mode

Getting In To type in characters, you need to be in insert mode. We are going to practice the most important ways to get into insert mode. Power users know them and use them all often.

First we show the six basic ways every piker knows.

KeystrokesHow you Enter Insert Mode
iYou insert text just before the cursor.
aYou append text just after the cursor.
oOpen a new line under the cursor.
IYou insert text at the beginning of the line.
AYou append text at the end of the line.
OOpen a new line above the cursor.

Mnemonic Step on your cat's tail and what does he say? IAO!!

yowling cat

If you only know the six modes above, you are a vi castrato.

picture of the castrato Farinelli

Now for some power modes. These are extremely useful in "search and destroy" find/replace procedures.

KeystrokesHow you Enter Insert Mode
clDelete the current character and enter insert mode. Think: change letter.
cwThis deletes the current word but it thinks of a word as a contiguous alphanumeric characters or underscores.
cWThis is like change word, but it thinks of a word as a contiguous string of any characters.
cChop the current line at the cursor and enter insert mode.
ROverwrite characters beginning at cursor. This is great for ASCII art afficianados.
SSlice out current line and enter insert mode.

We are going to practice these. You should exercise them a lot and get them to the "spinal cord" level.

Are you dotty? Dot repeats the last vi command

Search and Destroy! Search, change quarry, then find other and change using . This is a lot safer than doing a global search-and-replace.

Command Mode, a Reprise

Know your Colon If, whilst in command mode, you hit the colon key, the colon appears at the bottom of the screen.

There are four types of colon commands: mobility commands, changes of editor environment, colon-bang escapes, and file operations. We begin with file operations.

KeystrokesAction
:wThis saves the current file to disk. Think: "write."
:w fileNameThis saves the a copy of current file to disk to the file you specify.
:w! fileNameThis saves the a copy of current file to disk to the file you specify, and clobbers any existing file.
:w >>fileNameThis appends a copy of your current file to the indicated file name. This is useful for "harvesting" stuff from a file and saving into another file.
begin, end :w fileNameThis writes a range of lines to the indicated file.
:qThis quits vi and puts you back in UNIX. You will be warned if you have changes and be barred from exiting your vi session.
:q!Exit vi without saving changes.
:!unixCommandThis temporary escapes you to a shell and carries out the UNIX command you specified. This is a colon-bang escape.
:r fileName This reads the indicated file into your session starting on the line before the cursor.

Ready, set, Go! The set command changes your editing environment. We show some important commands here. The word set is always preceded by a colon.

KeystrokesAction
:set numberThis labels lines in a file with line numbers. This mode is very useful if you are programming or debugging.
:set nonumberGet rid of line numbers. You want to do this if you are doing a GUI copy/paste.
:set pasteIf you are doing a GUI paste, this pastes the text in exactly as you copied it. It prevents auto-formatting for certain file type and autoindent from "spraying" text.
:set hlsearchWhen you search for a string, all instance of the string in the file are highlighted.
:set nohlsearchTurn off the search highlighting effect.
:set ignorecaseIgnore case in all searches.
:set noignorecaseResume being case-sensitive in searches.
:set autindentTurn on autoindent.
:set no autoindentTurn on autoindent off.

Visual Mode

Before we go much further, let us learn how to use visual mode to select text. This is key for copying, pasting, searching and for a variety of other reasons you might want to control the scope of an operation.

Mastering this maode has great benefits and it can make you more efficient.

Three Modes in One Visual mode is reallly three different modes.

KeystrokesAction
:w fileName This writes selected text to a file. You can use this with ! and >> with the expected results.
d Delete selected text, and puts it in Mabel.
y Yank selected text to Mabel.
r char Replace every character of selected text with char.

With visual mode under control, we can now get to the full power of search/replace in vi.

Mabel If you are a vi user, you are familiar with Mabel, the unstable buffer. Use Mabel to keep stuff around for just a little while while copying and pasting. Let us begin with copy and paste. Each time new stuff is put in Mabel, the old stuff is overwritten.

KeystrokesAction
d Cut selected text to Mabel (visual)
gq Tidy up the selected text. Think: Gentleman's Quarterly. Mabel is not changed by this operation. Use it to break up excessively long lines in a jiffy. (visual)
y Yank selected text to Mabel (visual)
dd Cut current line to Mabel. Precede this with a number and cut that number of lines of text. (command)
yy Yank current line to Mabel. Precede this with a number and cut that number of lines of text. (command)
p Paste contents of Mabel after cursor. Precede this with a number for the expected effect. (command)

Hoist them Cookies, It's Time to get Buffer! Mabel is convenient, .... but she's unstable. You also have 26 named buffers. Here's the inside dope.

hugeola weight lifter

In this table, letter is any letter a-z and number is a positive integer which, if omitted, is taken to be 1.

Do not hit a : before using a buffer comand! The editor does its work silently. Whereever you are, just type the quote mark, then the buffer letter, then the command.

keystrokesaction
"letter numberyyYank number lines of text starting at the cursor's line to the named buffer letter.
"letter numberddCut number lines of text starting at the cursor's line to the named buffer letter.
"letter numberpPaste the contents of the named buffer letter number times just before the cursor.
"letter numberPPaste the contents of the named buffer letter number times just after the cursor.

You can use thes to store frequently typed stuff that is annoying to haul around and copy. We will do an example here with comment boxes.

Cookery with vi: A Few Useful Recipies

Copy-Paste from a GUI This is sometimes necessary. You can copy text from any application in the usual way. Then when you are ready to paste in vi, do the following.

Copy-Paste from a Terminal Window to a GUI In Linux, Select the text you want by dragging with the mouse. Then hit control-shift-C. This copies the text into the system clipboard. In a mac, just select and copy as you would otherwise.

All of My Text is Ragged and Sloppy Select a ragged paragraph with visual mode. Then hit gq (think: Gentlemen's Quarterly) and your text will be tidied up. This recipe also works when you paste in text from a word processor (Are you really using one of those...?) and you get extremely long lines.

How can I comment a range of lines? Select them using block-visual moode. Then hit I and type the comment token. Once this is done hit ESC, then enter. You can also use this to tab in a range of lines.

Larn Yer Sorry Self!

The vi editor brims with a panoply of useful capabilities. You never stop learning vi! We will list some resources here to help you become a vi ninja. If you run across cool stuff, email me and I will add your references to this page.

We begin with some free resources. Look in 'em!

Next we list some cool books and link to their Amazon pages. Put a couple on your Christmas list!