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\+$//eremoves 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
augroupto organize and prevent duplicate autocommands :autocmd!inside a group clears previous commands- Common events:
BufRead,BufWrite,FileType,InsertLeave :autocmdwith no arguments lists all autocommands:help autocmd-eventslists all available events