org-num.el 19 KB

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