Skip to main content

Importing your templates in Vim


How does it feels making copy of your coding templates before any coding competition ? Isn't there any method such that if you are making a new c++ file or c file and your template is automatically loaded. It is not a very tough task to just copy your code from github or just make copies of a template file but still here i am going to discuss a one time method so that you don't need to prepare anything before writing your code . An auto command such that your template is automatically imported whenever you make a new file is just awsome.

Before we proceed i would like to say that every software or program you use certain events are associated with it. For Vim or any editor opening a file when it does not exist , opening a pre existing file etc. are different events. We need an autocommand for the former one.

Vim contains a configuration file which can be edited from the home direcory as gedit .vimrc or vim .vimrc . You have to edit this file to make it perfect for coding. I recommend the following steps --

1. Go to the home directory and open your .vimrc file for editing. Actually .vimrc is its name.

2. Edit the contents of the file as follows ---

set ai
set tabstop=4
autocmd bufnewfile *.cpp so template.txt

3. Save the file and in the home folder and copy your template.txt to the home folder.

4. In the template.txt file in the first line add i and press enter. It should look like

i
#include<stdio.h>
.....

Now Enjoy writing codes with pre define templates :)

Appendix ---

1. bufnewfile tells vim about the event that a new file which does not exist is created or else you would have written the template in already written files too.
2. set ai is for autoindentation and set tabstop is for making tabspace length 4 from 8 (default)
3. i is added to the file because vim recognizes each step as a command given to it using the colon part. So i enables the editing feature. Remove i from the file and see what happens. You may understand the whole logic :)

Comments