Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight current search result in vim

Tags:

In emacs, when you do a search, there will be one highlight color for all occurences in the buffer, and another color for the occurence that your cursor happens to be on. I was wondering if anyone knew about similar behavior in vim, a vim plugin, or even some ideas on how to accomplish it myself in vimscript.

(note, I already know about hl-IncSearch, which is close, but not what I am looking for)

like image 886
Matt Briggs Avatar asked Aug 25 '11 23:08

Matt Briggs


People also ask

How do I highlight the current word in Vim?

To automatically highlight the current word, type z/ .

How do I highlight text in Gvim?

Use h and l to expand the selection left and right to include more words, and use j and k to expand the selection to the lines below and above. V (uppercasev) begins linewise visual mode. This selects entire lines of text at a time. Use j and k to expand the selection up and down.


2 Answers

It sounds like you want to highlight all results in the buffer. You can say

:set hls 

Which will turn on hlsearch. Then you can say

:set nohls  # turn off permanently :noh        # turn off until next time you search. 

You can also search for / highlight the word under the cursor with * (forwards) or # (backwards).

like image 149
Peter Avatar answered Sep 21 '22 02:09

Peter


As far as I know there isn't a built-in way to do what you want.

If I were to try to implement it myself... Well one way you could do it is by overriding *, n and p and combining it with something like this function:

noremap n n:call HighlightNearCursor()<CR> noremap p p:call HighlightNearCursor()<CR> noremap * *:call HighlightNearCursor()<CR>  function HighlightNearCursor()   if !exists("s:highlightcursor")     match Todo /\k*\%#\k*/     let s:highlightcursor=1   else     match None     unlet s:highlightcursor   endif endfunction 

I haven't tested it out, so this isn't a complete solution, but I think it is at least a viable approach.

EDIT : You will probably have to set some custom highlight colours. This vimwiki page gives some information about that, although I remember seeing a terser example somewhere.

EDIT AGAIN: Maybe a cleaner solution is to use Mark.vim in conjunction with the first technique. Then it would all boil down to something like:

noremap n \nn\m noremap p \np\m noremap * \n*\m 
like image 23
Nick Knowlson Avatar answered Sep 22 '22 02:09

Nick Knowlson