0

I'd like to have search highlights (set hlsearch) while the cursor is on a match and to turn it off automatically (set nohlsearch) when I move the cursor away.

Example:

foo bar foo
text text bar

After searching for bar: while the cursor is on "bar" the highlight is on, when the cursor moves away to "foo" or "text" the highlight is off and goes back on when I n/N/return to "bar".


I found a search "hack" in this plugin and used it with @Tumbler41's idea:

:autocmd CursorMoved * if (search('\%#\zs'.@/,'cnW',line('.'))) | set hlsearch | else | set nohlsearch | endif

Only highlights when I'm on the first char but that's fine for me.

  • I don't think this is possible in vanilla vim. A plugin should be able to do it though if you don't mind acting every time the cursor moves (:help CursorMoved) – Tumbler41 Jun 29 '17 at 14:18
4

It's actually a lot simpler than I originally thought, try this autocmd and see if it does what you're looking for:

autocmd CursorMoved * if (expand('<cword>') =~ @/) | set hlsearch | else | set nohlsearch | endif

This looks at the current word under the cursor and compares it the the search register (@/). If it matches, the command sets hlsearch, otherwise it unsets it.

  • Thanks, thas a great idea and it works for my example but not when I search for two words ... – laktak Jun 29 '17 at 14:39
  • Yeah, that makes sense. This only looks at a single word under the cursor. I can't put more effort into this right now, but I'll think about it and update later if I come up with a better solution. – Tumbler41 Jun 29 '17 at 14:41
  • OK, thanks anyways! I know that synID() allows to get a syntax ID for the specified position - anyone know if there is something similar for the highlight? – laktak Jun 29 '17 at 14:44
  • Found something - see update. – laktak Jun 29 '17 at 15:57

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.