Vim Tips Wiki
Register
Advertisement

Proposed tip Please edit this page to improve it, or add your comments below (do not use the discussion page).

Please use new tips to discuss whether this page should be a permanent tip, or whether it should be merged to an existing tip.
created June 19, 2008 · complexity basic · author Anon · version 7.0

Add the following to your vimrc:

function! DoHighlight(hlnum) range
  let l:saved_reg = @"
  execute "normal yw"
  let hls=@"
  execute a:hlnum . "match hl" . a:hlnum . " /" . hls . "/"
  let @" = l:saved_reg
endfunction

:highlight hl1 term=bold ctermfg=blue guifg=blue
:highlight hl2 term=bold ctermfg=green guifg=green
:highlight hl3 term=bold ctermfg=red guifg=red

:noremap 1m :call DoHighlight(1)<CR>
:noremap 2m :call DoHighlight(2)<CR>
"3match is used by the matchparen plugin, however
:noremap 3m :call DoHighlight(3)<CR>

You can now highlight all occurrences of a word by moving the cursor to a word, then pressing 1m, 2m or 3m.

Comments

This is a clever little function, but I'd suggest using matchadd() (and matchdelete()) in the function and v:count in the mapping instead of match, 2match, and 3match. This would allow unlimited matches. Also, the ":" is unneeded in the execute statement. I have removed this and the commented-out debug code. In addition, yw may not be what you want...if you're trying to get the entire word under the cursor, yiw will do that, or even pass it in to the function as an argument and use <C-R><C-W> in the mapping.

See:

Go ahead and add your own comments or edit my talk page if you want to discuss any of these comments. I think this could be a fairly good tip with a little work!

--Fritzophrenic 13:13, 19 June 2008 (UTC)


The Mark script does this, and even more. Check it out!

--Inkarkat 14:45, 20 June 2008 (UTC)


I think that a tip that highlights text should offer a way to remove the highlighting. Unfortunately, after fixing issues mentioned above, adding unhighlight, and using matchadd(), you would have a somewhat complex script, and probably the script mentioned above would be preferable. --JohnBeckett 11:29, 30 August 2008 (UTC)

Advertisement