如何获取某个元素所属的标题

How to get the headline an element belongs to

我可以在页面上使用 org-element-context,例如 link,然后向上走 parents 以查看它属于哪个段落。但是,我想获取 paragraph/link 下的 header 的值。有没有一种明智的方法可以做到这一点?我是 org-mode AST 的新手,所以任何一般提示都将不胜感激。

这取决于您需要标题中的哪些信息:

如果只需要标题的文字,可以使用org-get-heading。 (编辑:此函数似乎已添加到 Org 版本 8.2.10 和 8.3.2 之间的某处。)请注意,此函数 returns 一个 propertized 文本字符串(参见 this manual entry 了解更多信息,但对于大多数用途,您可以忽略文本属性并将其视为字符串)。

如果您想要航向位置,我(令人惊讶地)找不到任何开箱即用的功能。我会这样做:

(defun my/org-back-to-heading-safe (&optional invisible-ok)
  "As `org-back-to-heading', but return nil before first heading."
  (condition-case err
      (org-back-to-heading invisible-ok)
    (error nil)))

(defun my/org-get-heading-pos ()
  "Return position of heading containing point.
If before the first heading of the buffer, return nil.
Do not move point."
  (save-excursion (my/org-back-to-heading-safe :invisible-ok)))

如果你想要像 org-element-context 这样的完整列表,你可以做类似的事情:

(defun my/org-element-heading ()
  "Return context for heading containing point.
As `org-element-context', if point is on a heading.  Otherwise,
return the value `org-element-context' would return if point were
on its heading.

If before the first heading of the buffer, return nil."
  (save-excursion
    (when (my/org-back-to-heading-safe :invisible-ok)
      (org-element-context))))