如何为Org文件所有一级标题自动添加递归统计属性?
Sure thing—you can automate this with a straightforward Emacs Lisp snippet built for Org-mode. Let's cover both updating your existing tasks.org file and setting up automatic property addition for new top-level headings:
1. Batch Update Existing Top-Level Headings
This snippet will scan your entire Org file and add the required :PROPERTIES: block to any level-1 heading that doesn't already have the recursive cookie data:
(defun my/org-add-recursive-cookie-to-top-level () "Add :COOKIE_DATA: recursive property to all top-level Org headings." (interactive) (org-map-entries (lambda () ;; Skip headings that already have the recursive cookie property (unless (org-entry-get (point) "COOKIE_DATA" 'inherit) (end-of-line) (newline) (insert ":PROPERTIES:\n:COOKIE_DATA: recursive\n:END:"))) t 'tree "^\\* ")) ; Target only level-1 headings
To run this on your tasks.org:
- Open the file in Emacs
- Call the function with
M-x my/org-add-recursive-cookie-to-top-level - Save your changes with
C-x C-s
2. Auto-Add Properties to New Top-Level Headings
To eliminate manual work entirely for future date headings, add this hook to your Emacs configuration (e.g., ~/.emacs.d/init.el):
(defun my/org-set-recursive-cookie-on-new-top-level () "Automatically set :COOKIE_DATA: recursive for new level-1 Org headings." (when (= (org-current-level) 1) (org-set-property "COOKIE_DATA" "recursive"))) (add-hook 'org-insert-heading-hook #'my/org-set-recursive-cookie-on-new-top-level)
How This Works
- The batch function uses
org-map-entriesto loop through every top-level heading. It checks for the existingCOOKIE_DATAproperty, and inserts the full properties block only if it's missing. - The hook triggers every time you insert a new heading. If it's a level-1 heading (like your date entries), it automatically sets the
recursivecookie property—Org-mode will handle wrapping it in the proper:PROPERTIES:block for you.
Key Note
This setup ensures your task completion counts (e.g., [3/3]) will recursively calculate sub-task progress even when you collapse the top-level date headings, which is exactly what the recursive cookie data enables.
内容的提问来源于stack exchange,提问作者Siraben

