Skip to content

HighlightedYank feature #14848

Description

@girishji

Now that getregionpos() has been merged, it is quite straightforward to have this feature, which temporarily highlights the yanked region to make it apparent. I use this feature, and it may be of value to others. It is also natively included in Neovim.

If enough people think this is worthwhile, I can submit a PR. Maybe this can be a plugin, or an example added to the help file.

def HighlightedYank(hlgroup = 'IncSearch', duration = 300)
    if v:event.operator ==? 'y'
        var [beg, end] = [getpos("'["), getpos("']")]
        var type = v:event.regtype ?? 'v'
        var pos = getregionpos(beg, end, {type: type})
        var end_offset = (type == 'V' || v:event.inclusive) ? 1 : 0
        var m = matchaddpos(hlgroup, pos->mapnew((_, v) => {
            var col_beg = v[0][2] + v[0][3]
            var col_end = v[1][2] + v[1][3] + end_offset
            return [v[0][1], col_beg, col_end - col_beg]
        }))
        var winid = win_getid()
        timer_start(duration, (_) => m->matchdelete(winid))
    endif
enddef
autocmd TextYankPost * HighlightedYank()

Edit: Include window ID in matchdelete(), thanks to @bfrg !

Edit: Removed [0] from regtype, thanks to @zeertzjq

Edit: The highlightedyank plugin has an option to skip highlighting while yanking from visual mode. I've added the parameter in_visual to incorporate this:

def HighlightedYank(hlgroup = 'IncSearch', duration = 300, in_visual = true)
    if v:event.operator ==? 'y'
        if !in_visual && visualmode() != null_string
            visualmode(1)
            return
        endif
        var [beg, end] = [getpos("'["), getpos("']")]
        var type = v:event.regtype ?? 'v'
        var pos = getregionpos(beg, end, {type: type})
        var end_offset = (type == 'V' || v:event.inclusive) ? 1 : 0
        var m = matchaddpos(hlgroup, pos->mapnew((_, v) => {
            var col_beg = v[0][2] + v[0][3]
            var col_end = v[1][2] + v[1][3] + end_offset
            return [v[0][1], col_beg, col_end - col_beg]
        }))
        var winid = win_getid()
        timer_start(duration, (_) => m->matchdelete(winid))
    endif
enddef
autocmd TextYankPost * HighlightedYank()

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions