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

How do I programmatically simulate keypresses in Vim?

Answer

:call feedkeys("iHello\<Esc>", 'n')

Explanation

The feedkeys() function injects keystrokes into Vim's input buffer as if the user typed them. This is useful for automating complex key sequences, testing mappings, or building interactive scripts that need to simulate user input.

How it works

  • feedkeys({keys}, {mode}) — queues keys for processing
  • Mode flags: n = no remapping, t = handle as if typed, m = remap keys
  • Keys are processed after the current command completes
  • Special keys use backslash notation: \<CR>, \<Esc>, \<C-w>

Example

" Enter insert mode, type 'Hello', return to normal mode
:call feedkeys("iHello\<Esc>", 'n')

" Open a file and jump to line 50
:call feedkeys(":edit file.txt\<CR>50G", 'n')

" Simulate a complex editing sequence
:call feedkeys("ggVG:sort\<CR>", 'n')

Tips

  • Always use 'n' flag to avoid unexpected behavior from user mappings
  • Use 't' flag when you want mappings to be triggered (for testing)
  • feedkeys() is non-blocking — keys are processed asynchronously
  • For immediate execution, use :normal! instead; feedkeys is for deferred input

Next

How do I return to normal mode from absolutely any mode in Vim?