1

I have a file template which is rendered with replacing some stubs when new file created:

augroup templates
  autocmd!
  autocmd BufNewFile *.java $r ~/.vim/templates/skeleton.java|call s:SetupJavaClass()

  fun! s:SetupJavaClass()
    exe "%s/__CLASS_NAME__/" . expand('%:t:r')
  endfun
augroup END

it's working fine, but only if I create new file with new buffer, e.g. vim Foo.java works, but when I create new file from NerdTree, new file is opening in current buffer and my templates and vim doesn't call my autocommands. How can I fix it? Is it possible to create autocommand to be executed on every new file, doesn't matter it was opened in new buffer or not, or maybe I should use ftplugin for that?

4
  • How do you create a new file from NerdTree? I don't have much experience with NerdTree, and I only saw commands to open existing files. Jun 27, 2019 at 8:53
  • @JürgenKrämer I'm opening menu with m, then a to add new file, then I type filename, it creates a file which I'm opening in current buffet with o key.
    – g4s8
    Jun 27, 2019 at 10:22
  • The (a)dd a childnode menu item will ultimately result in a call to writefile([], a:fullpath) inside nerdtree/lib/nerdtree/path.vim. I don't think there is an autocommand that is triggered by writefile(). You might want to ask the maintainer of NerdTree if he/she could provide a hook for reading a template file. Jun 27, 2019 at 11:05
  • @JürgenKrämer thanks, submitted a ticket: github.com/scrooloose/nerdtree/issues/1010
    – g4s8
    Jun 27, 2019 at 19:37

1 Answer 1

1

As suggested @PhilRunninger in Github ticket, I can use BufRead autocommand and apply templates if file size is zero:

autocmd BufRead *.java if getfsize(expand('%'))==0|$r ~/.vim/templates/skeleton.java|call s:SetupJavaClass()|endif

it's working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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