vi editing  «Prev  Next»
Lesson 5 Creating command shortcuts
ObjectiveUse the map command to create a keyboard macro.

Creating Command Shortcuts

The previous lesson described text abbreviations, which are used in text mode to expand an abbreviation into a full sequence of text. This lesson describes keyboard macros, which are used in command mode to devise editing shortcuts.
The :map command lets you create shortcuts for editing tasks that are repetitive or hard to remember. With the :map command, you assign a sequence of vi commands to a single character. The result is a keyboard macro, also called a keyboard map or simply a map. The map acts like a new vi command but performs several things at a time. Conceptually, vi maps are similar to shell aliases. Both provide a shorthand for issuing more complex commands. The table below shows the general form of the related map commands:
Keyboard macro: A keyboard macro lets you perform a sequence of vi commands as a single keystroke. Keyboard macros also are called keyboard maps because they are created using the :map command.

CommandDescription
:map c sequence Map some character, c, as a sequence of editing commands
:map List your currently defined maps
:unmap c Turn off the definition for character c

Let us say you want to transpose two words. Even though vi has no built-in command to do this, you can create a keyboard map to do it. First, try out the actual sequence in your file and write down the individual commands. Then assign the command sequence to a single character. The following SlideShow demonstrates this process:
1) Keyword Map 1 2) Keyword Map 2 3) Keyword Map 3 4) Keyword Map 4 5) Keyword Map 5 6) Keyword Map 6 7) Keyword Map 7
  1. In a file named text, there are two lines where you want to transpose words
  2. The dw command deletes the word upon, and the cursor ends up on the o in the word once.
  3. The w command moves the cursor one word forward. The cursor is now on the word a.
  4. The P command puts the deleted word, upon, before the cursor location.
  5. Use the :map command, you can assign the sequence dwwP to the letter V.
  6. Here, the cursor is move to another line where you want to transpose words.
  7. This time, you can simply press the V key to switch the two words, upon and once.

Creating Command Shortcuts
Typically, you want to assign your map sequences to keys that are unused in command mode. That is because mapping a key overrides its regular command mode meaning. The following unused keys are available:
Letters and symbols: g K q V v _ * \ =
Control characters: Ctrl-A, Ctrl-K, Ctrl-O, Ctrl-Z

Some vi commands are rarely used, so you most likely could map these keys without missing their original functions. Among the rarely used keys are f, F, t, T, z, and Z.
In the next lesson, you will learn how to use the :set command to configure vi.