Vim Tips Wiki

Changes: Auto highlight current word when idle


Back to page

(create introduction and enhance/fix script (need augroup! to delete the group))
m (fix category typo)
Line 8: Line 8:

Revision as of 22:26, April 21, 2010

Tip 572 Printable Monobook Previous Next

created 2003 · complexity basic · author mosh · version 6.0

Vim can easily highlight all search pattern matches and search for the current word (the word under the cursor). This tip shows how to automatically highlight all occurrences of the current word without searching. That can useful when examining unfamiliar source code: just move the cursor to a variable, and all occurrences of the variable will be highlighted.


Put the following code in your vimrc, or create file ~/.vim/plugin/autohighlight.vim (Unix) or $HOME/vimfiles/plugin/autohighlight.vim (Windows) containing the script below. Then restart Vim.

To automatically highlight the current word, type z/. To turn off, type z/ again.

" 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
    augroup auto_highlight
      au CursorHold * let @/ = '\<'.expand('<cword>').'\>'
    augroup end
    setl updatetime=500
    echo 'Highlight current word: ON'
    return 1


Around Wikia's network

Random Wiki