Skip to content

Turn off highlight on CursorMoved and InsertEnter without remapping (doesn't break search operator pending mode) #9

Closed
@purpleP

Description

@purpleP

Thanks to guys from neovim I've found a way to automatically turn off search highlight when it's no longer needed (for me).

Notice how I check if the cursor is on something that have been searched previously. In your plugin you're using if expand("<cword>") =~ @/ which wouldn't work if someone searched for more than one word.

So in case someone is wondering this would turn off highlight if you've moved cursor with anything except next/previous match motion or if you've entered insert mode (in operator pending mode also, yey!)

noremap <expr> <Plug>(StopHL) execute('nohlsearch')[-1]
noremap! <expr> <Plug>(StopHL) execute('nohlsearch')[-1]

fu! HlSearch()
    let s:pos = match(getline('.'), @/, col('.') - 1) + 1
    if s:pos != col('.')
        call StopHL()
    endif
endfu

fu! StopHL()
    if !v:hlsearch || mode() isnot 'n'
        return
    else
        sil call feedkeys("\<Plug>(StopHL)", 'm')
    endif
endfu

augroup SearchHighlight
au!
    au CursorMoved * call HlSearch()
    au InsertEnter * call StopHL()
augroup end

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions