Recipe 6.11. Mapping Commands to Keystrokes
6.11.1 Problem
Some of Vim's
commands are long and complex, and you are amassing your own
collection of custom commands, so you would like to create keyboard
shortcuts for your most-used commands.
6.11.2 Solution
Use the map command to assign custom keystrokes to
any command or text string. map creates
keymappings for Normal mode; map! creates
keymappings for Insert mode. To see your current set of mappings,
type:
:map
or:
:map!
|
Be careful when creating your own maps—don't
map to keys that already have commands assigned to them by Vim, as
map will happily, and without comment, overwrite
them. (This is a good reason to wait until you're
proficient before going crazy with maps.)
|
|
Creating a new keymapping is done like this:
:map <F3> :runtime! syntax/2html.vim
This command adds HTML tags to the current document, in a new window.
Now hitting F3 activates it.
You can delete a map like this:
:unmap <F3>
You have to spell out the names of the Esc,
<CR> (carriage return) and
<F2>-<F12> keys, because if you
simply press the keys they will execute whatever command is assigned
to them.
This example maps a command to F3 that goes into Insert mode, inserts
an HTML tag around a word, and leaves off in Insert mode so you can
continue typing:
:map <F3> i<B><Esc>ea</B><Esc>a
These are examples of Insert mode mappings for quickly adding HTML
tags. They're fast, because you never leave Insert
mode, and it's unlikely that such comma-letter
combinations will come up in ordinary typing.
:map! ,ah <A href="">
:map! ,a </A>
:map! ,b <B><Esc>ea</B><Esc>a
:map! ,i <I><Esc>ea</I><Esc>a
:map! ,l <LI><Esc>ea</LI><Esc>a
6.11.3 Discussion
The safest keys to use are F2-F12 and Shift-F2-F12. (F1 is mapped to
Vim's help pages.) However, you'll
use those up pretty quickly, so using combinations like comma-letter
that usually do not occur in normal usage gives you the ability to
create as many keymappings as you like.
See :help map-which-keys for complete
information on Vim's built-in keymappings. You can
also query Vim's help for a specific key or
combination:
:help CTRL-V
:help F5
:help /b
Remember to spell out CTRL and F5; don't press the
Ctrl and F5 keys.
6.11.4 See Also
Vim's online help (:help
2html.vim, :help key-mapping) Chapter 8 of Vi IMproved—Vim Chapter 7 of Learning the vi Editor
|