这段代码中为什么要检测两次TOC?

最近想改造一下org-mode下回车键的功能,因此参考起了doom-emacs下的配置,有一些代码不理解为什么要这么做,请看这段代码

(`headline
         (cond ((memq (bound-and-true-p org-goto-map)
                      (current-active-maps))
                (org-goto-ret))
               ((and (fboundp 'toc-org-insert-toc)
                     (member "TOC" (org-get-tags)))
                (toc-org-insert-toc)
                (message "Updating table of contents"))
               ((string= "ARCHIVE" (car-safe (org-get-tags)))
                (org-force-cycle-archived))
               ((or (org-element-property :todo-type context)
                    (org-element-property :scheduled context))
                (org-todo
                 (if (eq (org-element-property :todo-type context) 'done)
                     (or (car (+org-get-todo-keywords-for (org-element-property :todo-keyword context)))
                         'todo)
                   'done))))
         ;; Update any metadata or inline previews in this subtree
         (org-update-checkbox-count)
         (org-update-parent-todo-statistics)
         (when (and (fboundp 'toc-org-insert-toc)
                    (member "TOC" (org-get-tags)))
           (toc-org-insert-toc)
           (message "Updating table of contents"))

这里在判断了两次(when (and (fboundp 'toc-org-insert-toc) (member "TOC" (org-get-tags)))

如果满足条件的话,在上面的cond当中应该已经完成了对toc的更新,无需下面再次更新了吧,不知道我的理解有没有问题?

明显不是,上面的cond分支不一定触发,下面是一定要触发的

是由于这里可能满足了,直接跳出了cond吗

那如果是这样的话,完全可以不在cond里判断toc,只保留下面的

是不是能达到一样的效果

1 个赞

cond 分支走完继续往下执行,没有立即退出。

所以,如果 (and (fboundp 'toc-org-insert-toc) (member "TOC" (org-get-tags))) 条件满足的话,就会执行两次 (toc-org-insert-toc)

当光标停在带有 :TOC: 的 Heading line 就会出现上述情况:

* Table of Contents :TOC:
- [[#section-1][section 1]]
- [[#section-2][section 2]]
- [[#section-3][section 3]]

但是这样的话,为什么要执行 (org-update-checkbox-count)?这句的作用是更新进度:

* Taks [1/3]
- [X] Todo1
- [ ] Todo2
- [ ] Todo3

插入 TOC 和更新进度在同一行?我也没有很深度使用 orgmode,不知道这是怎样一种场景。

是的,我能理解会执行两次(toc-org-insert-toc),我指的是满足(and (fboundp 'toc-org-insert-toc) (member "TOC" (org-get-tags)))就会跳出cond语句,不理解的在于为什么要执行两次(toc-org-insert-toc),如果要更新TOC,那只保留下面那一次就可以了,上面cond当中的判断可以省掉?

这部分应该是统计下面的子任务进度的,应该就是放在这里更新一下headline当中的任务计数而已。

光标在 :TOC: 的时候,执行(org-update-checkbox-count t) 才能更新任务进度:

$ emacsq.sh -P org,toc-org --eval "\
  (progn
    (switch-to-buffer \"*.org\")
    (org-mode)
    (insert \"\
  * Table of Contents :TOC:

  * section 1

  * section 2

  * section 3

  * Taks [1/3]
  - [X] Todo1
  - [X] Todo2
  - [ ] Todo3
  \")
    (goto-char (point-min))
    (toc-org-insert-toc)
-   (org-update-checkbox-count)
+   (org-update-checkbox-count t)
    (org-update-parent-todo-statistics)
    (print (buffer-string)))" --batch

结果:

 "* Table of Contents :TOC:
 - [[#section-1][section 1]]
 - [[#section-2][section 2]]
 - [[#section-3][section 3]]
 - [[#taks-13][Taks]]

 * section 1

 * section 2

 * section 3

-* Taks [1/3]
+* Taks [2/3]
 - [X] Todo1
 - [X] Todo2
 - [ ] Todo3
 "