Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to highlight all occurrences of a word in vim on double clicking

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 I find really interesting in notepad++. You can double-click on a word and it highlights all occurrences of that word automatically. I was wondering if I could do something like that with vim? So the question is how to highlight all occurrences of a word when you double click on the word in vim.

Obviously, I don't want to search for that word, or change my cursor position, just highlighting. My :set hlsearch is also on.

probably you may want to avoid the mouse in vim, but I make an exception here :).

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

like image 481
aminfar Avatar asked Jul 29 '11 17:07

aminfar


2 Answers

If you want to highlight the word under the cursor like *, but do not want to move the cursor then I suggest the following:

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

Basically this command sets the search register (@/) to the current word and turns on 'hlsearch' so the results are highlighted. By setting @/ the cursor is not moved as it is with * or #.

Explanation:

  • <silent> - to not show the command once executed
  • <2-LeftMouse> - Double click w/ the left mouse button
  • @/ is the register used for searching with / and ?
  • expand('<cword>') get the current word under the cursor
  • escape(pattern, '\') escape the regex in case of meta characters
  • \V use very-non-magic mode so everything meta character must be escaped with /
  • \< and \> to ensure the current word is at a word boundary
  • set hls set 'hlsearch' on so highlighting appears

If setting the @/ register is not your cup of tea than you can use :match instead like so:

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

To clear the matches just use:

:match none
like image 175
Peter Rincker Avatar answered Sep 23 '22 22:09

Peter Rincker


You can map * to double-click by a simple mapping:

:map <2-LeftMouse> *

If you want to use said functionality in insert-mode you can use this mapping:

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

Without (Ctrl-o) the * would be printed

[EDIT] As ZyX pointed out, it is always a good idea to use noremap respectively inoremap if you want to make sure that if * or <c-o> will be mapped to something else, that this recursive mapping won't be expanded.

like image 22
das_weezul Avatar answered Sep 21 '22 22:09

das_weezul