Contents‎ > ‎Vim Scripts‎ > ‎

File Templates

This script is a modified version of the template plugin documented here.

My updated version can be downloaded here: file_templates.vba.

Key features:
  • Multiple templates (optionally with a default) for any file type; for example, you can have a template for a given file type and for each project you're working on or company you're working for.
  • Support for automatic population of certain parameters, such as the file name, the year, the date or an upper case version of the basename etc etc (more can be added very easily).
  • Other parameters can be included and a dialog box will pop up to ask for the value.  The last-used value (from this Vim session) will be remembered as the default.
  • Support for fixed-width entries.
A template is just a source file stored in ~/.vim/templates or vimfiles/templates (depending on OS) with some identifiers inserted in appropriate places.  An identifier starts with "<+" and ends with "+>".  In the identifier, there can be:
  • Keywords surrounded by '$' signs: these are automatically expanded.  Supported keywords are (examples shown for file Flash.c):
    • $BASENAME$ (e.g. Flash)
    • $UBASENAME$ (e.g. FLASH)
    • $LBASENAME$ (e.g. flash)
    • $FILENAME$ (e.g. Flash.c)
    • $YEAR$ (e.g. 2008)
    • $DATE$ (e.g. 3/9/2008)
  • Keywords surrounded by '#' signs: the user will be asked what these mean (the same replacement will be used for all entries in the file).  For example, you may want to have:
  • A semicolon followed by an 'R' and then zero or more '+' signs.  This provides a fixed-width entry.  See the included examples for details.
There are example C source and header templates included in the distribution.

After creating a new file and setting the file name, the template is loaded with the command

:LoadFileTemplate <TemplateName>

Where <TemplateName> should be replaced by the name of your template (e.g. ":LoadFileTemplate Example" for the example template).  If you're editing a '.c' file, example.c will be loaded and if you're editing a '.h' file, example.h will be loaded.  If you add an entry in .vimrc to set the global variable g:file_template_default, it is then possible to simply run ":LoadFileTemplate" and the default will be used.

UPDATE: g:file_template_default is now a dictionary, so it is possible to have different defaults for different file types (based on the file extension).

let g:file_template_default = {}
let g:file_template_default["default"] = "Example"
let g:file_template_default["c"] = "Work"
let g:file_template_default["h"] = "Work"
let g:file_template_default["py"] = "Home"

UPDATE: Added AddTemplate command to allow addition of a template to an existing file (e.g. for adding a circular buffer or similar to an existing module).

If you have any comments or suggestions for improvement, please contact me on 
Alan Budden,
21 May 2009, 00:14