Enable hlsearch
whenever the cursor is on any part of a match and
disable hlsearch
otherwise.
Whenever the cursor is moved the current line is checked if it contains a match for the current search. If it does a range is created that can be compared to the cursor's current column. This matching is repeated for the current line until no more matches are found.
function! AutoHL() abort
let match_count = 1
let match_positions = []
while 1
let [match_start, match_end] = matchstrpos(getline('.'), @/, 0, match_count)[1:2]
let match_range = range(match_start, match_end)
if match_range != [-1]
let match_count += 1
call extend(match_positions, match_range[1:])
else
break
endif
endwhile
if index(match_positions, col('.')) != -1
execute !v:hlsearch ? 'set hlsearch' : ''
else
execute v:hlsearch ? 'set nohlsearch' : ''
endif
endfunction
augroup HighlightSearch
autocmd!
autocmd CursorMoved * call AutoHL()
autocmd InsertEnter * set nohlsearch
augroup END