Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

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?

like image 983
T.F. Avatar asked Nov 09 '16 10:11

T.F.


People also ask

Does vim allow for custom key bindings?

I was delighted to learn that you can have your own key mappings in Vim. It is documented very well in the vim help section.

What does Silent mean in Vimrc?

<silent> tells vim to show no message when this key sequence is used. <leader> means the key sequence starts with the character assigned to variable mapleader -- a backslash, if no let mapleader = statement has executed yet at the point nmap executes.

How do you call a function in vim?

Calling A Function Vim has a :call command to call a function. The call command does not output the return value. Let's call it with echo . To clear any confusion, you have just used two different call commands: the :call command-line command and the call() function.

What are vim bindings?

By Vim, I mean literally Vim, the command-line text editor. And by bindings, I mean keyboard commands that do specific things in the editor.


1 Answers

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.)
like image 64
Ingo Karkat Avatar answered Oct 01 '22 13:10

Ingo Karkat