vimtricks.wiki Concise Vim tricks, one at a time.

How do I briefly highlight text after yanking it to get visual confirmation of what was copied?

Answer

autocmd TextYankPost

Explanation

The TextYankPost event fires immediately after any yank operation completes — including y, Y, dd, dw, and any other command that writes to a register. In Neovim, this event can be paired with vim.highlight.on_yank() to briefly flash the yanked region, making it immediately obvious what text was captured. Without this, a yank gives no visual feedback at all, which leads to uncertainty about what was actually copied.

How it works

  • TextYankPost — the event that fires after text is placed into a register by any yank or delete command
  • vim.highlight.on_yank() — (Neovim) temporarily applies a highlight group over the yanked region, then removes it after a timeout
  • v:event — a dictionary available during the event that contains details: .operator (y, d, c), .regname, .visual
  • The highlight is purely visual and does not affect the buffer or register

Example

In init.vim or init.lua:

" Vimscript — add to init.vim
augroup YankHighlight
  autocmd!
  autocmd TextYankPost * silent! lua vim.highlight.on_yank({ higroup='IncSearch', timeout=200 })
augroup END

Or in pure Lua (init.lua):

vim.api.nvim_create_autocmd('TextYankPost', {
  callback = function()
    vim.highlight.on_yank({ higroup = 'Visual', timeout = 300 })
  end,
})

Tips

  • vim.hl.on_yank() is an alias available in newer Neovim versions (0.10+)
  • Change higroup to any highlight group: 'Visual', 'Search', 'IncSearch' are popular choices
  • Set timeout in milliseconds; 150–300ms is a comfortable duration
  • TextYankPost is also available in Vim 8.0.1206+, but the vim.highlight utility is Neovim-only — in Vim you can use matchaddpos() manually
  • Wrap in an augroup with autocmd! to prevent duplicate registrations when re-sourcing your config

Next

How do I autocomplete macro-defined identifiers from header files while in insert mode?