2

When I open a fresh file for coding, I like to insert a header like this:

#####################################################################   
# Purpose:
# Author: me (me@someplace.com)
# Date:
#####################################################################   

I keep this text in a file called header in ~/.emacs.d/ and I insert it like so:

;; Insert header to file 
(defun header()
  "Insert header into file"
  (interactive)
  (insert-file "~/.emacs.d/header")) 

which I call with M+x header. Very cool! I also have a function for adding the date:

;; Insert today's date
(defun today ()
  "Insert today's date"
  (interactive)
  (insert (format-time-string "%Y-%m-%d")))  

which I invoke with M+x today after inserting my header text in order to populate the Date: field.

Q: Is there a way that I can merge these functions such that the date is automatically inserted after Date: when I insert my header text? For example, can I add (format-time-string "%Y-%m-%d") after Date: in my header file and evaluate it somehow when it is inserted?

3
  • 1
    You need something along the following lines: (defun header() "Insert header into file" (interactive) (progn (insert-file "~/.emacs.d/header") (re-search-backward "Date: ") (insert (format-time-string "%Y-%m-%d"))))
    – aadcg
    Oct 29 '20 at 15:47
  • Whoa – that's magical! Care to turn it into an answer so I can mark this answered? (I found that I had to change re-search-backward to re-search-forward since the text is inserted after the cursor, presumably?)
    – Lyngbakr
    Oct 29 '20 at 15:53
  • 2
    There are lots of generic mechanisms for inserting templates in emacs. See e.g. skeleton in the Autotyping manual. See also Category Templates in the Emacs Wiki.
    – NickD
    Oct 29 '20 at 15:59
2

Inside of GNU Emacs only your imagination is the limit :)

I think you're looking for something along the following lines, though some adjustments might be needed.

(defun header()
  "Insert header into file"
  (interactive)
  (insert-file "~/.emacs.d/header")
  (re-search-backward "Date:")
  (insert (format-time-string "%Y-%m-%d")))

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.