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

How do I run commands automatically when certain events occur?

Answer

:autocmd Event pattern command

Explanation

Autocommands let you execute commands automatically in response to events like opening a file, saving, or changing buffers.

How it works

  • :autocmd BufWritePre * :%s/\s\+$//e removes trailing whitespace before saving
  • :autocmd FileType python setlocal tabstop=4
  • The event triggers the command on matching files

Example

autocmd BufWritePre *.go :silent !gofmt -w %
autocmd FileType javascript setlocal shiftwidth=2
autocmd BufNewFile *.py :r ~/templates/python.py

Tips

  • Use augroup to organize and prevent duplicate autocommands
  • :autocmd! inside a group clears previous commands
  • Common events: BufRead, BufWrite, FileType, InsertLeave
  • :autocmd with no arguments lists all autocommands
  • :help autocmd-events lists all available events

Next

How do you yank a single word into a named register?