Basics of vi

The Three Modes Of vi

Command Mode
press 'esc' to enter command mode.

X Command Mode
when you're in command mode, press ':' to enter an x command.

Edit Mode
There are different ways you can enter edit mode:
i = insert
a = append
r = replace single character (and then it goes back into command mode)
R = type over mode (starts replacing/typing over everything)

vi Terminology Differences

In vi,
cut = delete
copy = yank

Flags

-R = read only mode

Moving Around In a Document

To use these, you must be in command mode:
0 or ^ = beginning of line
$ = end of line
h = move left
j = move down
k = move up
l = move right
w = advance by word
b = go back by word
) = advance by sentence
( = go back by sentence
} = advance by paragraph
{ = go back by paragraph
H = go to top of screen
M = go to middle of screen
L = go to bottom of screen
Ctrl-F = advance by page
Ctrl-B = go back by page
z + return = place current line at top of screen
:[linenumber] = go to line number

See What Line You Are On

Ctrl + G

Undo

u

Delete

dd = delete current line
dw = delete word
x = delete the character at the cursor

Repeat Last Command

. (dot)

Revert

:e!

Run a Program On The Current Line

!}[some command/program]

Run this command/program on the current line/selection. The program gets the current selection as and its output replaces the selection.

Run a Program On The Whole File

%!}[some command/program]

Join The Line Below To The Current Line.

J

change case

~

Map One Command To Another

map [first command][second command]

This will map the first command to the second command, so when you type the first command, it executes the second command. For example:

map g 1G

Here, if you hit 'g', it will execute '1G'.

Search

/someword = search for some word
n = find next result for search.
N = find prev result for search.

Replace

%s/MIT/Harvard/g = replace all instances of MIT with Harvard on the whole document.
5,20s/MIT/Harvard/g = ON LINES 5 - 20, replace all instances of MIT with Harvard
5,20s/MIT/Harvard/gc = same as above, but with replace confirmation each time.

Add / Remove Line Numbers From The Document

:set number = set line numbers
:no number = remove line numbers

Copy (Yank)

y2w = yank (copy) two words

Paste

P

This will paste whatever is in the current buffer (not the clipboard). You add something to the buffer by deleting or yanking it.

Save File

:w = save file
:w [filename] = save file as filename

Quit

:q = quit (will give an error if you havent saved)
ZZ = quit (same as :q)
:q! = quit regardless of whether or not you've saved

Prefixing Commands With Numbers

Any of the above commands can be used with a number in front of it, and the command is executed that many times. For example:

4H = go to fourth line from top of the screen
4w = advance forward four words
4dd = delete 4 lines

Go To Matching Brace

%