[Howto] Code templates in vim

| 1 Comment | No TrackBacks

bash.pngThe text editor vim offers several tools for automation. This howto describes a way to auto-include text modules when creating new files.

Often during programming or administration you need the same text modules again and again. The editor vim is very helpful here, as it can detect a file type while it is being created and insert pre-defined text modules accordingly. This behaviour can be configured in the file .vim/plugin/autoinsert.vim, for example with:

if has("autocmd")
augroup autoinsert
  au!
  autocmd BufNewFile *.c call s:Template("c")
  autocmd BufNewFile Makefile call s:Template("make")
  autocmd BufNewFile makefile call s:Template("make-simple")
augroup END
endif

function s:Template(argument)
        if (a:argument == "help")
                echo "Currently available templates:"
                echo " c                - Plain C Template"
                echo " make             - Makefile Template"
                echo " make-simple      - Simple Variant of the Makefile Template"
        else
                " First delete all in the current buffer
                %d

                " The Makefile variants
                if (a:argument == "make")
                        0r ~/.vim/skeletons/template.make
                        set ft=make
                elseif (a:argument == "make-simple")
                        0r ~/.vim/skeletons/template.make_simple
                        set ft=make
                elseif (a:argument == "make-simple-cpp")
                        0r ~/.vim/skeletons/template.make_simple_cpp
                        set ft=make

                " Stuff for plain C
                elseif (a:argument == "c")
                        0r ~/.vim/skeletons/template.c
                        set ft=c
                endif

                silent %!~/.vim/do_header %
        endif
endfunction

command! -nargs=1 Template call s:Template(<f-args>)

The lines 21-35 clearly show the template names and include the text modules. The template for make_simple, ~/.vim/skeletons/template.make_simple, for example includes the compiler flags for building C/C++ programs with gcc:

CC := gcc
CFLAGS := -Wall -pedantic -O3
LDFLAGS :=

PROG := main
OBJS := main.o

all: $(PROG)

$(PROG): $(OBJS)
        $(CC) $(LDFLAGS) -o $@ $^

clean:
        rm -rf $(PROG) $(OBJS)

.PHONY: all clean

Another template is shown below: ~/.vim/skeletons/template.c includes text modules for not only the obligatory GPL header but also includes a basic code structure:

/*
 * %%FILENAME%% - description
 *
 * Copyright (C) %%YEAR%% %%AUTHOR%%
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA.
 */

#include <stdio.h>

int
main (int argc, char **argv)
{
  return 0;
}

/**This must remain at the end of the file.**********
 * vim600:set sw=2 ts=8 fdm=marker fmr=«««,»»»:     *
 * vim600:set cindent cinoptions={1s,>2s,^-1s,n-1s: *
 ****************************************************/


Variables like %%FILENAME%% or %%AUTHOR%% can also automatically be replaced by a small shell script running during file creation: the script ~/.vim/do_header labelled with the file name as argument detects the full name with getent or /etc/passwd, respectively. Other variables are gathered using the default GNU tools as the listing shows:

#!/usr/bin/env zsh

if which getent > /dev/null; then
        REALNAME=$(getent passwd $USER|awk -F : '{print $5}' | awk -F , '{print $1}')
else
        REALNAME=$(grep $USER /etc/passwd|awk -F : '{print $5}' | awk -F , '{print $1}')
        if which nidump > /dev/null && [ -z "$REALNAME" ]; then
                REALNAME=$(nidump passwd / | grep $USER|awk -F : '{print $8}')
        fi
fi
DATE=$(date)
YEAR=$(date +%Y)
FILENAME=$(echo $1 | sed 's/[^/]*\///')
FILE=$(echo $FILENAME | sed 's/\..*//')
FILEBIG=$(echo $FILE | tr '[:lower:]' '[:upper:]')
sed     "s/%%AUTHOR%%/$REALNAME/g;
        s/%%DATE%%/$DATE/g;
        s/%%YEAR%%/$YEAR/g;
        s/%%FILENAME%%/$FILENAME/g;
        s/%%FILE%%/$FILE/g;
        s/%%FILEBIG%%/$FILEBIG/g;"


Besides the examples shown here other templates can be generated to deal with HTML files, python or whatnot, among others - the possibilities are endless.

This howto has just touched on one small aspect of the many automations possible with vim. You can find other howtos in this blog in the howtos category, which has its own feed - if you need more in-depth support or services for GNU tools or Linux, you've come to the right place at credativ.

No TrackBacks

TrackBack URL: http://blog.credativ.com/mt-tb.cgi/143

1 Comment

nice :) Thank you!

I removed the auto commands (for c) as 35% of the files is testing and hacking.
Therefor I'd rather insert template on command. Found autocompletion to be a nice feature in that case; and added this:

function! ListKnownSkeletonTemplates(A, L, P)
	let g:l = ['c', 'c-simple', 'make', 'make-simple', 'java', 'php', 'bash', 'xhtml', 'html4', 'html5']
	return filter(copy(g:l), 'v:val =~ a:A')
endfunction

command! -complete=customlist,ListKnownSkeletonTemplates
\ -nargs=1 Template call s:Template("")

Guess there are a way to stroll trough the folder and make the names from the files - but I'm not to familiar with vim yet.

--

Nick

Leave a comment