Skip to content

Instantly share code, notes, and snippets.

@g0xA52A2A
Created October 22, 2020 12:34
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 g0xA52A2A/ceb1e72ce31aa9889a69efb55257d466 to your computer and use it in GitHub Desktop.
Save g0xA52A2A/ceb1e72ce31aa9889a69efb55257d466 to your computer and use it in GitHub Desktop.

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment