T.F.
T.F.

Reputation: 237

can I map a key binding to a function in vimrc?

So originally I had the following config in my vimrc

map <F5> :call Compile()<CR>

But somehow I feel F5 is not very convenient, so I tried to map it to <A-q> or <A-1>, which seem did not work. I also tried <C-q> and <C-1>, seems nothing happened.

So I can not map a function to a key binding?

Upvotes: 20

Views: 18291

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172570

Some key combinations, like Ctrl + non-alphabetic cannot be mapped, and Ctrl + letter vs. Ctrl + Shift + letter cannot be distinguished. (Unless your terminal sends a distinct termcap code for it, which most don't.) In insert or command-line mode, try typing the key combination. If nothing happens / is inserted, you cannot use that key combination. This also applies to <Tab> / <C-I>, <CR> / <C-M> / <Esc> / <C-[> etc. (Only exception is <BS> / <C-H>.) This is a known pain point, and the subject of various discussions on vim_dev and the #vim IRC channel.

So, <C-1> is out, but the other mappings should work just fine; for example:

nnoremap <C-q> :call Compile()<CR>

You can check that no other plugin cleared / overwrote the mapping via

:nmap <C-q>
n  <C-Q>       * :call Compile()<CR>

Additional tips

  • You should use :noremap; it makes the mapping immune to remapping and recursion.
  • :map covers normal, visual, and operator-pending modes. You probably only want to start compilation from normal mode, so :nnoremap is more precise. (And if you later add a visual mode mapping for compiling just the selection, the key is still free for use in that mode.)

Upvotes: 13

Related Questions