Thumbnail: jekyll

Vim filetype templates

on under vim
1 minute read

HEAD

This one is just a short article to demonstrate one of the powers of autocmd, with which we can set a default template for a particular file type which will open up whenever we open a file of that type.

With the number of C++ codes I write using vim, I got tired of writing the same default headers every time I open up a new cpp file. Vim has a great solution to this problem, it allows us to save templates for a specific file type, and when we open a new file of that type, the default template will show up.

Creating a default template for cpp file

Open up the terminal, and go to .vim folder in the home directory. Create a folder named “templates” and create the cpp file which will hold the template for cpp file type. Let’s call that template.cpp

scr

Open the template.cpp file using your text editting software (vim in this case), and insert the default template you want to keep for the cpp file types.

Close it up and open your ~/.vimrc file and paste the following code in it –

augroup templates
	autocmd!
	autocmd BufNewFile *.cpp 0r ~/.vim/templates/template.cpp
aurogroup END

hue

And that’s it! The next time you open a new cpp file, the default template will load up as shown below.

final

This is how my template for cpp files looks like :-

vim, templates
comments powered by Disqus