2

When creating a new section in an Org-Mode document I want to automatically add a :CREATED: date property, by example:

* Test
:PROPERTIES:
:CREATED:: 2022-06-13 11:05:59
:END:

I wrote a solution (see answer) however I am not 100% sure it has no side effect. Maybe a better solution exists ?

1 Answer 1

3

I came up with this solution :

(add-hook 'org-insert-heading-hook
(lambda()
(save-excursion
          (org-back-to-heading)
          (org-set-property "CREATED:" (format-time-string "%Y-%m-%d %T")))))

UPDATE:

I read what-you-need-to-know-about-hooks :

It’s important to mention that you shouldn’t use anonymous functions for your hooks because it becomes hard to tell the purpose of a lambda when you inspect the hook at some later point. Another benefit of using named functions is that you can easily remove them by passing their name to remove-hook.

By consequence, I updated my solution as follows :

(defun set-creation-date-heading-property ()
  (save-excursion
    (org-back-to-heading)
    (org-set-property "CREATED:" (format-time-string "%Y-%m-%d %T"))))

(defun my-org-mode-date-heading-on ()
  "Turn on heading creation date property"
  (interactive)
  (add-hook 'org-insert-heading-hook #'set-creation-date-heading-property))

(defun my-org-mode-date-heading-off ()
  "Turn off heading creation date property"
  (interactive)
  (remove-hook 'org-insert-heading-hook #'set-creation-date-heading-property))

You can use the two functions my-org-mode-date-heading-on and my-org-mode-date-heading-off to turn on/off automatic creation of the "CREATED" property.

2
  • You might want to consider bracketing the time string, to make it an inactive time stamp: (format-time-string "[%Y-%m-%d %T]") Jun 14 at 19:57
  • @PhilHudson thanks for this idea. Jun 14 at 20:05

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.