September 10, 2025

Emacs Org Mode: Updating or Adding the #+date Property When a File is Written

We want to update or add the #+date: export property (or keyword) when an org mode file is saved.

This is accomplished by placing the following code in init.el:

(defun horizon/set-write-date-file-property (&rest ignore)
  "Set the write date in a file export property of org files."
  (message (format "Setting write date for file %s" (buffer-file-name)))
  (when (string-match "\.org$" (buffer-file-name) nil t)
    (save-excursion
      (progn
        (beginning-of-buffer)
        (setq h-time-stamp-string (format-time-string (org-time-stamp-format t nil)))
        (if (re-search-forward "^#\\+date:.+$" nil t 1) ;; hint: use M-x re-builder to figure out the regex
            (progn
              (message "#+date: found, replacing")
              (replace-match (format "#+date: %s" h-time-stamp-string)))
          (progn
            (message "#+date: not found, try adding after title, or at beginning og file")
            (beginning-of-buffer)
            (if (re-search-forward "^#\\+title:.+$" nil t 1) ;; find title
                (insert (format "\n#+date: %s" h-time-stamp-string)) ;; insert after title if found
              (progn ;; insert at top of file if title not found
                (beginning-of-buffer)
                (insert (format "#+date: %s\n" h-time-stamp-string))))
            )))))
  nil) ;; returning non-nil indicates that the file has been written in this hook

(add-hook 'write-file-functions #'horizon/set-write-date-file-property)
Tags: Emacs Lisp Org Mode