How to auto highlight the current word in vim?
Something like this?
set updatetime=10
function! HighlightWordUnderCursor()
if getline(".")[col(".")-1] !~# '[[:punct:][:blank:]]'
exec 'match' 'Search' '/\V\<'.expand('<cword>').'\>/'
else
match none
endif
endfunction
autocmd! CursorHold,CursorHoldI * call HighlightWordUnderCursor()
This won't clobber the search register but will use the same highlighting as would normally be used. (If you want a different highlight color change Search
to that highlight group.) A short update time is needed so that the CursorHold event it fired fairly often. It also won't highlight anything if the cursor is above punctuation or whitespace.
The iskeyword
setting determines what is considered part of a word when expand('<cword>')
is used.
Yes there is a vim plugin for highlighting the occurances of a word automatically. This one is implemented exclusively for $variables
and ->properties
in .php files.
DEMO :
And here is the same one but adapted for Perl files.
DEMO :
May be you can modify it for your purpose.
Hope this helps.
There's a script on vim.wikia.com for doing exactly that. It waits until you've stopped moving the cursor and then highlights all instances of the current word. You can then use n
and N
to jump between them like you normally would with search results.
I'm copying it here in case the link goes down:
" Highlight all instances of word under cursor, when idle.
" Useful when studying strange source code.
" Type z/ to toggle highlighting on/off.
nnoremap z/ :if AutoHighlightToggle()<Bar>set hls<Bar>endif<CR>
function! AutoHighlightToggle()
let @/ = ''
if exists('#auto_highlight')
au! auto_highlight
augroup! auto_highlight
setl updatetime=4000
echo 'Highlight current word: off'
return 0
else
augroup auto_highlight
au!
au CursorHold * let @/ = '\V\<'.escape(expand('<cword>'), '\').'\>'
augroup end
setl updatetime=500
echo 'Highlight current word: ON'
return 1
endif
endfunction
As noted in a comment on that page, if you always want this feature on you can just call the function from your vimrc
after defining it. That way you can use z/
(or whatever shortcut you assign it to) to turn it off again later.