Maneuver easily between vi's dual modes in Linux

Take the confusion out of switching between insert and command modes in vi's Linux text editor.

Take the confusion out of switching between insert and command modes in vi's Linux text editor.

The vi text editor has been around almost as long as Unix, and consequently can be found installed on virtually any Unix-based system. Although the small and efficient text editor is not as powerful or customizable as Emacs, vi can be a lean, mean editing machine if you know how to use it.

Whereas Emacs relies on adding a Ctrl key to every command, vi uses a slightly more complicated system. More specifically, there are two modes that vi uses, command mode and insert mode--most of the confusion around vi can be attributed to this dual-mode aspect of vi. When you are in insert mode, anything you type will be added to your text document; when you are in command mode, the editor is expecting specific commands to move around a document, cut, paste, etc.

Opening a document with vi is just like Emacs. Simply type vi filename to open (or create) the document of the filename you specified. vi starts up in command mode, and whenever you want to get back to the command mode just press the Esc key. If you are in command mode and you try to type anything other than a valid command, vi will just beep at you, a frequent source of some frustration. Moving the cursor
To move around your file, use the following commands:

Command Function
h Move cursor one character to the left
j Move cursor one line down
k Move cursor one line up
l Move cursor one character to the right
w Move cursor right to the beginning of a word
e Move cursor right to the end of a word
b Move cursor left to beginning of word
$ Move cursor to end of current line
) Move cursor to beginning of next sentence
( Move cursor to beginning of previous sentence

Moving around by screens
You can also move around by screens, using the following commands:

Command Function
Ctrl+b Move back one screen
Ctrl+d Move down half a screen
Ctrl+f Move down one screen
Ctrl+j Move up half a screen
To restore a file that was being edited during a system crash, try using the recover option by typing vi -r filename. To undo changes you have made, type u, which will undo the last change made, or the uppercase U to undo all changes made to the current line. To get vi's online help, just use the ? command.

Finally to save your file and exit vi, type :wq or Z, following by typing another Z. If you want to exit without saving changes just type :q!.