Adding a template for new Python files in Emacs

I wanted my name and email address to appear in the top of the page every time I create a new python file in Emacs. So here’s what I did to achieve that.

First of all create a folder called templates in the .emacs.d directory (the .emacs.d directory is located in your home directory. If it does not exist, just create the directory ). Then create a file named template.py  in that directory. And add the text you want to be included when you create a new python file. An example can be shown as follows.

#Name: This Is My Name

#E-mail: someone@somewhere.lol

Then open the .emacs file in your home directory (if this doesn’t exist, simply create an empty file named .emacs). Then add the following content to the bottom of the .emcas.

 Lisp |  copy code |? 
01
;#############################################
02
;To load python templates
03
 
04
(add-hook 'find-file-hooks 'maybe-load-template)
05
(defun maybe-load-template ()
06
  (interactive)
07
  (when (and 
08
         (string-match "\\.py$" (buffer-file-name))
09
         (eq 1 (point-max)))
10
    (insert-file "~/.emacs.d/templates/template.py")))

(Use the ‘Lisp’ link above to copy the code).

That’s all…!. Now when ever you create a new python file using Emacs these header info will appear!.

More info:

As you might have observed this trick can be extended to other file types by changing the .py extension in the (insert-file “~/.emacs.d/templates/template.py”) line and creating a relevant template in the templates folder.

Also there are more advanced ways to achieve the same with more functionality in http://www.emacswiki.org/emacs/AutomaticFileHeaders

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *