0

Consider the following function and mapping.

function! DoMagic()
    if s:isActive
       echom "Performing magic!"
    else
       " Perform default action of whatever key was mapped to this function
    endif
endfunction

map F :call DoMagic()<CR>

Is there a magic command that tells vim to pretend the mapping never happened if some condition is not true?

2

Two patterns come to mind:

nnoremap <expr> F MyExprFunc('F')
nnoremap F :call MyFunc('F')<CR>

The function has to know what key is mapped to it, so it can do the appropriate thing.

Then:

function MyExprFunc(key)
  if blah blah
    return a:key
  else
    return magic_key_sequence
  endif
endfunction

function MyFunc(key)
  if blah blah
    exec printf("normal! %s", a:key)
  else
    " Do some magic
  endif
endfunction
| improve this answer | |
  • I think i accidentally inverted the conditional, but the intent should be clear – D. Ben Knoble May 28 '19 at 20:50
2

The generic way to do this is to use the :norm! <key>[<key>] command. The bang (!) is important, it will execute the given keys as normal commands as they are not mapped.

Another more low-level alternative is to make use of the feedkeys() function, that allows to insert keys into the typeahead buffer and allows to define whether mappings should apply or not (among others). See the documentation: :h :norm! and :h feedkeys()

| improve this answer | |

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.