Unleash your inner root

Vim Templates

There are often cases as an admin where you find yourself creating new files that all have the same type of basic formation. bash/python scripts come to mind. If you are a vim user, good news, there is a way to make your life easier when creating files of the same type! enter Vim Templates!

Basically you can create a template file that vim will read when you create a file of a certain extension, it will load the template for you instead of just creating an empty file. So how do you do it? Well, it comes down two simple things. Creating the template, and a quick edit to your .vimrc file.

The template File

Let’s start with the template file, first ensure a .vim/templates directory exists.

mkdir -p ~/.vim/templates

next simply create a file with a naming convention that makes sense to you, for example:

vim ~/.vim/templates/skeleton.py

Add your template information to the file:

#!/usr/local/bin/python3

#########
# Created By. Brandon Graves
# Function:
# Last Edited:
#########

.vimrc modifications

Next we just have to setup our vimrc to parse the directory for skeleton files:

augroup templates
  au!
  " Check Directory for template files
  autocmd BufNewFile *.* silent! execute '0r ~/.vim/templates/skeleton.'.expand("<afile>:e")
augroup END

The above will check the directory for any files named “skeleton.*”, and use them to apply to whatever the file extension is IE: skeleton.py applies to “.py”

skeletontemplatesvimvimrc

Brandon.Graves • February 20, 2018


Previous Post

Next Post

Leave a Reply

Your email address will not be published / Required fields are marked *

%d bloggers like this: