Skip to content

Instantly share code, notes, and snippets.

@akesling
Forked from akkartik/ondemandhighlight.vim
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akesling/8697928 to your computer and use it in GitHub Desktop.
Save akesling/8697928 to your computer and use it in GitHub Desktop.
" Highlight a word from inside vim. The color is chosen at random but
" persisted across sessions.
" By Kartik Agaram -- http://akkartik.name -- ondemandhighlight@akkartik.com
" Experimenting with an idea by Evan Brooks: https://medium.com/p/3a6db2743a1e
" Discussion: http://www.reddit.com/r/programming/comments/1w76um/coding_in_color
let highlight_file = &viewdir."/highlights"
if !filereadable(highlight_file)
call system("mkdir -p ".&viewdir)
call system("echo 'call clearmatches()' > ".highlight_file)
endif
autocmd BufReadPost * silent! exec "source ".highlight_file
function! s:highlight(x)
exec ":new ".g:highlight_file
silent exec "%!grep -v '\\<".s:group(a:x)."\\>'"
normal G
exec "normal ohighlight ".s:group(a:x)." ctermfg=".s:randomColor()
exec "normal ocall matchadd('".s:group(a:x)."', '\\<".a:x."\\>')"
write
bdelete
exec "source ".g:highlight_file
endfunction
function! s:unhighlight(x)
exec ":new ".g:highlight_file
silent exec "%!grep -v '\\<".s:group(a:x)."\\>'"
write
bdelete
exec "source ".g:highlight_file
endfunction
function! s:clearhighlights()
exec ":new ".g:highlight_file
silent exec "%!echo 'call clearmatches()'"
write
bdelete
exec "source ".g:highlight_file
endfunction
function! s:group(x)
return 'highlight_'.strpart(sha256(a:x), 0, 8)
endfunction
function! s:randomColor()
return system("echo $RANDOM") % &t_Co " num colors
endfunction
command! -nargs=1 Highlight call s:highlight(<q-args>)
command! -nargs=1 Unhighlight call s:unhighlight(<q-args>)
command! ClearHighlights call s:clearhighlights()
map - :Highlight <C-r><C-w><CR>
map _ :Unhighlight <C-r><C-w><CR>
map ^ :ClearHighlights <CR>
" Scenarios considered:
" should instantly update colors
" should overrule existing syntax highlighting
" quitting and restarting should preserve colors
" should work in multiple vim sessions at once
" repeatedly highlighting a single word shouldn't grow the highlights file
" repeatedly highlighting a single word should give uniformly random colors
" should start up with non-existent viewdir
" should handle words with colons
"
" Minor issues:
" Color might sometimes be hard to see. Just highlight again.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment