Highlight variable under cursor in Vim like in NetBeans
Question
I worked in NetBeans and liked this feature: when you place cursor in a variable name all occurences of the variable are highlighted. This is very useful for quick searching all occurences of the variable. Is it possible to add this behavior to Vim?
Solution
OTHER TIPS
If you set
:set hlsearch
to highlight all occurrences of a search pattern, and then use *
or #
to find occurrences of the word under your cursor, that will get you some way to what you want. However I think a syntax-aware variable highlighting is beyond the scope of VIM.
This statement will allow a variable to enable/disable highlighting all occurences of the word under the cursor:
:autocmd CursorMoved * exe exists("HlUnderCursor")?HlUnderCursor?printf('match IncSearch /\V\<%s\>/', escape(expand('<cword>'), '/\')):'match none':""
One would activate highlighting with:
:let HlUnderCursor=1
And disable it with:
:let HlUnderCursor=0
One could easily define a shortcut key for enabling/disabling highlighting:
:nnoremap <silent> <F3> :exe "let HlUnderCursor=exists(\"HlUnderCursor\")?HlUnderCursor*-1+1:1"<CR>
Deleting the variable would prevent the match statement from executing, and not clear the current highlight:
:unlet HlUnderCursor
If you do not want to highlight language words (statements / preprocs such as if
, #define
) when your cursor is on these words, you can put this function in your .vimrc
based on the @too_much_php answer :
let g:no_highlight_group_for_current_word=["Statement", "Comment", "Type", "PreProc"]
function s:HighlightWordUnderCursor()
let l:syntaxgroup = synIDattr(synIDtrans(synID(line("."), stridx(getline("."), expand('<cword>')) + 1, 1)), "name")
if (index(g:no_highlight_group_for_current_word, l:syntaxgroup) == -1)
exe printf('match IncSearch /\V\<%s\>/', escape(expand('<cword>'), '/\'))
else
exe 'match IncSearch /\V\<\>/'
endif
endfunction
autocmd CursorMoved * call s:HighlightWordUnderCursor()
i think that what you really want is the following plugin by Shuhei Kubota:
http://www.vim.org/scripts/script.php?script_id=4306
According to the description: 'This script highlights words under the cursor like many IDEs.'
Cheers.
This variant is optimized for speed (uses CursorHold instead of CursorMoved) and compatibility with hlsearch
. The current search word highlighting will not be disrupted.
" autosave delay, cursorhold trigger, default: 4000ms
setl updatetime=300
" highlight the word under cursor (CursorMoved is inperformant)
highlight WordUnderCursor cterm=underline gui=underline
autocmd CursorHold * call HighlightCursorWord()
function! HighlightCursorWord()
" if hlsearch is active, don't overwrite it!
let search = getreg('/')
let cword = expand('<cword>')
if match(cword, search) == -1
exe printf('match WordUnderCursor /\V\<%s\>/', escape(cword, '/\'))
endif
endfunction
vim_current_word
works out of the box, is syntax aware, and allows customisable colours.