Alexander Kondratskiy
Alexander Kondratskiy

Reputation: 4275

Change behaviour of mapping in certain cases, and reuse functionality in all others

I'm trying to change the behavior of "K" in certain circumstances, but keep its original functionality in all the others. Here's my failed attempt

function! GetDocumentation()
    if &filetype == 'java'
        JavaDocSearch
    else
        normal K
    endif
endfunction

nnoremap K :call GetDocumentation()<CR>

However since I use K in a function, when it's called as result of the remapping, the new mapping of K is used, and I get infinite recursion. I guess I could somehow fit the gist of the function onto the nnoremap line, but it seems awkward, and it would be nice to forcefully use the original mapping of a key.

Hope this makes sense,

Thanks.

Upvotes: 1

Views: 71

Answers (2)

ZyX
ZyX

Reputation: 53604

@ib. is right: you should be using :normal! here. But function is an overkill: the following expression mapping is sufficient:

nnoremap <expr> K ((&filetype is# "java")?(":JavaDocSearch\n"):("K"))

This mapping won’t trigger itself due to nore and also is eight lines shorter.

Upvotes: 2

ib.
ib.

Reputation: 28934

The :normal command without the ! modifier—as it is used in the function—executes its arguments as Normal mode commands taking mappings into consideration. This is why the line

        normal K

runs the mapping that has overridden the default handler. So, to ignore mappings shadowing commands, change the line as follows,

        normal! K

Upvotes: 3

Related Questions