5

I am trying to highlight a word in the current buffer dynamically like so:

function! Highlight()

  let @/ = 'word'
  set hlsearch

endfunction

When I run this function, the register / contains word as desired but the word word is not highlighted.

This surprises me because if I remove the set hlsearch part and after the function runs, I call it manually, it highlight correctly the word.

What can I do to have the correct behavior?

  • 5
    :h function-search-undo – Christian Brabandt Jun 12 '16 at 19:09
  • 2
    @nobe4 you can make the function return the actual commands. That should work. – Christian Brabandt Jun 13 '16 at 12:07
  • 1
    @SibiCoder setting @/ will highlight matches. – Antony Jun 14 '16 at 10:12
  • 1
    @nobe4 Ah, I tried it with vim -u NONE. It works like that. – Antony Jun 14 '16 at 10:23
  • 1
    Yeah, works as intended if I start with vim -u NONE. Doesn't if I start with vim -Nu NONE, even if I then :set compatible. Bug? Vim 7.4.778 btw. – Antony Jun 14 '16 at 10:30
3

A workaround:

function! Highlight()

  call matchadd('error', 'word')

endfunction

The matchadd function takes an highlight group (here 'error') and a regex to match (here 'word'), it will create a new highlight a return it's ID.


Bonus:

If you want to change the highlight over time, you can store this ID, call matchdelete(ID) to clear the current highlight and call matchadd again to add a new highlight.

e.g. pressing <C-H> will highlight the word under the cursor:

let s:current_matching = -1

function! Highlight()

  if s:current_matching != -1
    call matchdelete(s:current_matching)
  endif
  let s:current_matching = matchadd('error', expand('<cword>'))

endfunction

nnoremap <C-H> :call Highlight()<CR>
0

For reference, and maybe further research:

After a long discussion with antony we found out that this behavior is enable in compatible mode but not in nocompatible mode.

i.e. the code will highlight when called from

vim -u NONE

but not from

vim -Nu NONE

Moreover, we found that setting hls and nohls one after the other will make the highlight work for both compatible and nocompatible.

e.g. this code correctly highlight for both compatible and nocompatible:

function! Highlight()
  let @/ = 'word'
  set hlsearch
endfunction

let @/=''
set hls
set nohls

" source %
" call Highlight()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.