How do I automatically run a command when a specific event happens in Vim?
Answer
:autocmd {event} {pattern} {command}
Explanation
:autocmd registers a command to run automatically whenever a specified event fires for files matching a pattern. This is how Vim's built-in filetype detection, syntax highlighting triggers, and most plugin behaviors work under the hood — and it is the primary way to customize Vim's automatic behavior in your vimrc.
Syntax
autocmd {event} {file-pattern} {command}
{event}— what triggers the command (see below){file-pattern}— glob pattern for filenames (*.py,*.md,*, etc.); use<buffer>for current buffer only{command}— any Ex command or sequence
Common events
| Event | When it fires |
|---|---|
BufWritePre |
Before a buffer is written to disk |
BufWritePost |
After a buffer is written |
BufEnter |
When entering a buffer |
FileType |
When filetype is detected |
InsertLeave |
When leaving Insert mode |
VimEnter |
After Vim starts up |
WinResized |
When a window is resized |
Examples
Strip trailing whitespace before saving any file:
autocmd BufWritePre * :%s/\s\+$//e
Set shiftwidth to 2 for JavaScript files:
autocmd FileType javascript setlocal shiftwidth=2 tabstop=2
Run a linter after saving Python files:
autocmd BufWritePost *.py silent !flake8 %
Tips
- Wrap autocmds in
augroupto prevent duplicates whenvimrcis re-sourced:augroup mygroup | autocmd! | autocmd ... | augroup END :autocmd(no args) lists all currently registered autocommands:autocmd!inside an augroup clears that group's commands before re-registering them{command}can call afunction()for complex logic — keep the autocmd line itself short