A while ago, someone asked how to write a simple template engine, i.e. something like "when I create a new java file, how can I choose a code skeleton to prefill it with". I could practically hear the starter pistol fire. I cant remember if I won or not, but I wrote some dynamite hacks and kept them in my vimrc so that the next time someone asked I could pastebin them straight away and pretend I wrote them on the spot.
Anyway, a few days ago I revisited the code and cleaned it up a bit. Here it is:
1 "define the Template command
2 command! -complete=customlist,AvailableTemplates -n=1
3 \ Template :call InsertTemplate('<args>')
5 function! InsertTemplate(name)
7 "read in the template
8 execute 'read ~/.vim/templates/' . &filetype . '/' . a:name
10 "if the cursor was previously on a blank line, delete it
11 if getline(line(".")-1) =~ '^\s*$'
12 exec line(".")-1 . 'd'
16 function! AvailableTemplates(lead, cmdline, cursorpos)
17 let templateDir = expand('~/.vim/templates/' . &filetype . '/')
18 let files = split(globpath(templateDir, a:lead . '*'), '\n')
20 "chop off the templateDir from each file
21 return map(files, 'strpart(v:val,strlen(templateDir))')
The idea is that you store all your template files in:
So, for example, you might have three html templates and a java template:
Then you edit an html file and apply a template with:
You can also tab complete template names.
Limitations: No error handling. No clever variable expansion etc. Assumes you are working in *nix style os, but could easily be hacked for MF Windows.