VIM has a bunch of built-in event handlers which can be used to automate
certain tasks. These are known as autocommands. You can define actions
that get executed whenever one of these autocommands is fired to do
things like read in a template file or write a note to a log file. In
today’s tip, I’m going to show you how to use template files for certain
file types.
Let’s say you write a lot of HTML code, and you always find yourself
creating the following structure:
<HTML>
<HEAD><TITLE></TITLE></HEAD>
<BODY>
</BODY>
</HTML>
Instead of having to type that every single time you create a new .html
file, you can write that structure into a template file. In your home
directory, there should be a .vim directory. If there isn’t go ahead
and create one, then create a directory called templates and write your
template file under the name html.tpl.
Now, add the following line to your .vimrc:
:autocmd BufNewFile *.html 0r ~/.vim/templates/html.tpl
That line tells VIM that you’re defining a new autocommand that is to be
executed when the BufNewFile action is triggered. BufNewFile gets
triggered every time a new file is created in vim. In this case, if the
new file’s name matches the pattern “*.html”, it’s going to read in the
contents of ~/.vim/templates.html.tpl. So now, if you type:
vim brandnewfile.html
VIM is going to create the new file and read in the contents of your
HTML template.
One note about this tip – I have no idea what the 0 in “0r” is for. If
anyone knows why the zero is needed, please let me know.
Happy VIMming!
- David Roth
