For many kinds of files, when you create a new one from scratch, it would be handy to have part of the file created from a boilerplate template every time. For example, whenever I want to create a Perl file, it should start like this:


use warnings;
use strict;
use 5.010;

# vi:et:sw=4 ts=4 ft=perl

You can do this easily by putting this command in your .vimrc file:

au BufNewFile * silent! 0r ~/.vim/templates/%:e.tpl

What that’s saying is “Whenever vim opens a new, empty file, read in the contents of the file at ~/.vim/templates/%:e.tpl“, where %:e is the extension of the file you’re asking to open. So for an HTML standard file, I have this in ~/.vim/templates/html.tpl:

<!DOCTYPE html>
        <title> </title>

vi: expandtab sw=4 ts=4 ft=html:

The filename that it reads from is based on the extension of the file, not the filetype, so I have to have the same Perl template file in pm.tpl, pl.tpl and t.tpl, since all three are Perl extensions.

To find out more about how vim handles templates, see :help template.
I don’t know where I first discovered this technique, since I’ve had it in my .vimrc forever. Here’s another helpful summary: