views:

131

answers:

2

When I create a .tex file using vim I get a nice template from having

autocmd BufNewFile *.tex 0r $HOME/.vim/templates/skeleton.tex

in my .vimrc. I also have a makefile-template in my home directory, but this one I have to manually copy to where the .tex file is. In a Linux environment, how can I auto-copy or auto-generate the makefile at the same time as I create a .tex file?

+2  A: 

The normal ex command to do this would be

:!cp $HOME/.vim/templates/skeleton.makefile %:p:h

So you just need to add another autocmd (which will execute after the first)

autocmd BufNewFile *.tex silent !cp $HOME/.vim/templates/skeleton.makefile %:p:h

(the silent simply prevents the copy command from being printed on execution).

rampion
I also appreciate this answer because it is short and will work most of the time. Yet some times I will create two tex files in the same directory and then the makefile will be overwritten.
Viktiglemma
@Viktiglemma: I agree, that is a valid concern that I did not address. However, it could be fixed by changing it to `cp -n` (assuming you're on a *nix system). Any true crossplatform solution should be done in vimscript, as Luc does.
rampion
This was very close to what I came up with.I would suggest changing `cp` to `cp -i`. That way you'll be prompted if you want to overwrite the existing file or not. @rampion: `-n` doesn't seem to be a valid option for `cp` on either Ubuntu 8.04 or Solaris 10.Also, you may want to add `/Makefile` to the end of the `autocmd` if you want to rename the skeleton file.
Curt Nelson
+2  A: 

The portable answer would not use cp (which may overwrite a preexisting makefile) but the vim functions readfile() and writefile().

To trigger it, the best thing would be to define and execute a function that loads the first skeleton, and creates the Makefile on the fly:

" untested code
"
function! s:NewTeXPlusMakefile()
  let where = expand('%:p:h')
  " see mu-template's fork for a more advanced way to find template-files
  let skeletons_path = globpath(&rtp, 'templates')

  " the current .tex file
  let lines = readfile(skeletons_path.'/skeleton.tex')
  call setline(1, lines)

  " the Makefile, that MUST not be overwritten when it already exists!
  let makefile = where.'/Makefile'
  if ! filereadable(makefile)
    let lines = readfile(skeletons_path.'/skeleton.makefile')
    call writefile(lines, makefile )
  endif
endfunction

augroup LaTeXTemplates
  au!
  au BufNewFile *.tex call s:NewTeXPlusMakefile()
augroup END
Luc Hermitte
I flag this as the most complete answer.
Viktiglemma