Opt
Opt

Reputation: 4804

Mapping a sequence of keystrokes to command-line commands

Is there a way to map a sequence of keystrokes to a command-line commmand (a command entered after : in the Ex mode) in vim?

Upvotes: 5

Views: 4253

Answers (1)

catchmeifyoutry
catchmeifyoutry

Reputation: 7349

Yes, and it's intuitively called :map

Example:

:map foo :echo "bar"<CR>

No when in insert mode you press the keys foo vim will respond with "bar". Type :help :map in vim for more information. You can place mappings you want to load by default in your .vimrc file.

You can independently map keystrokes for different modes, such as insert mode (:imap) and visual mode (:vmap). See also vim help on the subject of remapping (:noremap)

Update

If you want to use an alias for command mode (but this can be done for insert mode too), you'll want to use abbreviations.

To define an abbreviation for command mode, use :ca (which is a shorthand for :cabbrev). See vim help :help :ca and for more info :help :abbreviations.

Notice that unlike map, abbreviations are not replaced by vim commands but by literal characters. Abbreviations are triggered when you press space or enter.

Examples:

" let me type :syn=cpp instead of :set syntax=cpp
"
:ca syn set syntax

" fix my favorite spelling error
"
:abbr teh the

" this does something different than the :map example above
"
:iabb foo :echo "bar"<CR>

" this is ugly, misusing an abbreviation as :map by simulating ESCAPE press
"
:iabb hello <ESC>:echo "world"<CR>

Upvotes: 8

Related Questions