Reputation: 33628
How can I use a variable when mapping keys in vim? The specific problem that I am trying to solve is the following. I need these key mappings:
nnoremap <C-1> 1gt
nnoremap <C-2> 2gt
nnoremap <C-3> 3gt
... and so on.
Can I specify one mapping; something like
nnoremap <C-x> xgt
where x takes the value of the key pressed (which can be from 1..9)
Thank you.
Edit 1: Towards the solution (not yet complete) thanks to Peter Rincker
I can use the function
function gotoTab(num)
execute "normal" a:num."gt"
endfunction
If I :call goToTab(3)
, it goes to tab 3.
How do I map Command-x (D-x) to goToTab(x) where x is between 1..9. How do I read the number from a Command-x press?
Upvotes: 6
Views: 2972
Reputation: 45117
I got bad news. You can not map <c-1>
, etc. You can only bind <c-6>
which I wouldn't do as it is very handy.
It also seems like you are doing a heavily tab centric workflow. I know it might sound weird but maybe use less tab panes and more buffers. Here are some nice posts about it:
... Ok, but I really want to do this variable mapping thing. You have options:
:execute
to create mappings7gt
. The 7
is the count.Example of using :for
and :execute
:
for i in range(1, 9)
execute "nnoremap \<d-" . i . "> " . i . "gt"
endfor
Note: this uses <d-...>
syntax for Command which is only available on MacVim and no terminal support (See :h <D-
). You can use <a-...>
for Alt. However I must warn you using Alt on the terminal can be tricky.
For more help see:
:h keycodes
:h map-which-keys
:h :for
:h :exe
:h count
:h v:count
:h range(
Upvotes: 6