abstract
| - The first idea one might have to allow dynamic template content could be to define autocmds that would replace specific pre-defined tags like [:DATE:] or [:FILE_NAME:] with the appropriate text. But, why define a syntax of your own, when Vim has a perfectly good expression syntax that you will eventually need to translate into anyway? Using the eval() function, you can easily evaluate an expression obtained from the template file itself in order to provide dynamic content limited only by Vim's expression syntax and parsing. Here's how: In your .vimrc, define an augroup to load all your desired template files, just as discussed in [help template], but modified to do it automatically. It should look something like this: augroup templates au! " read in template files autocmd BufNewFile *.* silent! execute '0r $HOME/vimfiles/templates/skeleton.'.expand(":e") augroup END silent! is used to ignore errors for non-existent templates. This command allows you to create a template for a new file type simply by naming it appropriately and placing it in the correct directory. Next, decide on special indicators to tell Vim to use certain text as an expression. I used [:VIM_EVAL:]...[:END_EVAL:], where the '...' is replaced with whatever expression you want Vim to evaluate to replace the entire block. Now, create all your template files, defining your dynamic content just as you would have Vim create it, and placing the resulting Vim expression inside your chosen indicators. For example, a copyright notice in a C file could look like: /* * Copyright [:VIM_EVAL:]strftime('%Y')[:END_EVAL:] ABC Company, all rights reserved. */ Finally, add this autocmd to replace each special tag with the result of the contained expression, after all the template files are loaded: autocmd BufNewFile * %substitute#\[:VIM_EVAL:\]\(.\{-\}\)\[:END_EVAL:\]#\=eval(submatch(1))#ge This autocmd takes advantage of the ability to use an expression as the replacement text of an s/ command. See [help sub-replace-expression] for details. Note that this means your template expressions will be unable to use the same technique internally. The final product should look something like this: augroup templates au! " read in template files autocmd BufNewFile *.* silent! execute '0r $HOME/vimfiles/templates/skeleton.'.expand(":e") " parse special text in the templates after the read autocmd BufNewFile * %substitute#\[:VIM_EVAL:\]\(.\{-\}\)\[:END_EVAL:\]#\=eval(submatch(1))#ge augroup END
|