1

[I have read How to debug a mapping? and although that is a great starting point I am still clueless why this does not work.]

I want 2* to search for the next occurence of the previous word in combination with the current word.

I have defined it in my vimrc in the following way:

nnoremap 2* hevgeb"zy/\<<C-R>z\><CR>

but pressing 2* ignores this mapping and searches for the 2nd occurence of the current word.

:map 2* shows that the keys are mapped correctly:

n  2*          * hevgeb"zy/\<<C-R>z\><CR> 

Pressing o2* inserts 2* on a new line and thereby proves that the keys are not intercepted, vim receives the keys as expected.

Leaving out the 2 remaps asterisk as expected and shows that hevgeb"zy/\<<C-R>z\><CR> does what it's intended to do. I am not happy with this implementation because it changes a register (z) but surprisingly I have not found an easy way to avoid that.

In a different mapping 2 followed by tab to show a table of contents works some times and some times not, but pressing it several times eventually triggers it:

nnoremap 2<Tab> :exec '!grep --color=always --line-number -E "^[[:space:]]*((class\|def) +([A-Za-z0-9_]+)\|\# (===\|---).*)"' shellescape(@%, 1) " \| less -R"<cr>

Based on that experience I have tried pressing 2* and here, too, it works in some cases. But what's annoying for the 2tab mapping is not acceptable for the 2* mapping because it moves the cursor.

Does somebody know in which circumstances these mappings work and in which not and how to trigger them reliably? I thought that pressing escape before might help but it does not. Sometimes it works, sometimes it does not.

jakun
  • 155
  • 3

1 Answers1

4

It is * that you need to map, not 2*:

nnoremap <expr> * v:count1 == 2 ? 'hevgeb"zy/\<<C-R>z\><CR>' : '*'
  • This is an "expression mapping", where the RHS is the result of an expression evaluated at runtime. See :help map-<expr>.
  • If :help v:count1 equals 2, then do your custom magic.
  • If not, just do [count]*.

So, basically…

What you press What you get
* *
1* 1*
2* hevgeb"zy/\<<C-R>z\><CR>
3* 3*
4* 4*
5* 5*
etc. etc.

That said, your mapping works as-is, here, so you should probably do some digging on your side, starting with $ vim --clean and $ vim -Nu NONE.

romainl
  • 40,486
  • 5
  • 85
  • 117