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 theE
command is often identical toe
.In the remaining examples, we assume that
e
has 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
q
helps 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
e
is already mapped toea
). The ability to use nested map sequences is controlled by vi'sremap
option (), 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
lb
to 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 theb
command.But if the cursor were already at the beginning of the word, the
b
command would move the cursor to the previous word instead. To guard against that case, type anl
before 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 theb
withB
and thee
withEa
. In all cases though, thel
command 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