Tuesday, February 15, 2011

vi cheat sheet

The default editor that comes with the UNIX operating system is called vi (visual editor).
The UNIX vi editor is a full screen editor and has two modes of operation:

1. Command mode commands which cause action to be taken on the file, and
2. Insert mode in which entered text is inserted into the file.
Vi has two modes insertion mode and command mode. The editor begins in command mode, where the cursor movement and text deletion and pasting occur. Insertion mode begins upon entering an insertion or change command. [ESC] returns the editor to command mode (where you can quit, for example by typing :q!).

To start vi:
vi filename edit filename starting at line 1
vi -r filename recover filename that was being edited when system crashed

To Exit vi:
:x quit vi, writing out modified file to file named in original invocation
:wq quit vi, writing out modified file to file named in original invocation
:q quit (or exit) vi
:q! quit vi even though latest changes have not been saved for this vi call

Moving the cursor:
j move cursor down one line
k move cursor up one line
h move cursor left one character
l move cursor right one character
0 move cursor to start of current line (the one with the cursor)
$ move cursor to end of current line
w move cursor to beginning of next word
b move cursor back to beginning of preceding word

Screen Manipulation: (the symbol ^ before a letter means that the key should be held down while the letter key is pressed):
^f move forward one screen
^b move backward one screen
^d move down (forward) one half screen
^u move up (back) one half screen
^l redraws the screen
^r redraws the screen, removing deleted lines

Adding, Changing, and Deleting Text:
u UNDO WHATEVER YOU JUST DID; a simple toggle

Inserting or Adding Text:
The following commands allow you to insert and add text. Each of these commands puts the vi editor into insert mode; thus, the key must be pressed to terminate the entry of text and to put the vi editor back into command mode.
* i insert text before cursor, until hit
I insert text at beginning of current line, until hit
* a append text after cursor, until hit
A append text to end of current line, until hit
* o open and put text in a new line below current line, until hit
* O open and put text in a new line above current line, until hit

Deleting Text:
* x delete single character under cursor
* dd delete entire current line

Cutting and Pasting Text:
yy copy (yank, cut) the current line into the buffer
p put (paste) the line(s) in the buffer into the text after the current line