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

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 mode
  • updatetime — 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
  • CursorHoldI is 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 updatetime values (below 100ms) also increase how frequently Vim writes swap files, which can slow down I/O on large files
  • Pair CursorHold with CursorMoved to open a popup on idle and close it on movement
  • LSP plugins such as nvim-lspconfig use CursorHold internally to power hover and signature help
  • Use autocmd CursorHoldI for the same behavior while the user is typing in insert mode
  • Wrap your autocmd in an augroup to prevent duplicates when re-sourcing your config

Next

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