More Examples of Mapping Keys in vi
The examples that follow will give you an idea of the clever shortcuts possible when defining keyboard maps.
- Add text whenever you move to the end of a word:
map e ea
Most of the time, the only reason you want to move to the end of a word is to add text. This map sequence puts you in text-input mode automatically. Note that the mapped key,
e, has meaning in vi. You're allowed to map a key that is already used by vi, but the key's normal function will be unavailable as long as the map is in effect. This isn't so bad in this case, since theEcommand is often identical toe.In the remaining examples, we assume that
ehas been mapped toea. - Save a file and edit the next one in a series ():
map q :w^M:n^M
Notice that you can map keys to ex commands, but be sure to finish each ex command with a RETURN. This sequence makes it easy to move from one file to the next and is useful when you've opened many short files with one vi command. Mapping the letter
qhelps you remember that the sequence is similar to a "quit." - Put troff emboldening codes (fB and fP) around a word:
map v i\fB^[e\fP^[
This sequence assumes that the cursor is at the beginning of the word. First, you enter text-input mode, then you type the code for bold font. (In map commands, you don't need to type two backslashes to produce one backslash.) Next, you return to command mode by typing a "quoted" () ESC. Finally, you append the closing troff code at the end of the word, and you return to command mode. Of course, the map is not limited to troff font codes. You can use it to enclose a word in parentheses or C comment characters, to name just a few applications.
This example shows you that map sequences are allowed to contain other map commands (the
eis already mapped toea). The ability to use nested map sequences is controlled by vi'sremapoption (), which is normally enabled. - Put troff emboldening codes around a word, even when the cursor is not at the beginning of the word:
map V lbi\fB^[e\fP^[
This sequence is the same as the previous one, except that it uses
lbto handle the additional task of positioning the cursor at the beginning of the word. The cursor might be in the middle of the word, so you want to move to the beginning with thebcommand.But if the cursor were already at the beginning of the word, the
bcommand would move the cursor to the previous word instead. To guard against that case, type anlbefore moving back withb, so that the cursor never starts on the first letter of the word. You can define variations of this sequence by replacing thebwithBand theewithEa. In all cases though, thelcommand prevents this sequence from working if the cursor is at the end of a line. (To get around this, you could add a space to the end of the word before typing the keymap.)
- DG from Anonymous' vi Editor, Chapter 7