Vim has multiple events where we can discover if a new file is created or a file is opened:
if has("autocmd")
au BufNewFile,BufRead *.cpp "Do something
endif
We want to check whether the file we opened is empty checks if a file has a file system location, let's put this in a function so it's easier to read:
function! EmptyFile()
if (line('$') == 1 && getline(1) == '')
"Do something
endif
endfunction
The last thing we want to do is insert some template based on a existing file:
function! LoadTemplate(template)
let fl = readfile(template)
call append('', fl)
endfunction
Now everything together (you should add it to your .vimrc
):
function! AddEmptyTemplate(template)
if (line('$') == 1 && getline(1) == '')
let fl = readfile(a:template)
call append('', fl)
endif
endfunction
if has("autocmd")
au BufNewFile,BufRead *.cpp call AddEmptyTemplate("cpp-template.cpp")
au BufNewFile,BufRead *.c call AddEmptyTemplate("c-template.c")
endif
This assumes you have the files in folders Vim can find.