Vim File Templates
All python modules I use have the same header. Usually I copy other modules but why not load a default template into a python file in vim?
Here a small snippet that does exactly that:
function! LoadFileTemplate()
silent! 0r ~/.vim/templates/%:e.tmpl
syn match vimTemplateMarker "<+.++>" containedin=ALL
hi vimTemplateMarker guifg=#67a42c guibg=#112300 gui=bold
endfunction
function! JumpToNextPlaceholder()
let old_query = getreg('/')
echo search("<+.++>")
exec "norm! c/+>/e<CR>"
call setreg('/', old_query)
endfunction
autocmd BufNewFile * :call LoadFileTemplate()
nnoremap <C-J> :call JumpToNextPlaceholder()<CR>a
inoremap <C-J> <ESC>:call JumpToNextPlaceholder()<CR>a
What it does is looking for a template called “extension.tmpl” in ~/.vim/templates. If it finds one it loads it and highlights everything between “<+" and "+>” as placeholder. Hitting Ctrl+J jumps to the next placeholder.
An example template could look like this:
# -*- coding: utf-8 -*-
"""
<+ MODULE_NAME +>
<+ DESCRIPTION +>
Licensed under the <+ LICENSE +> license, see X for more details etc.
Copyright by …
"""
If you want to load a file without a template, just hit “u” right at the beginning and the inserted template will disappear.
Hey, you’re a Vim user, I definitely love you ;)
Thanks for this code, although I won’t use it at present since I don’t grok vim scripting. I currently rely on two Nautilus templates to create a new module or script. I used Geany for a while and then Gedit, both of which support some kind of templates or code snippets, but Geany crashes and Gedit is stupid, so I use Gvim: it integrates well with my desktop environnement and lets me learn the commands step by step. I use the python.vim script from the Python 3.0a1 source and I understand the basic stuff it does yet I can’t even change the way tabs are displayed (^I being ugly and hindering reading), I forgot where I read about that in the doc. The big problem is domesticating windows, tabs and buffers. Well, looking forward to read more entries about Vim :)
Comment by Wok — Monday, December 10th, 2007 @ 6:21 am