org-num.el 18 KB

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