timakro
timakro

Reputation: 1851

Map key to itself and another key without overwriting the previous mapping of the key

I'm writing a plugin and I need to detect when a user uses the n key to get to the next search result.

nmap n n:echo "detected!"<CR>

Unfortunately this overwrites all mappings the user defined for n, for example centering on the cursor after jumping to the next search result.

nmap n nzz

Is there a way to map n to whatever the user mapped to n and my echo command? In this example the result should be equal to:

nmap n nzz:echo "detected"<CR>

Upvotes: 5

Views: 483

Answers (1)

yolenoyer
yolenoyer

Reputation: 9465

As melpomene wrote, you can take profit of the maparg() function, for example:

function! AppendMap(name, mode, rhs)
    let l:oldrhs = maparg(a:name, a:mode)
    exe printf('%smap %s %s', a:mode, a:name, l:oldrhs.a:rhs)
endf

call AppendMap('n', 'n', ':echo "detected"<CR>')
" If key 'n' was mapped to 'nzz', then it is now mapped to 'nzz:echo "detected"<CR>'

Upvotes: 4

Related Questions