How do I access event-specific data like yank contents or inserted characters inside a Vim autocommand?
Answer
v:event
Explanation
The v:event dictionary is populated inside certain autocommand callbacks with data specific to that event. It lets you inspect or modify what just happened — for example, reading what text was yanked, intercepting a character before it is inserted, or checking which operator triggered a yank.
How it works
When Vim fires a specific autocommand, it sets v:event to a dictionary whose keys depend on the event type. The dictionary is read-only for most events, but for InsertCharPre the char key can be reassigned to change the character that gets inserted.
Common v:event keys by event:
| Event | Useful keys |
|---|---|
TextYankPost |
operator, regname, regtype, regcontents |
InsertCharPre |
char (writable — change to alter the inserted character) |
BufReadCmd |
autoread |
OptionSet |
option, oldval, newval, oldlocal, oldglobal |
Example
Log the contents and type of every yank:
autocmd TextYankPost * echom 'yanked ' . v:event.regtype . ': ' . join(v:event.regcontents, ' ')
Reject specific characters in insert mode:
autocmd InsertCharPre * if v:event.char ==# '\t' | let v:event.char = ' ' | endif
Tips
v:eventis only valid inside the autocommand body — it is cleared immediately after the autocmd runs.regtypevalues:v(characterwise),V(linewise),<C-v>(blockwise).TextYankPostis available since Vim 8.0 and Neovim. Use it for features like highlight-on-yank without plugins.