Archive

Posts Tagged ‘template’

Automatic file templates in Vim

February 28th, 2008 pvital No comments

I’d like to share with you, a good post that my friend Alex Zanetti (trustlix) posted in our IBM internal Blog system.

He was trying to automatically add some fancy headers to the our projects *.py files. Searching a little, he discovered how do that using Vim, the text editor that we commonly use to develop.

To set up your Vim text editor to do the same thing, follow the points bellow:

  • Create a directory named .vim/styles, where you’ll add some skeleton files (template text files, each one for a file type):
    • mkdir -p ~/.vim/styles
  • In this directory create the skeleton.py file, with the desired content you’d like to add to every new python file:
    • vim ~/.vim/styles/skeleton.py
  1. # -*- encoding: utf-8 -*-
  2. # Copyright (C) <year> Your Company or Name.
  3. ###
  4. # Classes:
  5. # Author : Your name <your_email@domain>;
  6. # Descr. :
  7. # Created: <date>;
  8. # Updated:
  9. ###
  • After that, add the following lines into the ~/.vimrc file:
  1. "Headers for new files
  2. "——- PYTHON ——-
  3. :autocmd BufNewFile *.py 0r ~/style/skeleton.py
  4. :autocmd BufNewFile *.py   ks|call LastMod()|’s
  5. :fun LastMod()
  6. : if line("$") > 20
  7.    :   let l = 20
  8. : else
  9.    :   let l = line("$")
  10. : endif
  11. : exe "1," . l . "g/Created: /s/Created: .*/Created: " . strftime("%Y %b %d")
  12. : exe "2s/<year>/" . strftime("%Y")
  13. :endfun

The vimrc code above will:

  1. add the content of the skeleton file to every new *.py file created under vim;
  2. replace the “Created: ” string with the current system date;
  3. replace in the line 2 the “<year>” string with the current year.

To test it, type in your shell “vim blah.py”, and a new file called blah.py will be created with the content of the ~/.vim/styles/skeleton.py. In my case, the file created looks like:

  1. # -*- encoding: utf-8 -*-
  2. # Copyright (C) 2008 Paulo Vital.        
  3. ###
  4. # Classes:
  5. # Author : Paulo Vital <pvital at domain>;
  6. # Descr. :
  7. # Created: 2008 Jan 21;
  8. # Updated:
  9. ###

The nice thing is that you can do it differently for any type of file you want, like *.c or *.java, justing creating a new ~/styles/skeleton/ file and adding a new block of code in the ~/.vimrc file to work if those.