org-num.el 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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--make-overlay (numbering level skip)
  150. "Return overlay for numbering headline at point.
  151. NUMBERING is the numbering to use, as a list of integers, or nil
  152. if nothing should be displayed. LEVEL is the level of the
  153. headline. SKIP is its skip value.
  154. Assume point is at a headline."
  155. (let ((after-edit-functions
  156. (list (lambda (o &rest _) (org-num--invalidate-overlay o))))
  157. (o (save-excursion
  158. (beginning-of-line)
  159. (skip-chars-forward "*")
  160. (make-overlay (line-beginning-position) (1+ (point))))))
  161. (overlay-put o 'org-num t)
  162. (overlay-put o 'skip skip)
  163. (overlay-put o 'level level)
  164. (overlay-put o 'numbering-face
  165. (or org-num-face
  166. ;; Compute face that would be used at the
  167. ;; headline. We cannot extract it from the
  168. ;; buffer: at the time the overlay is created,
  169. ;; Font Lock has not proceeded yet.
  170. (nth (if org-cycle-level-faces
  171. (% (1- level) org-n-level-faces)
  172. (1- (min level org-n-level-faces)))
  173. org-level-faces)))
  174. (overlay-put o 'modification-hooks after-edit-functions)
  175. (overlay-put o 'insert-in-front-hooks after-edit-functions)
  176. (org-num--refresh-display o numbering)
  177. o))
  178. (defun org-num--refresh-display (overlay numbering)
  179. "Refresh OVERLAY's display.
  180. NUMBERING specifies the new numbering, as a list of integers, or
  181. nil if nothing should be displayed. Assume OVERLAY is valid."
  182. (let ((display (and numbering
  183. (funcall org-num-format-function (reverse numbering)))))
  184. (when (and display (not (get-text-property 0 'face display)))
  185. (org-add-props display `(face ,(overlay-get overlay 'numbering-face))))
  186. (overlay-put overlay 'after-string display)))
  187. (defun org-num--skip-value ()
  188. "Return skip value for headline at point.
  189. Value is t when headline should not be numbered, and nil
  190. otherwise."
  191. (org-match-line org-complex-heading-regexp)
  192. (let ((title (match-string 4))
  193. (tags (and org-num-skip-tags
  194. (match-end 5)
  195. (org-split-string (match-string 5) ":"))))
  196. (or (and org-num-skip-footnotes
  197. org-footnote-section
  198. (equal title org-footnote-section))
  199. (and org-num-skip-commented
  200. (let ((case-fold-search nil))
  201. (string-match org-num--comment-re title))
  202. t)
  203. (and org-num-skip-tags
  204. (cl-some (lambda (tag) (member tag org-num-skip-tags))
  205. tags)
  206. t)
  207. (and org-num-skip-unnumbered
  208. (org-entry-get (point) "UNNUMBERED")
  209. t))))
  210. (defun org-num--current-numbering (level skip)
  211. "Return numbering for current headline.
  212. LEVEL is headline's level, and SKIP its skip value. Return nil
  213. if headline should be skipped."
  214. (cond
  215. ;; Skipped by inheritance.
  216. ((and org-num--skip-level (> level org-num--skip-level)) nil)
  217. ;; Skipped by a non-nil skip value; set `org-num--skip-level'
  218. ;; to skip the whole sub-tree later on.
  219. (skip (setq org-num--skip-level level) nil)
  220. (t
  221. (setq org-num--skip-level nil)
  222. ;; Compute next numbering, and update `org-num--numbering'.
  223. (let ((last-level (length org-num--numbering)))
  224. (setq org-num--numbering
  225. (cond
  226. ;; First headline : nil => (1), or (1 0)...
  227. ((null org-num--numbering) (cons 1 (make-list (1- level) 0)))
  228. ;; Sibling: (1 1) => (2 1).
  229. ((= level last-level)
  230. (cons (1+ (car org-num--numbering)) (cdr org-num--numbering)))
  231. ;; Parent: (1 1 1) => (2 1), or (2).
  232. ((< level last-level)
  233. (let ((suffix (nthcdr (- last-level level) org-num--numbering)))
  234. (cons (1+ (car suffix)) (cdr suffix))))
  235. ;; Child: (1 1) => (1 1 1), or (1 0 1 1)...
  236. (t
  237. (append (cons 1 (make-list (- level last-level 1) 0))
  238. org-num--numbering))))))))
  239. (defun org-num--number-region (start end)
  240. "Add numbering overlays between START and END positions.
  241. When START or END are nil, use buffer boundaries. Narrowing, if
  242. any, is ignored. Return the list of created overlays, newest
  243. first."
  244. (org-with-point-at (or start 1)
  245. ;; Do not match headline starting at START.
  246. (when start (end-of-line))
  247. (let ((regexp (org-num--headline-regexp))
  248. (new nil))
  249. (while (re-search-forward regexp end t)
  250. (let* ((level (org-reduced-level
  251. (- (match-end 0) (match-beginning 0) 1)))
  252. (skip (org-num--skip-value))
  253. (numbering (org-num--current-numbering level skip)))
  254. ;; Apply numbering to current headline. Store overlay for
  255. ;; the return value.
  256. (push (org-num--make-overlay numbering level skip)
  257. new)))
  258. new)))
  259. (defun org-num--update ()
  260. "Update buffer's numbering.
  261. This function removes invalid overlays and refreshes numbering
  262. for the valid ones in the numbering overlays list. It also adds
  263. missing overlays to that list."
  264. (setq org-num--skip-level nil)
  265. (setq org-num--numbering nil)
  266. (let ((new-overlays nil)
  267. (overlay nil))
  268. (while (setq overlay (pop org-num--overlays))
  269. (cond
  270. ;; Valid overlay.
  271. ;;
  272. ;; First handle possible missing overlays OVERLAY. If missing
  273. ;; overlay marker is pointing before next overlay and after the
  274. ;; last known overlay, make sure to parse the buffer between
  275. ;; these two overlays.
  276. ((org-num--valid-overlay-p overlay)
  277. (let ((next (overlay-start overlay))
  278. (last (and new-overlays (overlay-start (car new-overlays)))))
  279. (cond
  280. ((null org-num--missing-overlay))
  281. ((> org-num--missing-overlay next))
  282. ((or (null last) (> org-num--missing-overlay last))
  283. (setq org-num--missing-overlay nil)
  284. (setq new-overlays (nconc (org-num--number-region last next)
  285. new-overlays)))
  286. ;; If it is already after the last known overlay, reset it:
  287. ;; some previous invalid overlay already triggered the
  288. ;; necessary parsing.
  289. (t
  290. (setq org-num--missing-overlay nil))))
  291. ;; Update OVERLAY's numbering.
  292. (let* ((level (overlay-get overlay 'level))
  293. (skip (overlay-get overlay 'skip))
  294. (numbering (org-num--current-numbering level skip)))
  295. (org-num--refresh-display overlay numbering)
  296. (push overlay new-overlays)))
  297. ;; Invalid overlay. It indicates that the buffer needs to be
  298. ;; parsed again between the two surrounding valid overlays or
  299. ;; buffer boundaries.
  300. (t
  301. ;; Delete all consecutive invalid overlays: we re-create all
  302. ;; overlays between last valid overlay and the next one.
  303. (delete-overlay overlay)
  304. (while (and org-num--overlays
  305. (not (org-num--valid-overlay-p (car org-num--overlays))))
  306. (delete-overlay (pop org-num--overlays)))
  307. ;; Create and register new overlays.
  308. (let ((last (and new-overlays (overlay-start (car new-overlays))))
  309. (next (and org-num--overlays
  310. (overlay-start (car org-num--overlays)))))
  311. (setq new-overlays (nconc (org-num--number-region last next)
  312. new-overlays))))))
  313. ;; If invalid position hasn't been handled yet, it must be located
  314. ;; between last valid overlay and end of the buffer. Parse that
  315. ;; area before returning.
  316. (when org-num--missing-overlay
  317. (let ((last (and new-overlays (overlay-start (car new-overlays)))))
  318. (setq new-overlays (nconc (org-num--number-region last nil)
  319. new-overlays))))
  320. ;; Numbering is now up-to-date. Reset invalid flag. Also return
  321. ;; `org-num--overlays' in a sorted fashion.
  322. (setq org-num--invalid-flag nil)
  323. (setq org-num--overlays (nreverse new-overlays))))
  324. (defun org-num--verify (beg end _)
  325. "Check numbering integrity; update it if necessary.
  326. This function is meant to be used in `after-change-functions'.
  327. See this variable for the meaning of BEG and END."
  328. (setq org-num--missing-overlay nil)
  329. (save-match-data
  330. (org-with-point-at beg
  331. (let ((regexp (org-num--headline-regexp)))
  332. ;; At this point, directly altered overlays between BEG and
  333. ;; END are marked as invalid and will trigger a full update.
  334. ;; However, there are still two cases to handle.
  335. ;;
  336. ;; First, some valid overlays may need to be invalidated, due
  337. ;; to an indirect change. That happens when the skip value --
  338. ;; see `org-num--skip-value' -- of the heading BEG belongs to
  339. ;; is altered, or when deleting the newline character right
  340. ;; before the next headline.
  341. (save-excursion
  342. ;; Bail out if we're before first headline or within
  343. ;; a headline too deep to be numbered.
  344. (when (and (org-with-limited-levels
  345. (ignore-errors (org-back-to-heading t)))
  346. (looking-at regexp))
  347. (pcase (get-char-property-and-overlay (point) 'org-num)
  348. (`(nil)
  349. ;; At a headline, without a numbering overlay: change
  350. ;; just created one. Mark it for parsing.
  351. (setq org-num--missing-overlay (point)))
  352. (`(t . ,o)
  353. ;; Check if skip value changed. Invalidate overlay
  354. ;; accordingly.
  355. (unless (eq (org-num--skip-value) (overlay-get o 'skip))
  356. (org-num--invalidate-overlay o)))
  357. (_ nil))))
  358. ;; Deleting the newline character before a numbering overlay
  359. ;; doesn't invalidate it, even though it could land in the
  360. ;; middle of a line. Be sure to catch this case.
  361. (when (and (= beg end) (not (bolp)))
  362. (pcase (get-char-property-and-overlay (point) 'org-num)
  363. (`(t . ,o) (org-num--invalidate-overlay o))
  364. (_ nil)))
  365. ;; Second, if nothing is marked as invalid, and therefore if
  366. ;; no full update is due so far, changes may still have
  367. ;; created new headlines, at BEG -- which is actually handled
  368. ;; by the previous phase --, or, in case of a multi-line
  369. ;; insertion, at END, or in-between.
  370. (unless (or org-num--invalid-flag
  371. org-num--missing-overlay
  372. (<= end (line-end-position))) ;single line change
  373. (forward-line)
  374. (when (or (re-search-forward regexp end 'move)
  375. ;; Check if change created a headline after END.
  376. (progn (skip-chars-backward "*") (looking-at regexp)))
  377. (setq org-num--missing-overlay (line-beginning-position))))))
  378. ;; Update numbering only if a headline was altered or created.
  379. (when (or org-num--missing-overlay org-num--invalid-flag)
  380. (org-num--update))))
  381. ;;; Public Functions
  382. ;;;###autoload
  383. (defun org-num-default-format (numbering)
  384. "Default numbering display function.
  385. NUMBERING is a list of numbers."
  386. (concat (mapconcat #'number-to-string numbering ".") " "))
  387. ;;;###autoload
  388. (define-minor-mode org-num-mode
  389. "Dynamic numbering of headlines in an Org buffer."
  390. :lighter " o#"
  391. (cond
  392. (org-num-mode
  393. (unless (derived-mode-p 'org-mode)
  394. (user-error "Cannot activate headline numbering outside Org mode"))
  395. (setq org-num--numbering nil)
  396. (setq org-num--overlays (nreverse (org-num--number-region nil nil)))
  397. (add-hook 'after-change-functions #'org-num--verify nil t))
  398. (t
  399. (mapc #'delete-overlay org-num--overlays)
  400. (setq org-num--overlays nil)
  401. (remove-hook 'after-change-functions #'org-num--verify t))))
  402. (provide 'org-num)
  403. ;;; org-num.el ends here