3

Is there a way to auto insert text in vim when a new file is created? Maybe there is a plugin for it? Here is what I'm talking about:

I work a lot with C/C++ and Python. Very often I need to create .h and .py files. We have some coding standards ( duh ). For example every .h file needs to have a following code:

#ifndef _filename
#define _filename

#endif // _filename

and every python file needs to have the following:

if '__main__' == __name__:
    main()

Is there a plugin that will auto insert this type of code automatically when the file is created? I know there are snippets out there, but I would prefer for it to be done automatically without engaging them?

Any help is appreciated.

3

As multiple people have said in various comments, check out :h skeleton. This sounds like just what your looking for. However if you want a little more customizability you can try the following...

Detecting when a file is "created" might be hard, since vim creates files by writing buffers to files. But you can detect when you write to a file with the BufWritePre autocmd.

Edit

Another possible solution would be to use the BufNewfile autocmd. You can substitute either in the code below to find out what works best for you.

/Edit

You could call a function to insert the text. Something like:

autocmd BufNewFile *.h  :call CheckHFile()
autocmd BufNewFile *.py :call CheckPyFile()

function! CheckHFile()
   let filename = expand("%:t")
   if (getline("1") !~ '#ifndef _'.filename)
      exe "normal!ggO#ifndef _".filename
      exe "normal!o#define _".filename
      exe "normal!o^M#endif // _".filename
   endif
endfunction

function! CheckPyFile()
   if (getline("1") !~ "if '__main__' == __name__:")
      normal!ggOif '__main__' == __name__:
      normal!o    main()
   endif
endfunction

This will make sure that these lines exist in the file before writing.

  • expand("%:t") retrieves the file name to be used in the template.
  • Note that ^M will need to be re-typed with Ctrl+V, Enter

See

:h autocmd
:h expand

for more info.

  • 1
    BufNewFile might be one way :) – VanLaser Jun 24 '16 at 20:12
  • 1
    Oh, I didn't know that one existed. Good find. I'll update. – Tumbler41 Jun 24 '16 at 20:15
  • To be fair most python coders add the if __main__ ... at the end of the file not the beginning. Adding one or two empty lines above that would be useful. – grochmal Jun 24 '16 at 20:16
  • 2
    Also :h skeleton or :h template – VanLaser Jun 24 '16 at 20:17
  • @grochmal getline('$') would work for that. But I'm going to wait to see if OP says anything before updating that. – Tumbler41 Jun 24 '16 at 20:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.