Tip 26 | Using Autocommands to Respond to Events |
This tip comes in two parts. In the first part, you’ll try out some examples of autocommands to understand how they work. In the second part, you’ll look at some real examples of how autocommands can be useful, collected from other tips in this book.
Understanding Autocommands
Here’s a short sample Vim script that defines two autocommands:
| augroup demo |
| autocmd! |
| autocmd BufReadPost * echo 'Reading: ' . expand('<afile>') |
| autocmd BufWritePost * echo 'Writing: ' . expand('<afile>') |
| augroup END |
Before we look at the syntax of these autocommands, let’s see how they behave. Open that script in a fresh instance of Vim:
=> | $ cd code/autocmd-demo/ |
=> | $ vim ... |
Get Modern Vim now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.