Consider the following function and mapping.

function! GetInvoker()
    echom "I was invokeed by the key "
    echom <This_should_echo_F_or_G>

map F :call GetInvoker()<CR>
map G :call GetInvoker()<CR>

How do I determine which key that the user actually typed from inside the function?

  • 2
    Simpler just to pass the mapped key as an arg to the function – D. Ben Knoble May 28 '19 at 20:51
  • Gotta agree with DBK. From the standpoint of the called function the input buffer when call occurs as part of a mapping is indistinguishable from a manual/direct call to the function, I believe. Unless there's some special internal v: variable or the like that I'm not aware of that contains this information it's likely impossible to determine. – B Layer May 29 '19 at 5:56
  • 1
    not possible currently. There was some discussion about a new v:variable that allows that, but it has not been implemented yet. – Christian Brabandt May 29 '19 at 6:01
  • @ChristianBrabandt Cool. Would it be something simple/granular like v:caller_mapping (e.g. mapped key(s) or null) or something broader (e.g. dict with various data about caller/callee state)? Or did it even get that far? – B Layer May 29 '19 at 6:08
  • 2
    no it didn't get that far. I believe it was just a whishlist to allow something like that. That's actually quite an old wish, I remember I wished for that years ago when I started with Vim and the workaround to give the key as argument to the function (while ugly) works quite well. So I wouldn't bet on implementing it anytime soon. – Christian Brabandt May 29 '19 at 6:32

You need to explicitly pass the key into the function; there's no built-in way to obtain that from Vim; this isn't a common use case. As plugins should only have a few keymappings, this approach should be fine. Metaprogramming (e.g. a :for loop) could be used to automatically define many mappings without duplicating all the information.

function! GetInvoker( key )
    echom "I was invokeed by the key "
    echom a:key

map F :call GetInvoker('F')<CR>
map G :call GetInvoker('G')<CR>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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