mhn2's blog

By mhn2, history, 2 years ago, In English

Hello, today in this blog I'm going to share these two vim scripts with you.

  • The first one will simply just remove the current content of your file and will replace it with your template file.
  • The second one will allow you to have multiple templates in the same folder and will let you to choose which template to copy.

Note that these scripts has only been tested on linux. I don't think they will work on Windows and there is no guaranty that it will work on Mac.

Let's start with the simpler script:
fu Template()
    let tempfile = "/path/to/template.cpp"
    silent :execute "!cp " . tempfile . " " . expand("%")
    edit!
    execute "normal \<c-L>"
endf

command T :call Template()
command Temp :call Template()
" map <F12> :call Template() <cr>

So lets explain whats going on:

  • In the 2nd line we keep the path to the template file in a variable, change it to your template file.
  • In the 3rd line we execute the cp command, this will copy the template file to the current file and overwrite the content of the current file. The silent will make the command run without you having to press extra enter keys each time.
  • In the 4th line we ask vim to reload the content of the current file.
  • In the 5th line we ask vim to rerender the page. This will fix the rendering problems that was caused by the previous two lines.
  • In the 8th and 9th we will map the :T and :Temp command to call this function
  • The 10th line will map the F12 key to call this function, this is commented by default, uncomment it if you want to.

If you want to use this script just copy it to the end of your vimrc.

Now lets move on to the more complex script:
fu Template(file="")
    let tempfile = "default-template-name"
    let temppath = "/path/to/template/folder/"
    if a:file != ""
        let tempfile = a:file
    endif
    silent :execute "!cp " . temppath . tempfile . ".cpp " . expand("%")
    edit!
    execute "normal \<c-L>"
endf

command -nargs=? T :call Template("<args>")
command -nargs=? Temp :call Template("<args>")

This script is pretty much the same. Just keep these in you mine:

  • Edit the 2nd line to the name of the default template file that you use. (without extension)
  • Edit the 3rd line to the path of your template folder. Make sure that you put a / at the end.
  • If you use any language other than c++, change the .cpp in the 7th line to your languages file extension.

Same as the previous script, if you want to use it, just copy it to the end of your vimrc.
I personally use the second script because I keep different templates, one for normal problems, one for segment tree problems and one for using the ordered_set. You can however use them for anything you want.

I hope this blog is useful to you. Have a nice day!

Full text and comments »

  • Vote: I like it
  • +11
  • Vote: I do not like it