Sunday, August 21, 2011

Detect whether search highlighting is active

I just reworked an interesting idea added to this tip:
http://vim.wikia.com/wiki/Highlight_all_search_pattern_matches

The following script means you can press Enter to toggle search
highlighting for the current word on and off (without moving the
cursor). I did not think I would want this, but it's strangely
attractive.

let g:highlighting = 0
function! Highlighting()
if g:highlighting == 1 && @/ =~ '^\\<'.expand('<cword>').'\\>$'
let g:highlighting = 0
return ":silent nohlsearch\<CR>"
endif
let @/ = '\<'.expand('<cword>').'\>'
let g:highlighting = 1
return ":silent set hlsearch\<CR>"
endfunction
nnoremap <silent> <expr> <CR> Highlighting()

Question: Can a script detect whether search highlighting is
currently active? The above uses a global variable as a
workaround, but it fails for common scenarios like this:

- Move to a word.
- Press Enter to highlight that word.
- Press Enter to remove highlighting.
- Press n to search for next occurrence of word.
- Press Enter (bug).

The bug is that the script thinks highlighting is off, when in
fact it is on due to the 'n' search.

John

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: