Vim Recipes Extending Creating Keyboard Shortcuts with Key Mappings

Creating Keyboard Shortcuts with Key Mappings

Problem

You'd like to execute a command, or series thereof, with a keyboard shortcut rather than continually type it in. Or, you'd like to change an existing keyboard shortcut so that it does something more useful.

For example, you use the <Space> key to page down in other applications, and you'd like to do the same in Vim. Or, you regularly reformat paragraphs with gqap, but would prefer to simply hit Q.

Solution

Use key mappings. A map is simply a key combination followed by another key combination. When you enter the first key combination Vim acts as if you entered the second.

For example, to remap <Space> to <PageDown> you execute :map <Space> <PageDown>. The map command creates a mapping for Normal, Visual, and Operator Pending mode; i.e. if you press <Space> in Insert mode this mapping, thankfully, has no effect.

Mapping Q to gqap is similarly straight forward: :nmap Q gqap. Unlike map, :nmap only takes effect in Normal mode. We used nmap here because this mapping doesn't make sense in other modes: in Insert mode we want Q to insert a literal Q, and in Visual mode we want to reformat the selected text rather than the current paragraph. The Visual mode mapping is :vmap Q gq.

The other main types of mapping commands are:

:imap
Insert mode only.
:cmap
Command-line only.
:map
Normal, Visual, and Operator-pending.

Discussion

Keyboard mapping is yet another way to save valuable keystrokes. If you find yourself executing a command repeatedly create a mapping. It's also useful for creating more sensible aliases for existing keyboard shortcuts that you can never quite remember.

It's generally recommended to map the function keys (<F1>-<F12>), as well as their shifted counterparts (e.g. <Shift>-<F3>) because they're not used by Vim<F1> is used for :help but pretty useless given that you'd normally use :help topic.. As long as you use a combination that doesn't interfere with the commands you do use, you're free to use whatever you want, though.

Before you create a mapping you might like to check what, if anything, it's currently being used for. You can do this by executing :help key, e.g. :help <F1> will show that Vim maps it to :help. If you want to see the user-defined mappings (whether set by you or a plugin) call the :map command with no arguments. This works will the mode-specific map commands outlined above, too, so :imap will show Insert mode mappings.