求助: org导出前怎么映射标题的级别为更高级别的标题?

举个例子, 我的习惯是从2级标题写到6级标题, 不会用1级标题. 常常只用了2,4,5,6级标题. 如何把2,4,5,6级标题映射为1,2,3,4? 也就是说, 把原本不连续的标题级别,映射成连续的, 且从1开始的. 如果用R描述, 就是headings<-rank(headings) 为什么样这样做:

  • 因为latex只支持5级标题(chapter就不算在内了).
  • 标题级别太低不好看. 就算是html, 如果六级标题总是用item(unordered list), 不美观. 我曾经找到过一段代码:
(defun org-promote-to-top-level ()
  "Promote a single subtree to top-level."
  (let ((cur-level (org-current-level)))
    (loop repeat (/ (- cur-level 1) (org-level-increment))
          do (org-promote-subtree))))

;; Define a function that applies "org-promote-to-top-level" 
;; to each :export: subtree:
(defun org-export-trees-to-top-level (backend)
  "Promote all subtrees tagged :export: to top-level.
BACKEND is the export back-end being used, as a symbol."
  (org-map-entries 'org-promote-to-top-level "+export"))

;; Make org-mode run "org-export-subtrees-to-top-level" as part of the export
;; process:
(add-hook 'org-export-before-parsing-hook 'org-export-trees-to-top-level)

但不起作用. 具体来说, 2级标题的确被映射为1级标题了, 但6级标题不知怎么回事, 还是会被映射为unordered list.

关于这里的org-map-entries这一行, 我想问, 是不是有export的entry只有level最高的那个entry? 比如说, 有2, 4,5,6级标题, 只有2级标题会被调用函数org-promote-to-top-level?

几个月后解决了这个问题, 代码如下:

(defun org-export-trees-to-top-level (backend)
  "Promote all subtrees tagged :export: to top-level.
  BACKEND is the export back-end being used, as a symbol."
  (let (cur-heading (heading-stack-list '(0)) cur-target-heading-level) ; 0 是哨兵, 以免 list 为空
    (org-map-entries (lambda () (setq cur-heading (org-current-level))
                       (while (<= cur-heading (car heading-stack-list)) (progn (pop heading-stack-list)) ) (setq cur-target-heading-level (length heading-stack-list)) (push cur-heading heading-stack-list)
                       (loop repeat (- cur-heading cur-target-heading-level) do (org-do-promote))) )
    )
)

(add-hook 'org-export-before-parsing-hook 'org-export-trees-to-top-level)

举个例子:

*** heading1
***** heading2
** heading3
*** heading4
* heading5
**** heading6
*** heading7
**** heading8
***** heading9

也就是 (3 5 2 3 1 4 3 4 5), 会被映射为 level (1 2 1 2 1 2 2 3 4). 这样就可以保证: 导出时 section 一定是连续且有效的, 并且父子结构与原 org 一致. 实现想法是用栈, 当栈顶表示的标题级别比当前要处理的级别更低, 就 pop, 一直到栈顶级别更高, 此时栈的大小就是标题大小. 再 push 进去.

在这个例子中, 会出现 4 级标题, 注意加上:

(setq org-export-headline-levels 5)

或者:

#+OPTIONS: H:5
4 个赞

为什么不用一级标题?有什么不好使的吗