org-num.el 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. ;;; org-num.el --- Dynamic Headlines Numbering -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2018-2022 Free Software Foundation, Inc.
  3. ;; Author: Nicolas Goaziou <mail@nicolasgoaziou.fr>
  4. ;; Keywords: outlines, hypermedia, calendar, wp
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software; you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; This library provides dynamic numbering for Org headlines. Use
  18. ;;
  19. ;; <M-x org-num-mode>
  20. ;;
  21. ;; to toggle it.
  22. ;;
  23. ;; You can select what is numbered according to level, tags, COMMENT
  24. ;; keyword, or UNNUMBERED property. You can also skip footnotes
  25. ;; sections. See `org-num-max-level', `org-num-skip-tags',
  26. ;; `org-num-skip-commented', `org-num-skip-unnumbered', and
  27. ;; `org-num-skip-footnotes' for details.
  28. ;;
  29. ;; You can also control how the numbering is displayed by setting
  30. ;;`org-num-face' and `org-num-format-function'.
  31. ;;
  32. ;; Internally, the library handles an ordered list, per buffer
  33. ;; position, of overlays in `org-num--overlays'. These overlays are
  34. ;; marked with the `org-num' property set to a non-nil value.
  35. ;;
  36. ;; Overlays store the level of the headline in the `level' property,
  37. ;; and the face used for the numbering in `numbering-face'.
  38. ;;
  39. ;; The `skip' property is set to t when the corresponding headline has
  40. ;; some characteristic -- e.g., a node property, or a tag -- that
  41. ;; prevents it from being numbered.
  42. ;;
  43. ;; An overlay with `org-num' property set to `invalid' is called an
  44. ;; invalid overlay. Modified overlays automatically become invalid
  45. ;; and set `org-num--invalid-flag' to a non-nil value. After
  46. ;; a change, `org-num--invalid-flag' indicates numbering needs to be
  47. ;; updated and invalid overlays indicate where the buffer needs to be
  48. ;; parsed. So does `org-num--missing-overlay' variable. See
  49. ;; `org-num--verify' function for details.
  50. ;;
  51. ;; Numbering display is done through the `after-string' property.
  52. ;;; Code:
  53. (require 'org-macs)
  54. (org-assert-version)
  55. (require 'cl-lib)
  56. (require 'org-macs)
  57. (require 'org) ;Otherwise `org-num--comment-re' burps on `org-comment-string'
  58. (defvar org-comment-string)
  59. (defvar org-complex-heading-regexp)
  60. (defvar org-cycle-level-faces)
  61. (defvar org-footnote-section)
  62. (defvar org-level-faces)
  63. (defvar org-n-level-faces)
  64. (defvar org-odd-levels-only)
  65. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  66. (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
  67. (declare-function org-reduced-level "org" (l))
  68. ;;; Customization
  69. (defcustom org-num-face nil
  70. "Face to use for numbering.
  71. When nil, use the same face as the headline. This value is
  72. ignored if `org-num-format-function' specifies a face for its
  73. output."
  74. :group 'org-appearance
  75. :package-version '(Org . "9.3")
  76. :type '(choice (const :tag "Like the headline" nil)
  77. (face :tag "Use face"))
  78. :safe (lambda (val) (or (null val) (facep val))))
  79. (defcustom org-num-format-function #'org-num-default-format
  80. "Function used to display numbering.
  81. It is called with one argument, a list of numbers, and should
  82. return a string, or nil. When nil, no numbering is displayed.
  83. Any `face' text property on the returned string overrides
  84. `org-num-face'."
  85. :group 'org-appearance
  86. :package-version '(Org . "9.3")
  87. :type 'function)
  88. (defcustom org-num-max-level nil
  89. "Level below which headlines are not numbered.
  90. When set to nil, all headlines are numbered."
  91. :group 'org-appearance
  92. :package-version '(Org . "9.3")
  93. :type '(choice (const :tag "Number everything" nil)
  94. (integer :tag "Stop numbering at level"))
  95. :safe (lambda (val) (or (null val) (wholenump val))))
  96. (defcustom org-num-skip-commented nil
  97. "Non-nil means commented sub-trees are not numbered."
  98. :group 'org-appearance
  99. :package-version '(Org . "9.3")
  100. :type 'boolean
  101. :safe #'booleanp)
  102. (defcustom org-num-skip-footnotes nil
  103. "Non-nil means footnotes sections are not numbered."
  104. :group 'org-appearance
  105. :package-version '(Org . "9.3")
  106. :type 'boolean
  107. :safe #'booleanp)
  108. (defcustom org-num-skip-tags nil
  109. "List of tags preventing the numbering of sub-trees.
  110. For example, add \"ARCHIVE\" to this list to avoid numbering
  111. archived sub-trees.
  112. Tag in this list prevent numbering the whole sub-tree,
  113. irrespective to `org-use-tag-inheritance', or other means to
  114. control tag inheritance."
  115. :group 'org-appearance
  116. :package-version '(Org . "9.3")
  117. :type '(repeat (string :tag "Tag"))
  118. :safe (lambda (val) (and (listp val) (cl-every #'stringp val))))
  119. (defcustom org-num-skip-unnumbered nil
  120. "Non-nil means numbering obeys to UNNUMBERED property."
  121. :group 'org-appearance
  122. :package-version '(Org . "9.3")
  123. :type 'boolean
  124. :safe #'booleanp)
  125. ;;; Internal Variables
  126. (defconst org-num--comment-re (format "\\`%s\\(?: \\|$\\)" org-comment-string)
  127. "Regexp matching a COMMENT keyword at headline beginning.")
  128. (defvar-local org-num--overlays nil
  129. "Ordered list of overlays used for numbering outlines.")
  130. (defvar-local org-num--skip-level nil
  131. "Level below which headlines from current tree are not numbered.
  132. When nil, all headlines are numbered. It is used to handle
  133. inheritance of no-numbering attributes.")
  134. (defvar-local org-num--numbering nil
  135. "Current headline numbering.
  136. A numbering is a list of integers, in reverse order. So numbering
  137. for headline \"1.2.3\" is (3 2 1).")
  138. (defvar-local org-num--missing-overlay nil
  139. "Buffer position signaling a headline without an overlay.")
  140. (defvar-local org-num--invalid-flag nil
  141. "Non-nil means an overlay became invalid since last update.")
  142. ;;; Internal Functions
  143. (defsubst org-num--headline-regexp ()
  144. "Return regexp matching a numbered headline."
  145. (if (null org-num-max-level) (org-with-limited-levels org-outline-regexp-bol)
  146. (format "^\\*\\{1,%d\\} "
  147. (if org-odd-levels-only (1- (* 2 org-num-max-level))
  148. org-num-max-level))))
  149. (defsubst org-num--overlay-p (o)
  150. "Non-nil if overlay O is a numbering overlay."
  151. (overlay-get o 'org-num))
  152. (defsubst org-num--valid-overlay-p (o)
  153. "Non-nil if overlay O is still active in the buffer."
  154. (not (eq 'invalid (overlay-get o 'org-num))))
  155. (defsubst org-num--invalidate-overlay (o)
  156. "Mark overlay O as invalid.
  157. Update `org-num--invalid-flag' accordingly."
  158. (overlay-put o 'org-num 'invalid)
  159. (setq org-num--invalid-flag t))
  160. (defun org-num--clear ()
  161. "Remove all numbering overlays in current buffer."
  162. (mapc #'delete-overlay org-num--overlays)
  163. (setq org-num--overlays nil))
  164. (defun org-num--make-overlay (numbering level skip)
  165. "Return overlay for numbering headline at point.
  166. NUMBERING is the numbering to use, as a list of integers, or nil
  167. if nothing should be displayed. LEVEL is the level of the
  168. headline. SKIP is its skip value.
  169. Assume point is at a headline."
  170. (let ((after-edit-functions
  171. (list (lambda (o &rest _) (org-num--invalidate-overlay o))))
  172. (o (save-excursion
  173. (beginning-of-line)
  174. (skip-chars-forward "*")
  175. (make-overlay (line-beginning-position) (1+ (point))))))
  176. (overlay-put o 'org-num t)
  177. (overlay-put o 'skip skip)
  178. (overlay-put o 'level level)
  179. (overlay-put o 'numbering-face
  180. (or org-num-face
  181. ;; Compute face that would be used at the
  182. ;; headline. We cannot extract it from the
  183. ;; buffer: at the time the overlay is created,
  184. ;; Font Lock has not proceeded yet.
  185. (nth (if org-cycle-level-faces
  186. (% (1- level) org-n-level-faces)
  187. (1- (min level org-n-level-faces)))
  188. org-level-faces)))
  189. (overlay-put o 'modification-hooks after-edit-functions)
  190. (overlay-put o 'insert-in-front-hooks after-edit-functions)
  191. (org-num--refresh-display o numbering)
  192. o))
  193. (defun org-num--refresh-display (overlay numbering)
  194. "Refresh OVERLAY's display.
  195. NUMBERING specifies the new numbering, as a list of integers, or
  196. nil if nothing should be displayed. Assume OVERLAY is valid."
  197. (let ((display (and numbering
  198. (funcall org-num-format-function (reverse numbering)))))
  199. (when (and display (not (get-text-property 0 'face display)))
  200. (org-add-props display `(face ,(overlay-get overlay 'numbering-face))))
  201. (overlay-put overlay 'after-string display)))
  202. (defun org-num--skip-value ()
  203. "Return skip value for headline at point.
  204. Value is t when headline should not be numbered, and nil
  205. otherwise."
  206. (org-match-line org-complex-heading-regexp)
  207. (let ((title (match-string 4))
  208. (tags (and org-num-skip-tags
  209. (match-end 5)
  210. (org-split-string (match-string 5) ":"))))
  211. (or (and org-num-skip-footnotes
  212. org-footnote-section
  213. (equal title org-footnote-section))
  214. (and org-num-skip-commented
  215. title
  216. (let ((case-fold-search nil))
  217. (string-match org-num--comment-re title))
  218. t)
  219. (and org-num-skip-tags
  220. (cl-some (lambda (tag) (member tag org-num-skip-tags))
  221. tags)
  222. t)
  223. (and org-num-skip-unnumbered
  224. (org-entry-get (point) "UNNUMBERED")
  225. t))))
  226. (defun org-num--current-numbering (level skip)
  227. "Return numbering for current headline.
  228. LEVEL is headline's level, and SKIP its skip value. Return nil
  229. if headline should be skipped."
  230. (cond
  231. ;; Skipped by inheritance.
  232. ((and org-num--skip-level (> level org-num--skip-level)) nil)
  233. ;; Skipped by a non-nil skip value; set `org-num--skip-level'
  234. ;; to skip the whole sub-tree later on.
  235. (skip (setq org-num--skip-level level) nil)
  236. (t
  237. (setq org-num--skip-level nil)
  238. ;; Compute next numbering, and update `org-num--numbering'.
  239. (let ((last-level (length org-num--numbering)))
  240. (setq org-num--numbering
  241. (cond
  242. ;; First headline : nil => (1), or (1 0)...
  243. ((null org-num--numbering) (cons 1 (make-list (1- level) 0)))
  244. ;; Sibling: (1 1) => (2 1).
  245. ((= level last-level)
  246. (cons (1+ (car org-num--numbering)) (cdr org-num--numbering)))
  247. ;; Parent: (1 1 1) => (2 1), or (2).
  248. ((< level last-level)
  249. (let ((suffix (nthcdr (- last-level level) org-num--numbering)))
  250. (cons (1+ (car suffix)) (cdr suffix))))
  251. ;; Child: (1 1) => (1 1 1), or (1 0 1 1)...
  252. (t
  253. (append (cons 1 (make-list (- level last-level 1) 0))
  254. org-num--numbering))))))))
  255. (defun org-num--number-region (start end)
  256. "Add numbering overlays between START and END positions.
  257. When START or END are nil, use buffer boundaries. Narrowing, if
  258. any, is ignored. Return the list of created overlays, newest
  259. first."
  260. (org-with-point-at (or start 1)
  261. ;; Do not match headline starting at START.
  262. (when start (end-of-line))
  263. (let ((regexp (org-num--headline-regexp))
  264. (new nil))
  265. (while (re-search-forward regexp end t)
  266. (let* ((level (org-reduced-level
  267. (- (match-end 0) (match-beginning 0) 1)))
  268. (skip (org-num--skip-value))
  269. (numbering (org-num--current-numbering level skip)))
  270. ;; Apply numbering to current headline. Store overlay for
  271. ;; the return value.
  272. (push (org-num--make-overlay numbering level skip)
  273. new)))
  274. new)))
  275. (defun org-num--update ()
  276. "Update buffer's numbering.
  277. This function removes invalid overlays and refreshes numbering
  278. for the valid ones in the numbering overlays list. It also adds
  279. missing overlays to that list."
  280. (setq org-num--skip-level nil)
  281. (setq org-num--numbering nil)
  282. (let ((new-overlays nil)
  283. (overlay nil))
  284. (while (setq overlay (pop org-num--overlays))
  285. (cond
  286. ;; Valid overlay.
  287. ;;
  288. ;; First handle possible missing overlays OVERLAY. If missing
  289. ;; overlay marker is pointing before next overlay and after the
  290. ;; last known overlay, make sure to parse the buffer between
  291. ;; these two overlays.
  292. ((org-num--valid-overlay-p overlay)
  293. (let ((next (overlay-start overlay))
  294. (last (and new-overlays (overlay-start (car new-overlays)))))
  295. (cond
  296. ((null org-num--missing-overlay))
  297. ((> org-num--missing-overlay next))
  298. ((or (null last) (> org-num--missing-overlay last))
  299. (setq org-num--missing-overlay nil)
  300. (setq new-overlays (nconc (org-num--number-region last next)
  301. new-overlays)))
  302. ;; If it is already after the last known overlay, reset it:
  303. ;; some previous invalid overlay already triggered the
  304. ;; necessary parsing.
  305. (t
  306. (setq org-num--missing-overlay nil))))
  307. ;; Update OVERLAY's numbering.
  308. (let* ((level (overlay-get overlay 'level))
  309. (skip (overlay-get overlay 'skip))
  310. (numbering (org-num--current-numbering level skip)))
  311. (org-num--refresh-display overlay numbering)
  312. (push overlay new-overlays)))
  313. ;; Invalid overlay. It indicates that the buffer needs to be
  314. ;; parsed again between the two surrounding valid overlays or
  315. ;; buffer boundaries.
  316. (t
  317. ;; Delete all consecutive invalid overlays: we re-create all
  318. ;; overlays between last valid overlay and the next one.
  319. (delete-overlay overlay)
  320. (while (and org-num--overlays
  321. (not (org-num--valid-overlay-p (car org-num--overlays))))
  322. (delete-overlay (pop org-num--overlays)))
  323. ;; Create and register new overlays.
  324. (let ((last (and new-overlays (overlay-start (car new-overlays))))
  325. (next (and org-num--overlays
  326. (overlay-start (car org-num--overlays)))))
  327. (setq new-overlays (nconc (org-num--number-region last next)
  328. new-overlays))))))
  329. ;; If invalid position hasn't been handled yet, it must be located
  330. ;; between last valid overlay and end of the buffer. Parse that
  331. ;; area before returning.
  332. (when org-num--missing-overlay
  333. (let ((last (and new-overlays (overlay-start (car new-overlays)))))
  334. (setq new-overlays (nconc (org-num--number-region last nil)
  335. new-overlays))))
  336. ;; Numbering is now up-to-date. Reset invalid flag. Also return
  337. ;; `org-num--overlays' in a sorted fashion.
  338. (setq org-num--invalid-flag nil)
  339. (setq org-num--overlays (nreverse new-overlays))))
  340. (defun org-num--verify (beg end _)
  341. "Check numbering integrity; update it if necessary.
  342. This function is meant to be used in `after-change-functions'.
  343. See this variable for the meaning of BEG and END."
  344. (setq org-num--missing-overlay nil)
  345. (save-match-data
  346. (org-with-point-at beg
  347. (let ((regexp (org-num--headline-regexp)))
  348. ;; At this point, directly altered overlays between BEG and
  349. ;; END are marked as invalid and will trigger a full update.
  350. ;; However, there are still two cases to handle.
  351. ;;
  352. ;; First, some valid overlays may need to be invalidated, due
  353. ;; to an indirect change. That happens when the skip value --
  354. ;; see `org-num--skip-value' -- of the heading BEG belongs to
  355. ;; is altered, or when deleting the newline character right
  356. ;; before the next headline.
  357. (save-excursion
  358. ;; Bail out if we're before first headline or within
  359. ;; a headline too deep to be numbered.
  360. (when (and (org-with-limited-levels
  361. (ignore-errors (org-back-to-heading t)))
  362. (looking-at regexp))
  363. (pcase (get-char-property-and-overlay (point) 'org-num)
  364. (`(nil)
  365. ;; At a headline, without a numbering overlay: change
  366. ;; just created one. Mark it for parsing.
  367. (setq org-num--missing-overlay (point)))
  368. (`(t . ,o)
  369. ;; Check if skip value changed. Invalidate overlay
  370. ;; accordingly.
  371. (unless (eq (org-num--skip-value) (overlay-get o 'skip))
  372. (org-num--invalidate-overlay o)))
  373. (_ nil))))
  374. ;; Deleting the newline character before a numbering overlay
  375. ;; doesn't invalidate it, even though it could land in the
  376. ;; middle of a line. Be sure to catch this case.
  377. (when (and (= beg end) (not (bolp)))
  378. (pcase (get-char-property-and-overlay (point) 'org-num)
  379. (`(t . ,o) (org-num--invalidate-overlay o))
  380. (_ nil)))
  381. ;; Second, if nothing is marked as invalid, and therefore if
  382. ;; no full update is due so far, changes may still have
  383. ;; created new headlines, at BEG -- which is actually handled
  384. ;; by the previous phase --, or, in case of a multi-line
  385. ;; insertion, at END, or in-between.
  386. (unless (or org-num--invalid-flag
  387. org-num--missing-overlay
  388. (<= end (line-end-position))) ;single line change
  389. (forward-line)
  390. (when (or (re-search-forward regexp end 'move)
  391. ;; Check if change created a headline after END.
  392. (progn (skip-chars-backward "*") (looking-at regexp)))
  393. (setq org-num--missing-overlay (line-beginning-position))))))
  394. ;; Update numbering only if a headline was altered or created.
  395. (when (or org-num--missing-overlay org-num--invalid-flag)
  396. (org-num--update))))
  397. ;;; Public Functions
  398. ;;;###autoload
  399. (defun org-num-default-format (numbering)
  400. "Default numbering display function.
  401. NUMBERING is a list of numbers."
  402. (concat (mapconcat #'number-to-string numbering ".") " "))
  403. ;;;###autoload
  404. (define-minor-mode org-num-mode
  405. "Dynamic numbering of headlines in an Org buffer."
  406. :lighter " o#"
  407. (cond
  408. (org-num-mode
  409. (unless (derived-mode-p 'org-mode)
  410. (user-error "Cannot activate headline numbering outside Org mode"))
  411. (org-num--clear)
  412. (setq org-num--numbering nil)
  413. (setq org-num--overlays (nreverse (org-num--number-region nil nil)))
  414. (add-hook 'after-change-functions #'org-num--verify nil t)
  415. (add-hook 'change-major-mode-hook #'org-num--clear nil t))
  416. (t
  417. (org-num--clear)
  418. (remove-hook 'after-change-functions #'org-num--verify t)
  419. (remove-hook 'change-major-mode-hook #'org-num--clear t))))
  420. (provide 'org-num)
  421. ;; Local variables:
  422. ;; generated-autoload-file: "org-loaddefs.el"
  423. ;; End:
  424. ;;; org-num.el ends here