How do I trigger an autocommand action after the cursor has been idle for a set period?
Answer
CursorHold
Explanation
The CursorHold autocommand event fires once whenever the cursor has been motionless in normal mode for updatetime milliseconds. By default updatetime is 4000ms (4 seconds), but setting it to 300ms or less makes CursorHold fire quickly enough for interactive features. This event is the standard mechanism for idle-triggered behaviors like showing diagnostic popups, hover documentation, or automatically refreshing a preview.
How it works
CursorHold— the event that Vim emits after cursor inactivity in normal modeupdatetime— the option (:set updatetime=300) that controls the idle delay in milliseconds- The event fires once per idle period, then resets when the cursor moves or a key is pressed
CursorHoldIis the companion event for insert mode inactivity
Example
" Reduce the idle delay
set updatetime=300
" Show a floating diagnostic window after the cursor pauses
autocmd CursorHold * lua vim.diagnostic.open_float(nil, { focus = false })
" Dismiss it when the cursor moves
autocmd CursorMoved * lua vim.diagnostic.close_float()
For a Vimscript-only setup:
set updatetime=500
autocmd CursorHold * echo 'Cursor idle'
Tips
- Very short
updatetimevalues (below 100ms) also increase how frequently Vim writes swap files, which can slow down I/O on large files - Pair
CursorHoldwithCursorMovedto open a popup on idle and close it on movement - LSP plugins such as
nvim-lspconfiguseCursorHoldinternally to power hover and signature help - Use
autocmd CursorHoldIfor the same behavior while the user is typing in insert mode - Wrap your autocmd in an
augroupto prevent duplicates when re-sourcing your config