org-num.el 19 KB

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