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?

Dan
  • 191
  • 5
  • 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?) – Dan Oct 29 '20 at 15:53
  • 2
    There are lots of generic mechanisms for inserting templates in emacs. See e.g. [skeleton](https://www.gnu.org/software/emacs/manual/html_mono/autotype.html#Skeleton-Language) in the Autotyping manual. See also [Category Templates](https://www.emacswiki.org/emacs/CategoryTemplates) in the Emacs Wiki. – NickD Oct 29 '20 at 15:59

1 Answers1

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")))
Phil Hudson
  • 1,651
  • 10
  • 13
aadcg
  • 1,203
  • 6
  • 13