1

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 Visual Studio but not for Vim or Atom.

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112

2 Answers2

1

That's what snippets are for. Use a snippet plugin, such as UltiSnips. You'll also need a set of snippets to start with, such as vim-snippets.

Sato Katsura
  • 3,066
  • 15
  • 21
0

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.

tversteeg
  • 4,717
  • 10
  • 42
  • 77
  • Thanks , that helped a lot. – Swapnill Daga Sep 14 '16 at 16:37
  • There is one problem though i am encountering....if I put cpp-template in some folder (say home) then I am not able to access that template on opening a .cpp file in other folder unless i copy paste the same template in that folder – Swapnill Daga Sep 14 '16 at 16:45
  • 2
    Try it with `BufRead,BufNewFile`. `BufEnter` is called whenever you switch buffers, and that's definitely not what you want. – Sato Katsura Sep 14 '16 at 17:25
  • Edit : The problem was fixed by using glob command in readfile and keeping no parameter in AddEmptyTemplate() function . Although this removes versatility of function , it fixed the problem of not opening template in different folders – Swapnill Daga Sep 14 '16 at 17:34