How to highlight all occurrences of a word in vim with a double click

When I'm on Windows, I use notepad ++, and on Linux I use vim. I really like vim. But there is at least one thing that I find very interesting in notepad ++. You can double-click on a word and it will automatically highlight all occurrences of that word. I was wondering if I can do something like this with vim? So the question is how to highlight all occurrences of a word when you double-click on a word in vim.

Obviously, I don’t want to search for this word or change the position of the cursor, just highlighting. Mine is :set hlsearchalso included.

You might want to avoid the mouse in vim, but I am making an exception here :).

I know it *does the same job, but what about the mouse?

+5
source share
2 answers

You can match * to double-click a simple match:

:map <2-LeftMouse> *

If you want to use the specified functions in insert mode, you can use this mapping:

:imap <2-LeftMouse> <c-o>*

Without (Ctrl-o) the * character will be printed

[EDIT] As ZyX pointed out, it is always recommended to use noremapaccordingly inoremapif you want to make sure that if *or <c-o>is matched against something else, this recursive mapping will not be expanded.

+14
source

If you want to highlight a word under the cursor like *, but don’t want to move the cursor, then I suggest the following:

nnoremap <silent> <2-LeftMouse> :let @/='\V\<'.escape(expand('<cword>'), '\').'\>'<cr>:set hls<cr>

(@/) 'hlsearch', . @/, , , * #.

:

  • <silent> -
  • <2-LeftMouse> -
  • @/ - , / ?
  • expand('<cword>')
  • escape(pattern, '\')
  • \V , /
  • \< \>, ,
  • set hls 'hlsearch',

@/ , :match, :

nnoremap <silent> <2-leftMouse> :exe 'highlight DoubleClick ctermbg=green guibg=green<bar>match DoubleClick /\V\<'.escape(expand('<cword>'), '\').'\>/'<cr>

To clear matches, use:

:match none
+17
source

All Articles