Autocommands

Autocommands are a way to tell Vim to run certain commands whenever certain events happen.

examples

Let's change it so that Vim creates files as soon as you edit them. Run the following command:

:autocmd BufNewFile * :write

Take a look piece by piece

: : :autocmd BufNewFile * :write ^ ^ ^ | | | | | The command to run. | | | A "pattern" to filter the event. (regular expression) | The "event" to watch for.

The event type of vim

Starting to edit a file that doesn't already exist.
Reading a file, whether it exists or not.
Switching a buffer's filetype setting.
Not pressing a key on your keyboard for a certain amount of time.
Entering insert mode.
Exiting insert mode.
BufWritePre: the event will be checked just before you write any file.
FileType: the event will check file type (like javascipt, python)

So try more specific

:autocmd BufNewFile *.txt :write

:autocmd BufWritePre *.html :normal gg=G #reindent html file before save

Multiple Events

:autocmd BufWritePre,BufRead *.html :normal gg=G #reindent html file before write and after read

FileType Events

:autocmd FileType javascript nnoremap <buffer> <localleader>c I//<esc>

:autocmd FileType python nnoremap <buffer> <localleader>c I#<esc>

Open a Javascript file (a file that ends in .js), pick a line and type c. This will comment out the line.

Now open a Python file (a file that ends in .py), pick a line and type c. This will comment out the line, but it will use Python's comment character!

Exercises

Skim :help autocmd-events to see a list of all the events you can bind autocommands to. You don't need to memorize each one right now. Just try to get a feel for the kinds of things you can do.

Create a few FileType autocommands that use setlocal to set options for your favorite filetypes just the way you like them. Some options you might like to change on a per-filetype basis are wrap, list, spell, and number.

Create a few more "comment this line" autocommands for filetypes you work with often.

Add all of these autocommands to your ~/.vimrc file. Use your shortcut mappings for editing and sourcing it quickly, of course!

Last updated

Was this helpful?