1

I am using vim 8.2 in terminal with mouse support (mouse=a) and trying to define a custom mapping for <C-LeftMouse>. The mapping itself works but the problem is that vim stops setting cursor position at the mouse click with Ctrl button pressed.

Specifically, I map <C-LeftMouse> to a command that adds the word under cursor to the search history and highlights it. After clicking, the cursor position will not change and the highlighted word will be one at the old cursor position. So, I have to first do <LeftMouse> click to change the cursor position and then <C-LeftMouse> to execute my command with the new position.

I tried mapping my command to <C-LeftRelease> but in that case <C-LeftMouse> is kept mapped to the default action ("CTRL-]") which leads to jumping to a tag if it is found.

I thought about writing a function to position the cursor and execute my custom command but I am afraid it may be not trivial (I would like also to be able to click to a different window, as in the default behavior).

Is there a way to keep vim positioning the cursor automatically after assigning commands to mouse events?

1 Answer 1

1

Let's say for example that you are talking about the *N command for the custom bit. Then the following should work:

nnoremap <C-LeftMouse> <LeftMouse>*N

(when I tried this it worked perfectly). The idea is to delegate to the default <LeftMouse> behavior, which does everything you want.

7
  • brilliant! This works really for me. Though, what if <LeftMouse> was mapped to something custom as well? I am just curious to know this for future possible cases.
    – Maxim V.
    Jun 17 at 12:54
  • 1
    That would not be a problem. The noremap versions of the map commands ensure that all key sequences on the rhs retain their original meaning and do not use any custom remappings of these key sequences.
    – Ingo
    Jun 17 at 14:13
  • @MaximV. as Ingo points out, that is why we use a non-recursive mapping. Rarely, recursive mappings are actually desired (most often with <Plug> mappings); for that, omit nore.
    – D. Ben Knoble
    Jun 17 at 16:43
  • @D.BenKnoble, there is the following minor problem with this solution: after I press <C-LeftMouse> my custom command is executed successfully but then Ctrl key seems to be not marked as released in vim (though, it is not physically pressed anymore); therefore, if I start scrolling with mouse wheel, it scrolls pages, not lines. I have to press <LeftMouse> again to reset the state. Can this be overcome somehow?
    – Maxim V.
    Jun 23 at 8:17
  • 1
    @D.BenKnoble, the problem with scrolling is solved for vim 9: d6212b8
    – Maxim V.
    Aug 4 at 9:07

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.