Swapnill Daga Swapnill Daga - 2 months ago 9
C++ Question

Default text on opening a new file of a certain extension(ex: .cpp)

I want some default text like:

#include <iostream>
using namespace std;
int main()
{
// code
return 0;
}


to come whenever I open a .cpp file in vim or atom . I searched a lot in various forums but could not find answers except for the same in visual studio but not for vim or atom.

Answer

Vim has multiple events where we can discover if a new file is created or a file is opened:

if has("autocmd")   
    au BufEnter,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 BufEnter,BufRead *.cpp call AddEmptyTemplate("cpp-template.cpp")
    au BufEnter,BufRead *.c call AddEmptyTemplate("c-template.c")
endif

This assumes you have the files in folders Vim can find.