Vim Templates

I feature of Vim I recently came across was the use of templates. Templates can be used when creating new documents to automatically insert information that will be always included. Examples would be headers for blog posts, copyright notices, zettelkasten ids. Templates are based on file extenstions. So if the new document name ends in .html it uses the html template, if it ends in .md it uses the md template.

Templates are named skeleton.yourextension. So the html template is named skeleton.html. The md template is named skeleton.md. If I need multiple templates for particular file type, a work around I use is using different valid extensions for a that file type. I use markdown for three types of documents; dairy entries, zettelkasten notes, and blog posts. So in order to have three different templates, I use three different markdown extensions; for diary entries I use .mkd, for zettelkasten notes I use .markdown, and for blog posts I use .md. What if you want multiple templates for a given extension. The answer is I don't know. I would suggest looking for a Vim plugin.

Templates can be used for static or dynamic information. A good article to read about Vim templates is Use eval to create dynamic templates The article contains some great drop in place code to use dynamic & static templates. The addition of the code below to your .vimrc will allow you to use static or dynamic templates. The only bit that needs to be changed is the path to your templates.

augroup templates
  au!
  " read in template files
  autocmd BufNewFile *.* silent! execute '0r $HOME/vimfiles/templates/skeleton.'.expand("<afile>:e")

  " parse special text in the templates after the read
  autocmd BufNewFile * %substitute#\[:VIM_EVAL:\]\(.\{-\}\)\[:END_EVAL:\]#\=eval(submatch(1))#ge
augroup END

Here is an example template I use:

 ---
 Title: 
 Published: [:VIM_EVAL:]strftime('%Y-%m-%d %H:%M')[:END_EVAL:]
 Author: Rev. Fr. Robert Bower
 Tag: 
 layout: blog
 ---

 Zettelkasten ID  **[:VIM_EVAL:]expand("%:t:r")[:END_EVAL:]**

Any static text can be typed as you would like it to appear. There are two tags [:VIM_EVAL:] and [:END_EVAL:]. Any vim script function that is between the tags will be run. So in my blog template my first set of tags calculates today's date and time. The second set uses expand to insert the file name which I use for the zettelkasten ID.

Using templates can speed up your workflow and ensure consistency in document structure.


Zettelkasten ID vimtemplates-2020-05-12-0933