I'm wondering if it is possible to check in vimscript if a key (or key combination) is already bound?

I know about the :map command which lets me see visually which keys are bound to what actions, but what I am looking for is a way to check it programmatically and perform actions conditionally.

My concrete scenario is the following: I like the the possibility to dynamically/manually map <leader><leader> to what I need in different cases. (eg. while programming python: run the script. Or compile while programming c++). I usually do it by typing :nmap <leader><leader> :!make && run program manually while editing.

Now I want to check in my .vimrc if the combination is already bound (by a plugin, or manually) and if not map it to a default action.

In short words: How can I map a key only if it is not already bound?

  • 3
    I think you are facing a XY problem. Instead of conditionnaly mapping your key, you might prefer reading :h ftplugin and :h 'makeprg'. The idea is to set a different makeprg for each filetype you're dealing with and having just a generic mapping which will call :make. Otherwise maybe check :h :redir to see how to get the output of map into a variable.
    – statox
    Oct 8, 2018 at 11:29

1 Answer 1


You've got:

that, respectively permit to:

  • get the exact mapping bound to the exact keybinding passed as parameter
  • check whether there is any mapping bound to a keybinding starting as the parameter

On the other way around (get which keybinding could be bound to an action), so far I've only found the following

function! lh#mapping#who_maps(rhs, mode) abort
  " lh#askvim#execute  =~ split(execute(...), "\n")
  let maps = filter(lh#askvim#execute(a:mode . 'map'), 'v:val =~ a:rhs."$"')
  " Unfortunatelly, knowing exactly what mapping is associated to a
  " keybinding, it's best to use maparg()
  let lhs_list = map(maps, 'split(v:val)[1]')
  let mappings = map(lhs_list, 'maparg(v:val, a:mode, 0, 1)')
  call filter(mappings, 'v:val.rhs == a:rhs')
  return mappings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.