template.vim 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. let s:current_file = expand("<sfile>")
  2. function! go#template#create() abort
  3. let l:go_template_use_pkg = get(g:, 'go_template_use_pkg', 0)
  4. let l:root_dir = fnamemodify(s:current_file, ':h:h:h')
  5. let cd = exists('*haslocaldir') && haslocaldir() ? 'lcd ' : 'cd '
  6. let dir = getcwd()
  7. let l:package_name = -1
  8. if isdirectory(expand('%:p:h'))
  9. execute cd . fnameescape(expand('%:p:h'))
  10. let l:package_name = go#tool#PackageName()
  11. endif
  12. " if we can't figure out any package name(no Go files or non Go package
  13. " files) from the directory create the template or use the cwd
  14. " as the name
  15. if l:package_name == -1 && l:go_template_use_pkg != 1
  16. let l:filename = fnamemodify(expand("%"), ':t')
  17. if l:filename =~ "_test.go$"
  18. let l:template_file = get(g:, 'go_template_test_file', "hello_world_test.go")
  19. else
  20. let l:template_file = get(g:, 'go_template_file', "hello_world.go")
  21. endif
  22. let l:template_path = go#util#Join(l:root_dir, "templates", l:template_file)
  23. silent exe 'keepalt 0r ' . fnameescape(l:template_path)
  24. elseif l:package_name == -1 && l:go_template_use_pkg == 1
  25. " cwd is now the dir of the package
  26. let l:path = fnamemodify(getcwd(), ':t')
  27. let l:content = printf("package %s", l:path)
  28. call append(0, l:content)
  29. else
  30. let l:content = printf("package %s", l:package_name)
  31. call append(0, l:content)
  32. endif
  33. $delete _
  34. execute cd . fnameescape(dir)
  35. endfunction
  36. function! go#template#ToggleAutoCreate() abort
  37. if get(g:, "go_template_autocreate", 1)
  38. let g:go_template_autocreate = 0
  39. call go#util#EchoProgress("auto template create disabled")
  40. return
  41. end
  42. let g:go_template_autocreate = 1
  43. call go#util#EchoProgress("auto template create enabled")
  44. endfunction
  45. " vim: sw=2 ts=2 et