1

I have different templates in this directory ~/Documents/Library/
like: Template.cpp, normal.cpp, advanced.cpp

normally i use this

autocmd BufNewFile *.cpp 0r ~/Documents/Library/Template.cpp

I want to add an option "choose template" for new files
that i create via vim file.cpp or vim -p file1.cpp file2.cpp

  1. After triggering vim file.cpp, vim will show me multiple options. After choosing one, vim will use that template.

  2. In case of vim -p file1.cpp file2.cpp, i want to choose only one for all tabs. vim will use that template on all tabs.

Is it possible?
if yes, then please help me make this config :)

1
  • 3
    Well, there's input or popup_menu for making the selection. Then you have to handle argv() or v:argv (to detect -p) in some kind of VimEnter autocommand to decide what to do
    – D. Ben Knoble
    Sep 15 at 19:20
0

A rough sketch with lots of bugs, probably. The function names could use some work, too.

function Templates(ext) abort
  return glob(printf('~/Documents/Library/**/*.%s', a:ext), v:false, v:true)
endfunction

function ChooseTemplateAll() abort
  const ext = fnamemodify(@%, ':e')
  call popup_menu(Templates(ext), #{callback: 'SelectedTemplate', title: 'template for '.@%})
endfunction

function SelectedTemplate(id, result) abort
  if a:result is# -1
    " didn't choose anything
  else
    execute '0read' Templates(fnamemodify(@%, ':e'))[a:result]
  endif
  next
  call ChooseTemplateAll()
endfunction

function ChooseOneTemplate() abort
  const ext = fnamemodify(@%, ':e')
  call popup_menu(Templates(ext), #{callback: 'SelectedOneTemplate', title: 'template for all files'})
endfunction

function SelectedOneTemplate(id, result) abort
  if a:result is# -1
    " didn't choose anything
  else
    execute 'argdo 0read' Templates(fnamemodify(@%, ':e'))[a:result]
    first
  endif
endfunction

function TryTemplate() abort
  if len(v:argv) >= 2 && index(v:argv, '-p') >= 0
    call ChooseOneTemplate()
  else
    call ChooseTemplateAll()
    rewind
  endif
endfunction

augroup templates
  autocmd!
  autocmd VimEnter * call TryTemplate()
augroup END

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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