Navigating Within a File
The vi editor uses the following keystrokes to move left, right, up, and down, but if you have cursor keys, you can use them, too. Here are some useful keystrokes:
HThis is the left arrow; it's easy to remember because it's the leftmost key in the four-key set.
JUse this for the down arrow.
KUse this for the up arrow.
LUse this for the right arrow.
Figure 3.1 illustrates how these keys work.
Figure 3.1 Cursor key directions.
As you can see in Figure 3.1, one of the ways to remember the keyboard cursor keys is to just look down at the home row and remember that H is the leftmost, J goes jown (down), K goes kup (up), and L is on the right. Makes perfect sense, right?
You'll see questions about the movement keys on the exam. The arrow keys are a favorite topic, whereas the Ctrl keys don't get much love. Know those arrow movement keys!
Other keystrokes move you around in vi using the Ctrl key and a letter:
Ctrl+FMoves forward a page
Ctrl+BMoves backward a page
Ctrl+DMoves forward a half-page
Ctrl+UMoves backward a half-page
Just about any keystroke or action can be done X number of times by prefixing it with a number.
For example, to move the cursor to line 5, you would press 5G. Moving 12 words to the right is accomplished with 12W.
A lot of editing, inserting, and escaping back can sometimes leave the message line without some pertinent information showing, such as the name of the file being edited. When you get confused as to where you are or under which filename you saved this iteration of the file, pressing Ctrl+G shows the filename, total number of lines, and current position expressed as a percentage of the total lines in the file.
A useful and largely unknown set of options are the undo operations. You press U in Command mode to undo a single operation or the latest in a series of changes. If you opened a file, made 30 changes, and then pressed the U key 30 times, you'd end up with the exact same file you had opened.
Don't bother trying U to undo all changesthat's not what it's for. Instead, use the :+E+! keystroke combination in Command mode to undo all changes since the last disk write to the file.