org-footnote.el 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. ;;; org-footnote.el --- Footnote support in Org -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2009-2022 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  6. ;; Keywords: outlines, hypermedia, calendar, wp
  7. ;; Homepage: https://orgmode.org
  8. ;;
  9. ;; This file is part of GNU Emacs.
  10. ;;
  11. ;; GNU Emacs is free software: you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation, either version 3 of the License, or
  14. ;; (at your option) any later version.
  15. ;; GNU Emacs is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;; GNU General Public License for more details.
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  21. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  22. ;;
  23. ;;; Commentary:
  24. ;; This file contains the code dealing with footnotes in Org mode.
  25. ;;; Code:
  26. ;;;; Declarations
  27. (require 'cl-lib)
  28. (require 'org-macs)
  29. (require 'org-compat)
  30. (declare-function org-at-comment-p "org" ())
  31. (declare-function org-at-heading-p "org" (&optional ignored))
  32. (declare-function org-back-over-empty-lines "org" ())
  33. (declare-function org-end-of-meta-data "org" (&optional full))
  34. (declare-function org-edit-footnote-reference "org-src" ())
  35. (declare-function org-element-at-point "org-element" ())
  36. (declare-function org-element-class "org-element" (datum &optional parent))
  37. (declare-function org-element-context "org-element" (&optional element))
  38. (declare-function org-element-lineage "org-element" (blob &optional types with-self))
  39. (declare-function org-element-property "org-element" (property element))
  40. (declare-function org-element-type "org-element" (element))
  41. (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
  42. (declare-function org-fill-paragraph "org" (&optional justify region))
  43. (declare-function org-in-block-p "org" (names))
  44. (declare-function org-in-verbatim-emphasis "org" ())
  45. (declare-function org-inside-LaTeX-fragment-p "org" ())
  46. (declare-function org-inside-latex-macro-p "org" ())
  47. (declare-function org-mark-ring-push "org" (&optional pos buffer))
  48. (declare-function org-show-context "org" (&optional key))
  49. (declare-function outline-next-heading "outline")
  50. (defvar electric-indent-mode)
  51. (defvar org-blank-before-new-entry) ; defined in org.el
  52. (defvar org-link-bracket-re) ; defined in org.el
  53. (defvar org-complex-heading-regexp) ; defined in org.el
  54. (defvar org-odd-levels-only) ; defined in org.el
  55. (defvar org-outline-regexp) ; defined in org.el
  56. (defvar org-outline-regexp-bol) ; defined in org.el
  57. ;;;; Constants
  58. (defconst org-footnote-re
  59. "\\[fn:\\(?:\\(?1:[-_[:word:]]+\\)?\\(:\\)\\|\\(?1:[-_[:word:]]+\\)\\]\\)"
  60. "Regular expression for matching footnotes.
  61. Match group 1 contains footnote's label. It is nil for anonymous
  62. footnotes. Match group 2 is non-nil only when footnote is
  63. inline, i.e., it contains its own definition.")
  64. (defconst org-footnote-definition-re "^\\[fn:\\([-_[:word:]]+\\)\\]"
  65. "Regular expression matching the definition of a footnote.
  66. Match group 1 contains definition's label.")
  67. (defconst org-footnote-forbidden-blocks '("comment" "example" "export" "src")
  68. "Names of blocks where footnotes are not allowed.")
  69. ;;;; Customization
  70. (defgroup org-footnote nil
  71. "Footnotes in Org mode."
  72. :tag "Org Footnote"
  73. :group 'org)
  74. (defcustom org-footnote-section "Footnotes"
  75. "Outline heading containing footnote definitions.
  76. This can be nil, to place footnotes locally at the end of the
  77. current outline node. If can also be the name of a special
  78. outline heading under which footnotes should be put.
  79. This variable defines the place where Org puts the definition
  80. automatically, i.e. when creating the footnote, and when sorting
  81. the notes. However, by hand you may place definitions
  82. *anywhere*.
  83. If this is a string, during export, all subtrees starting with
  84. this heading will be ignored.
  85. If you don't use the customize interface to change this variable,
  86. you will need to run the following command after the change:
  87. `\\[universal-argument] \\[org-element-cache-reset]'"
  88. :group 'org-footnote
  89. :initialize 'custom-initialize-default
  90. :set (lambda (var val)
  91. (set var val)
  92. (when (fboundp 'org-element-cache-reset)
  93. (org-element-cache-reset 'all)))
  94. :type '(choice
  95. (string :tag "Collect footnotes under heading")
  96. (const :tag "Define footnotes locally" nil))
  97. :safe #'string-or-null-p)
  98. (defcustom org-footnote-define-inline nil
  99. "Non-nil means define footnotes inline, at reference location.
  100. When nil, footnotes will be defined in a special section near
  101. the end of the document. When t, the [fn:label:definition] notation
  102. will be used to define the footnote at the reference position."
  103. :group 'org-footnote
  104. :type 'boolean
  105. :safe #'booleanp)
  106. (defcustom org-footnote-auto-label t
  107. "Non-nil means define automatically new labels for footnotes.
  108. Possible values are:
  109. nil Prompt the user for each label.
  110. t Create unique labels of the form [fn:1], [fn:2], etc.
  111. confirm Like t, but let the user edit the created value.
  112. The label can be removed from the minibuffer to create
  113. an anonymous footnote.
  114. random Automatically generate a unique, random label."
  115. :group 'org-footnote
  116. :type '(choice
  117. (const :tag "Prompt for label" nil)
  118. (const :tag "Create automatic [fn:N]" t)
  119. (const :tag "Offer automatic [fn:N] for editing" confirm)
  120. (const :tag "Create a random label" random))
  121. :safe #'symbolp)
  122. (defcustom org-footnote-auto-adjust nil
  123. "Non-nil means automatically adjust footnotes after insert/delete.
  124. When this is t, after each insertion or deletion of a footnote,
  125. simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
  126. If you want to have just sorting or just renumbering, set this variable
  127. to `sort' or `renumber'.
  128. The main values of this variable can be set with in-buffer options:
  129. #+STARTUP: fnadjust
  130. #+STARTUP: nofnadjust"
  131. :group 'org-footnote
  132. :type '(choice
  133. (const :tag "No adjustment" nil)
  134. (const :tag "Renumber" renumber)
  135. (const :tag "Sort" sort)
  136. (const :tag "Renumber and Sort" t))
  137. :safe #'symbolp)
  138. (defcustom org-footnote-fill-after-inline-note-extraction nil
  139. "Non-nil means fill paragraphs after extracting footnotes.
  140. When extracting inline footnotes, the lengths of lines can change a lot.
  141. When this option is set, paragraphs from which an inline footnote has been
  142. extracted will be filled again."
  143. :group 'org-footnote
  144. :type 'boolean
  145. :safe #'booleanp)
  146. ;;;; Predicates
  147. (defun org-footnote-in-valid-context-p ()
  148. "Is point in a context where footnotes are allowed?"
  149. (save-match-data
  150. (not (or (org-at-comment-p)
  151. (org-inside-LaTeX-fragment-p)
  152. ;; Avoid literal example.
  153. (org-in-verbatim-emphasis)
  154. (save-excursion
  155. (beginning-of-line)
  156. (looking-at "[ \t]*:[ \t]+"))
  157. ;; Avoid forbidden blocks.
  158. (org-in-block-p org-footnote-forbidden-blocks)))))
  159. (defun org-footnote-at-reference-p ()
  160. "Non-nil if point is at a footnote reference.
  161. If so, return a list containing its label, beginning and ending
  162. positions, and the definition, when inline."
  163. (let ((reference (org-element-context)))
  164. (when (eq 'footnote-reference (org-element-type reference))
  165. (let ((end (save-excursion
  166. (goto-char (org-element-property :end reference))
  167. (skip-chars-backward " \t")
  168. (point))))
  169. (when (< (point) end)
  170. (list (org-element-property :label reference)
  171. (org-element-property :begin reference)
  172. end
  173. (and (eq 'inline (org-element-property :type reference))
  174. (buffer-substring-no-properties
  175. (org-element-property :contents-begin reference)
  176. (org-element-property :contents-end
  177. reference)))))))))
  178. (defun org-footnote-at-definition-p ()
  179. "Non-nil if point is within a footnote definition.
  180. This matches only pure definitions like [fn:name] at the
  181. beginning of a line. It does not match references like
  182. \[fn:name:definition], where the footnote text is included and
  183. defined locally.
  184. The return value is nil if not at a footnote definition, and
  185. a list with label, start, end and definition of the footnote
  186. otherwise."
  187. (pcase (org-element-lineage (org-element-at-point) '(footnote-definition) t)
  188. (`nil nil)
  189. (definition
  190. (let* ((label (org-element-property :label definition))
  191. (begin (org-element-property :post-affiliated definition))
  192. (end (save-excursion
  193. (goto-char (org-element-property :end definition))
  194. (skip-chars-backward " \r\t\n")
  195. (line-beginning-position 2)))
  196. (contents-begin (org-element-property :contents-begin definition))
  197. (contents-end (org-element-property :contents-end definition))
  198. (contents
  199. (if (not contents-begin) ""
  200. (org-trim
  201. (buffer-substring-no-properties contents-begin
  202. contents-end)))))
  203. (list label begin end contents)))))
  204. ;;;; Internal functions
  205. (defun org-footnote--allow-reference-p ()
  206. "Non-nil when a footnote reference can be inserted at point."
  207. ;; XXX: This is similar to `org-footnote-in-valid-context-p' but
  208. ;; more accurate and usually faster, except in some corner cases.
  209. ;; It may replace it after doing proper benchmarks as it would be
  210. ;; used in fontification.
  211. (unless (bolp)
  212. (let* ((context (org-element-context))
  213. (type (org-element-type context)))
  214. (cond
  215. ;; No footnote reference in attributes.
  216. ((let ((post (org-element-property :post-affiliated context)))
  217. (and post (< (point) post)))
  218. nil)
  219. ;; Paragraphs and blank lines at top of document are fine.
  220. ((memq type '(nil paragraph)))
  221. ;; So are contents of verse blocks.
  222. ((eq type 'verse-block)
  223. (and (>= (point) (org-element-property :contents-begin context))
  224. (< (point) (org-element-property :contents-end context))))
  225. ;; In an headline or inlinetask, point must be either on the
  226. ;; heading itself or on the blank lines below.
  227. ((memq type '(headline inlinetask))
  228. (or (not (org-at-heading-p))
  229. (and (save-excursion
  230. (beginning-of-line)
  231. (and (let ((case-fold-search t))
  232. (not (looking-at-p "\\*+ END[ \t]*$")))
  233. (let ((case-fold-search nil))
  234. (looking-at org-complex-heading-regexp))))
  235. (match-beginning 4)
  236. (>= (point) (match-beginning 4))
  237. (or (not (match-beginning 5))
  238. (< (point) (match-beginning 5))))))
  239. ;; White spaces after an object or blank lines after an element
  240. ;; are OK.
  241. ((>= (point)
  242. (save-excursion (goto-char (org-element-property :end context))
  243. (skip-chars-backward " \r\t\n")
  244. (if (eq (org-element-class context) 'object) (point)
  245. (line-beginning-position 2)))))
  246. ;; At the beginning of a footnote definition, right after the
  247. ;; label, is OK.
  248. ((eq type 'footnote-definition) (looking-at (rx space)))
  249. ;; Other elements are invalid.
  250. ((eq (org-element-class context) 'element) nil)
  251. ;; Just before object is fine.
  252. ((= (point) (org-element-property :begin context)))
  253. ;; Within recursive object too, but not in a link.
  254. ((eq type 'link) nil)
  255. ((eq type 'table-cell)
  256. ;; :contents-begin is not reliable on empty cells, so special
  257. ;; case it.
  258. (<= (save-excursion (skip-chars-backward " \t") (point))
  259. (org-element-property :contents-end context)))
  260. ((let ((cbeg (org-element-property :contents-begin context))
  261. (cend (org-element-property :contents-end context)))
  262. (and cbeg (>= (point) cbeg) (<= (point) cend))))))))
  263. (defun org-footnote--clear-footnote-section ()
  264. "Remove all footnote sections in buffer and create a new one.
  265. New section is created at the end of the buffer. Leave point
  266. within the new section."
  267. (when org-footnote-section
  268. (goto-char (point-min))
  269. (let ((regexp (format "^\\*+ +%s[ \t]*$"
  270. (regexp-quote org-footnote-section))))
  271. (while (re-search-forward regexp nil t)
  272. (delete-region
  273. (match-beginning 0)
  274. (org-end-of-subtree t t))))
  275. (goto-char (point-max))
  276. ;; Clean-up blank lines at the end of the buffer.
  277. (skip-chars-backward " \r\t\n")
  278. (unless (bobp)
  279. (forward-line)
  280. (when (eolp) (insert "\n")))
  281. (delete-region (point) (point-max))
  282. (when (and (cdr (assq 'heading org-blank-before-new-entry))
  283. (zerop (save-excursion (org-back-over-empty-lines))))
  284. (insert "\n"))
  285. (insert "* " org-footnote-section "\n")))
  286. (defun org-footnote--set-label (label)
  287. "Set label of footnote at point to string LABEL.
  288. Assume point is at the beginning of the reference or definition
  289. to rename."
  290. (forward-char 4)
  291. (cond ((eq (char-after) ?:) (insert label))
  292. ((looking-at "\\([-_[:word:]]+\\)") (replace-match label nil nil nil 1))
  293. (t nil)))
  294. (defun org-footnote--collect-references (&optional anonymous)
  295. "Collect all labeled footnote references in current buffer.
  296. Return an alist where associations follow the pattern
  297. (LABEL MARKER TOP-LEVEL SIZE)
  298. with
  299. LABEL the label of the of the definition,
  300. MARKER a marker pointing to its beginning,
  301. TOP-LEVEL a boolean, nil when the footnote is contained within
  302. another one,
  303. SIZE the length of the inline definition, in characters,
  304. or nil for non-inline references.
  305. When optional ANONYMOUS is non-nil, also collect anonymous
  306. references. In such cases, LABEL is nil.
  307. References are sorted according to a deep-reading order."
  308. (org-with-wide-buffer
  309. (goto-char (point-min))
  310. (let ((regexp (if anonymous org-footnote-re "\\[fn:[-_[:word:]]+[]:]"))
  311. references nested)
  312. (save-excursion
  313. (while (re-search-forward regexp nil t)
  314. ;; Ignore definitions.
  315. (unless (and (eq (char-before) ?\])
  316. (= (line-beginning-position) (match-beginning 0)))
  317. ;; Ensure point is within the reference before parsing it.
  318. (backward-char)
  319. (let ((object (org-element-context)))
  320. (when (eq (org-element-type object) 'footnote-reference)
  321. (let* ((label (org-element-property :label object))
  322. (begin (org-element-property :begin object))
  323. (size
  324. (and (eq (org-element-property :type object) 'inline)
  325. (- (org-element-property :contents-end object)
  326. (org-element-property :contents-begin object)))))
  327. (let ((d (org-element-lineage object '(footnote-definition))))
  328. (push (list label (copy-marker begin) (not d) size)
  329. references)
  330. (when d
  331. ;; Nested references are stored in alist NESTED.
  332. ;; Associations there follow the pattern
  333. ;;
  334. ;; (DEFINITION-LABEL . REFERENCES)
  335. (let* ((def-label (org-element-property :label d))
  336. (labels (assoc def-label nested)))
  337. (if labels (push label (cdr labels))
  338. (push (list def-label label) nested)))))))))))
  339. ;; Sort the list of references. Nested footnotes have priority
  340. ;; over top-level ones.
  341. (letrec ((ordered nil)
  342. (add-reference
  343. (lambda (ref allow-nested)
  344. (when (or allow-nested (nth 2 ref))
  345. (push ref ordered)
  346. (dolist (r (mapcar (lambda (l) (assoc l references))
  347. (reverse
  348. (cdr (assoc (nth 0 ref) nested)))))
  349. (funcall add-reference r t))))))
  350. (dolist (r (reverse references) (nreverse ordered))
  351. (funcall add-reference r nil))))))
  352. (defun org-footnote--collect-definitions (&optional delete)
  353. "Collect all footnote definitions in current buffer.
  354. Return an alist where associations follow the pattern
  355. (LABEL . DEFINITION)
  356. with LABEL and DEFINITION being, respectively, the label and the
  357. definition of the footnote, as strings.
  358. When optional argument DELETE is non-nil, delete the definition
  359. while collecting them."
  360. (org-with-wide-buffer
  361. (goto-char (point-min))
  362. (let (definitions seen)
  363. (while (re-search-forward org-footnote-definition-re nil t)
  364. (backward-char)
  365. (let ((element (org-element-at-point)))
  366. (let ((label (org-element-property :label element)))
  367. (when (and (eq (org-element-type element) 'footnote-definition)
  368. (not (member label seen)))
  369. (push label seen)
  370. (let* ((beg (progn
  371. (goto-char (org-element-property :begin element))
  372. (skip-chars-backward " \r\t\n")
  373. (if (bobp) (point) (line-beginning-position 2))))
  374. (end (progn
  375. (goto-char (org-element-property :end element))
  376. (skip-chars-backward " \r\t\n")
  377. (line-beginning-position 2)))
  378. (def (org-trim (buffer-substring-no-properties beg end))))
  379. (push (cons label def) definitions)
  380. (when delete (delete-region beg end)))))))
  381. definitions)))
  382. (defun org-footnote--goto-local-insertion-point ()
  383. "Find insertion point for footnote, just before next outline heading.
  384. Assume insertion point is within currently accessible part of the buffer."
  385. (org-with-limited-levels (outline-next-heading))
  386. (skip-chars-backward " \t\n")
  387. (unless (bobp) (forward-line))
  388. (unless (bolp) (insert "\n")))
  389. ;;;; Navigation
  390. (defun org-footnote-get-next-reference (&optional label backward limit)
  391. "Return complete reference of the next footnote.
  392. If LABEL is provided, get the next reference of that footnote. If
  393. BACKWARD is non-nil, find previous reference instead. LIMIT is
  394. the buffer position bounding the search.
  395. Return value is a list like those provided by `org-footnote-at-reference-p'.
  396. If no footnote is found, return nil."
  397. (let ((label-regexp (if label (format "\\[fn:%s[]:]" label) org-footnote-re)))
  398. (catch :exit
  399. (save-excursion
  400. (while (funcall (if backward #'re-search-backward #'re-search-forward)
  401. label-regexp limit t)
  402. (unless backward (backward-char))
  403. (pcase (org-footnote-at-reference-p)
  404. (`nil nil)
  405. (reference (throw :exit reference))))))))
  406. (defun org-footnote-next-reference-or-definition (limit)
  407. "Move point to next footnote reference or definition.
  408. LIMIT is the buffer position bounding the search.
  409. Return value is a list like those provided by
  410. `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
  411. If no footnote is found, return nil.
  412. This function is meant to be used for fontification only."
  413. (let ((origin (point)))
  414. (catch 'exit
  415. (while t
  416. (unless (re-search-forward org-footnote-re limit t)
  417. (goto-char origin)
  418. (throw 'exit nil))
  419. ;; Beware: with non-inline footnotes point will be just after
  420. ;; the closing square bracket.
  421. (backward-char)
  422. (cond
  423. ((and (/= (match-beginning 0) (line-beginning-position))
  424. (let* ((beg (match-beginning 0))
  425. (label (match-string-no-properties 1))
  426. ;; Inline footnotes don't end at (match-end 0)
  427. ;; as `org-footnote-re' stops just after the
  428. ;; second colon. Find the real ending with
  429. ;; `scan-sexps', so Org doesn't get fooled by
  430. ;; unrelated closing square brackets.
  431. (end (ignore-errors (scan-sexps beg 1))))
  432. (and end
  433. ;; Verify match isn't a part of a link.
  434. (not (save-excursion
  435. (goto-char beg)
  436. (let ((linkp
  437. (save-match-data
  438. (org-in-regexp org-link-bracket-re))))
  439. (and linkp (< (point) (cdr linkp))))))
  440. ;; Verify point doesn't belong to a LaTeX macro.
  441. (not (org-inside-latex-macro-p))
  442. (throw 'exit
  443. (list label beg end
  444. ;; Definition: ensure this is an
  445. ;; inline footnote first.
  446. (and (match-end 2)
  447. (org-trim
  448. (buffer-substring-no-properties
  449. (match-end 0) (1- end))))))))))
  450. ;; Definition: also grab the last square bracket, matched in
  451. ;; `org-footnote-re' for non-inline footnotes.
  452. ((and (save-excursion
  453. (beginning-of-line)
  454. (save-match-data (org-footnote-in-valid-context-p)))
  455. (save-excursion
  456. (end-of-line)
  457. ;; Footnotes definitions are separated by new
  458. ;; headlines, another footnote definition or 2 blank
  459. ;; lines.
  460. (let ((end (match-end 0))
  461. (lim (save-excursion
  462. (re-search-backward
  463. (concat org-outline-regexp-bol
  464. "\\|^\\([ \t]*\n\\)\\{2,\\}")
  465. nil t))))
  466. (and (re-search-backward org-footnote-definition-re lim t)
  467. (throw 'exit
  468. (list nil
  469. (match-beginning 0)
  470. (if (eq (char-before end) ?\]) end
  471. (1+ end)))))))))
  472. (t nil))))))
  473. (defun org-footnote-goto-definition (label &optional location)
  474. "Move point to the definition of the footnote LABEL.
  475. LOCATION, when non-nil specifies the buffer position of the
  476. definition.
  477. Throw an error if there is no definition or if it cannot be
  478. reached from current narrowed part of buffer. Return a non-nil
  479. value if point was successfully moved."
  480. (interactive "sLabel: ")
  481. (let* ((label (org-footnote-normalize-label label))
  482. (def-start (or location (nth 1 (org-footnote-get-definition label)))))
  483. (cond
  484. ((not def-start)
  485. (user-error "Cannot find definition of footnote %s" label))
  486. ((or (> def-start (point-max)) (< def-start (point-min)))
  487. (user-error "Definition is outside narrowed part of buffer")))
  488. (org-mark-ring-push)
  489. (goto-char def-start)
  490. (looking-at (format "\\[fn:%s[]:]" (regexp-quote label)))
  491. (goto-char (match-end 0))
  492. (org-show-context 'link-search)
  493. (when (derived-mode-p 'org-mode)
  494. (message "%s" (substitute-command-keys
  495. "Edit definition and go back with \
  496. `\\[org-mark-ring-goto]' or, if unique, with `\\[org-ctrl-c-ctrl-c]'.")))
  497. t))
  498. (defun org-footnote-goto-previous-reference (label)
  499. "Find the first closest (to point) reference of footnote with label LABEL."
  500. (interactive "sLabel: ")
  501. (let* ((label (org-footnote-normalize-label label))
  502. (reference
  503. (save-excursion
  504. (or (org-footnote-get-next-reference label t)
  505. (org-footnote-get-next-reference label)
  506. (and (buffer-narrowed-p)
  507. (org-with-wide-buffer
  508. (or (org-footnote-get-next-reference label t)
  509. (org-footnote-get-next-reference label)))))))
  510. (start (nth 1 reference)))
  511. (cond ((not reference)
  512. (user-error "Cannot find reference of footnote %S" label))
  513. ((or (> start (point-max)) (< start (point-min)))
  514. (user-error "Reference is outside narrowed part of buffer")))
  515. (org-mark-ring-push)
  516. (goto-char start)
  517. (org-show-context 'link-search)))
  518. ;;;; Getters
  519. (defun org-footnote-normalize-label (label)
  520. "Return LABEL without \"fn:\" prefix.
  521. If LABEL is the empty string or constituted of white spaces only,
  522. return nil instead."
  523. (pcase (org-trim label)
  524. ("" nil)
  525. ((pred (string-prefix-p "fn:")) (substring label 3))
  526. (_ label)))
  527. (defun org-footnote-get-definition (label)
  528. "Return label, boundaries and definition of the footnote LABEL."
  529. (let* ((label (regexp-quote (org-footnote-normalize-label label)))
  530. (re (format "^\\[fn:%s\\]\\|.\\[fn:%s:" label label)))
  531. (org-with-wide-buffer
  532. (goto-char (point-min))
  533. (catch 'found
  534. (while (re-search-forward re nil t)
  535. (let* ((datum (progn (backward-char) (org-element-context)))
  536. (type (org-element-type datum)))
  537. (when (memq type '(footnote-definition footnote-reference))
  538. (throw 'found
  539. (list
  540. label
  541. (org-element-property :begin datum)
  542. (org-element-property :end datum)
  543. (let ((cbeg (org-element-property :contents-begin datum)))
  544. (if (not cbeg) ""
  545. (replace-regexp-in-string
  546. "[ \t\n]*\\'"
  547. ""
  548. (buffer-substring-no-properties
  549. cbeg
  550. (org-element-property :contents-end datum))))))))))
  551. nil))))
  552. (defun org-footnote-all-labels ()
  553. "List all defined footnote labels used throughout the buffer.
  554. This function ignores narrowing, if any."
  555. (org-with-wide-buffer
  556. (goto-char (point-min))
  557. (let (all)
  558. (while (re-search-forward org-footnote-re nil t)
  559. (backward-char)
  560. (let ((context (org-element-context)))
  561. (when (memq (org-element-type context)
  562. '(footnote-definition footnote-reference))
  563. (let ((label (org-element-property :label context)))
  564. (when label (cl-pushnew label all :test #'equal))))))
  565. all)))
  566. (defun org-footnote-unique-label (&optional current)
  567. "Return a new unique footnote label.
  568. The function returns the first numeric label currently unused.
  569. Optional argument CURRENT is the list of labels active in the
  570. buffer."
  571. (let ((current (or current (org-footnote-all-labels))))
  572. (let ((count 1))
  573. (while (member (number-to-string count) current)
  574. (cl-incf count))
  575. (number-to-string count))))
  576. ;;;; Adding, Deleting Footnotes
  577. (defun org-footnote-new ()
  578. "Insert a new footnote.
  579. This command prompts for a label. If this is a label referencing an
  580. existing label, only insert the label. If the footnote label is empty
  581. or new, let the user edit the definition of the footnote."
  582. (interactive)
  583. (unless (org-footnote--allow-reference-p)
  584. (user-error "Cannot insert a footnote here"))
  585. (let* ((all (org-footnote-all-labels))
  586. (label
  587. (if (eq org-footnote-auto-label 'random)
  588. (format "%x" (abs (random)))
  589. (org-footnote-normalize-label
  590. (let ((propose (org-footnote-unique-label all)))
  591. (if (eq org-footnote-auto-label t) propose
  592. (completing-read
  593. "Label (leave empty for anonymous): "
  594. (mapcar #'list all) nil nil
  595. (and (eq org-footnote-auto-label 'confirm) propose))))))))
  596. (cond ((not label)
  597. (insert "[fn::]")
  598. (backward-char 1))
  599. ((member label all)
  600. (insert "[fn:" label "]")
  601. (message "New reference to existing note"))
  602. (org-footnote-define-inline
  603. (insert "[fn:" label ":]")
  604. (backward-char 1)
  605. (org-footnote-auto-adjust-maybe))
  606. (t
  607. (insert "[fn:" label "]")
  608. (let ((p (org-footnote-create-definition label)))
  609. ;; `org-footnote-goto-definition' needs to be called
  610. ;; after `org-footnote-auto-adjust-maybe'. Otherwise
  611. ;; both label and location of the definition are lost.
  612. ;; On the contrary, it needs to be called before
  613. ;; `org-edit-footnote-reference' so that the remote
  614. ;; editing buffer can display the correct label.
  615. (if (ignore-errors (org-footnote-goto-definition label p))
  616. (org-footnote-auto-adjust-maybe)
  617. ;; Definition was created outside current scope: edit
  618. ;; it remotely.
  619. (org-footnote-auto-adjust-maybe)
  620. (org-edit-footnote-reference)))))))
  621. (defun org-footnote-create-definition (label)
  622. "Start the definition of a footnote with label LABEL.
  623. Return buffer position at the beginning of the definition. This
  624. function doesn't move point."
  625. (let ((label (org-footnote-normalize-label label))
  626. electric-indent-mode) ; Prevent wrong indentation.
  627. (org-preserve-local-variables
  628. (org-with-wide-buffer
  629. (cond
  630. ((not org-footnote-section) (org-footnote--goto-local-insertion-point))
  631. ((save-excursion
  632. (goto-char (point-min))
  633. (re-search-forward
  634. (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section) "[ \t]*$")
  635. nil t))
  636. (goto-char (match-end 0))
  637. (org-end-of-meta-data t)
  638. (unless (bolp) (insert "\n")))
  639. (t (org-footnote--clear-footnote-section)))
  640. (when (zerop (org-back-over-empty-lines)) (insert "\n"))
  641. (insert "[fn:" label "] \n")
  642. (line-beginning-position 0)))))
  643. (defun org-footnote-delete-references (label)
  644. "Delete every reference to footnote LABEL.
  645. Return the number of footnotes removed."
  646. (save-excursion
  647. (goto-char (point-min))
  648. (let (ref (nref 0))
  649. (while (setq ref (org-footnote-get-next-reference label))
  650. (goto-char (nth 1 ref))
  651. (delete-region (nth 1 ref) (nth 2 ref))
  652. (cl-incf nref))
  653. nref)))
  654. (defun org-footnote-delete-definitions (label)
  655. "Delete every definition of the footnote LABEL.
  656. Return the number of footnotes removed."
  657. (save-excursion
  658. (goto-char (point-min))
  659. (let ((def-re (format "^\\[fn:%s\\]" (regexp-quote label)))
  660. (ndef 0))
  661. (while (re-search-forward def-re nil t)
  662. (pcase (org-footnote-at-definition-p)
  663. (`(,_ ,start ,end ,_)
  664. ;; Remove the footnote, and all blank lines before it.
  665. (delete-region (progn
  666. (goto-char start)
  667. (skip-chars-backward " \r\t\n")
  668. (if (bobp) (point) (line-beginning-position 2)))
  669. (progn
  670. (goto-char end)
  671. (skip-chars-backward " \r\t\n")
  672. (if (bobp) (point) (line-beginning-position 2))))
  673. (cl-incf ndef))))
  674. ndef)))
  675. (defun org-footnote-delete (&optional label)
  676. "Delete the footnote at point.
  677. This will remove the definition (even multiple definitions if they exist)
  678. and all references of a footnote label.
  679. If LABEL is non-nil, delete that footnote instead."
  680. (catch 'done
  681. (org-preserve-local-variables
  682. (let* ((nref 0) (ndef 0) x
  683. ;; 1. Determine LABEL of footnote at point.
  684. (label (cond
  685. ;; LABEL is provided as argument.
  686. (label)
  687. ;; Footnote reference at point. If the footnote is
  688. ;; anonymous, delete it and exit instead.
  689. ((setq x (org-footnote-at-reference-p))
  690. (or (car x)
  691. (progn
  692. (delete-region (nth 1 x) (nth 2 x))
  693. (message "Anonymous footnote removed")
  694. (throw 'done t))))
  695. ;; Footnote definition at point.
  696. ((setq x (org-footnote-at-definition-p))
  697. (car x))
  698. (t (error "Don't know which footnote to remove")))))
  699. ;; 2. Now that LABEL is non-nil, find every reference and every
  700. ;; definition, and delete them.
  701. (setq nref (org-footnote-delete-references label)
  702. ndef (org-footnote-delete-definitions label))
  703. ;; 3. Verify consistency of footnotes and notify user.
  704. (org-footnote-auto-adjust-maybe)
  705. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  706. ndef nref label)))))
  707. ;;;; Sorting, Renumbering, Normalizing
  708. (defun org-footnote-renumber-fn:N ()
  709. "Order numbered footnotes into a sequence in the document."
  710. (interactive)
  711. (let* ((c 0)
  712. (references (cl-remove-if-not
  713. (lambda (r) (string-match-p "\\`[0-9]+\\'" (car r)))
  714. (org-footnote--collect-references)))
  715. (alist (mapcar (lambda (l) (cons l (number-to-string (cl-incf c))))
  716. (delete-dups (mapcar #'car references)))))
  717. (org-with-wide-buffer
  718. ;; Re-number references.
  719. (dolist (ref references)
  720. (goto-char (nth 1 ref))
  721. (org-footnote--set-label (cdr (assoc (nth 0 ref) alist))))
  722. ;; Re-number definitions.
  723. (goto-char (point-min))
  724. (while (re-search-forward "^\\[fn:\\([0-9]+\\)\\]" nil t)
  725. (replace-match (or (cdr (assoc (match-string 1) alist))
  726. ;; Un-referenced definitions get higher
  727. ;; numbers.
  728. (number-to-string (cl-incf c)))
  729. nil nil nil 1)))))
  730. (defun org-footnote-sort ()
  731. "Rearrange footnote definitions in the current buffer.
  732. Sort footnote definitions so they match order of footnote
  733. references. Also relocate definitions at the end of their
  734. relative section or within a single footnote section, according
  735. to `org-footnote-section'. Inline definitions are ignored."
  736. (let ((references (org-footnote--collect-references)))
  737. (org-preserve-local-variables
  738. (let ((definitions (org-footnote--collect-definitions 'delete)))
  739. (org-with-wide-buffer
  740. (org-footnote--clear-footnote-section)
  741. ;; Insert footnote definitions at the appropriate location,
  742. ;; separated by a blank line. Each definition is inserted
  743. ;; only once throughout the buffer.
  744. (let (inserted)
  745. (dolist (cell references)
  746. (let ((label (car cell))
  747. (nested (not (nth 2 cell)))
  748. (inline (nth 3 cell)))
  749. (unless (or (member label inserted) inline)
  750. (push label inserted)
  751. (unless (or org-footnote-section nested)
  752. ;; If `org-footnote-section' is non-nil, or
  753. ;; reference is nested, point is already at the
  754. ;; correct position. Otherwise, move at the
  755. ;; appropriate location within the section
  756. ;; containing the reference.
  757. (goto-char (nth 1 cell))
  758. (org-footnote--goto-local-insertion-point))
  759. (insert "\n"
  760. (or (cdr (assoc label definitions))
  761. (format "[fn:%s] DEFINITION NOT FOUND." label))
  762. "\n"))))
  763. ;; Insert un-referenced footnote definitions at the end.
  764. (pcase-dolist (`(,label . ,definition) definitions)
  765. (unless (member label inserted)
  766. (insert "\n" definition "\n")))))))))
  767. (defun org-footnote-normalize ()
  768. "Turn every footnote in buffer into a numbered one."
  769. (interactive)
  770. (org-preserve-local-variables
  771. (let ((n 0)
  772. (translations nil)
  773. (definitions nil)
  774. (references (org-footnote--collect-references 'anonymous)))
  775. (org-with-wide-buffer
  776. ;; Update label for reference. We need to do this before
  777. ;; clearing definitions in order to rename nested footnotes
  778. ;; before they are deleted.
  779. (dolist (cell references)
  780. (let* ((label (car cell))
  781. (anonymous (not label))
  782. (new
  783. (cond
  784. ;; In order to differentiate anonymous references
  785. ;; from regular ones, set their labels to integers,
  786. ;; not strings.
  787. (anonymous (setcar cell (cl-incf n)))
  788. ((cdr (assoc label translations)))
  789. (t (let ((l (number-to-string (cl-incf n))))
  790. (push (cons label l) translations)
  791. l)))))
  792. (goto-char (nth 1 cell)) ; Move to reference's start.
  793. (org-footnote--set-label
  794. (if anonymous (number-to-string new) new))
  795. (let ((size (nth 3 cell)))
  796. ;; Transform inline footnotes into regular references and
  797. ;; retain their definition for later insertion as
  798. ;; a regular footnote definition.
  799. (when size
  800. (let ((def (concat
  801. (format "[fn:%s] " new)
  802. (org-trim
  803. (substring
  804. (delete-and-extract-region
  805. (point) (+ (point) size 1))
  806. 1)))))
  807. (push (cons (if anonymous new label) def) definitions)
  808. (when org-footnote-fill-after-inline-note-extraction
  809. (org-fill-paragraph)))))))
  810. ;; Collect definitions. Update labels according to ALIST.
  811. (let ((definitions
  812. (nconc definitions
  813. (org-footnote--collect-definitions 'delete)))
  814. (inserted))
  815. (org-footnote--clear-footnote-section)
  816. (dolist (cell references)
  817. (let* ((label (car cell))
  818. (anonymous (integerp label))
  819. (pos (nth 1 cell)))
  820. ;; Move to appropriate location, if required. When there
  821. ;; is a footnote section or reference is nested, point is
  822. ;; already at the expected location.
  823. (unless (or org-footnote-section (not (nth 2 cell)))
  824. (goto-char pos)
  825. (org-footnote--goto-local-insertion-point))
  826. ;; Insert new definition once label is updated.
  827. (unless (member label inserted)
  828. (push label inserted)
  829. (let ((stored (cdr (assoc label definitions)))
  830. ;; Anonymous footnotes' label is already
  831. ;; up-to-date.
  832. (new (if anonymous label
  833. (cdr (assoc label translations)))))
  834. (insert "\n"
  835. (cond
  836. ((not stored)
  837. (format "[fn:%s] DEFINITION NOT FOUND." new))
  838. (anonymous stored)
  839. (t
  840. (replace-regexp-in-string
  841. "\\`\\[fn:\\(.*?\\)\\]" new stored nil nil 1)))
  842. "\n")))))
  843. ;; Insert un-referenced footnote definitions at the end.
  844. (pcase-dolist (`(,label . ,definition) definitions)
  845. (unless (member label inserted)
  846. (insert "\n"
  847. (replace-regexp-in-string org-footnote-definition-re
  848. (format "[fn:%d]" (cl-incf n))
  849. definition)
  850. "\n"))))))))
  851. (defun org-footnote-auto-adjust-maybe ()
  852. "Renumber and/or sort footnotes according to user settings."
  853. (when (memq org-footnote-auto-adjust '(t renumber))
  854. (org-footnote-renumber-fn:N))
  855. (when (memq org-footnote-auto-adjust '(t sort))
  856. (let ((label (car (org-footnote-at-definition-p))))
  857. (org-footnote-sort)
  858. (when label
  859. (goto-char (point-min))
  860. (and (re-search-forward (format "^\\[fn:%s\\]" (regexp-quote label))
  861. nil t)
  862. (progn (insert " ")
  863. (just-one-space)))))))
  864. ;;;; End-user interface
  865. ;;;###autoload
  866. (defun org-footnote-action (&optional special)
  867. "Do the right thing for footnotes.
  868. When at a footnote reference, jump to the definition.
  869. When at a definition, jump to the references if they exist, offer
  870. to create them otherwise.
  871. When neither at definition or reference, create a new footnote,
  872. interactively if possible.
  873. With prefix arg SPECIAL, or when no footnote can be created,
  874. offer additional commands in a menu."
  875. (interactive "P")
  876. (let* ((context (and (not special) (org-element-context)))
  877. (type (org-element-type context)))
  878. (cond
  879. ;; On white space after element, insert a new footnote.
  880. ((and context
  881. (> (point)
  882. (save-excursion
  883. (goto-char (org-element-property :end context))
  884. (skip-chars-backward " \t")
  885. (point))))
  886. (org-footnote-new))
  887. ((eq type 'footnote-reference)
  888. (let ((label (org-element-property :label context)))
  889. (cond
  890. ;; Anonymous footnote: move point at the beginning of its
  891. ;; definition.
  892. ((not label)
  893. (goto-char (org-element-property :contents-begin context)))
  894. ;; Check if a definition exists: then move to it.
  895. ((let ((p (nth 1 (org-footnote-get-definition label))))
  896. (when p (org-footnote-goto-definition label p))))
  897. ;; No definition exists: offer to create it.
  898. ((yes-or-no-p (format "No definition for %s. Create one? " label))
  899. (let ((p (org-footnote-create-definition label)))
  900. (or (ignore-errors (org-footnote-goto-definition label p))
  901. ;; Since definition was created outside current scope,
  902. ;; edit it remotely.
  903. (org-edit-footnote-reference)))))))
  904. ((eq type 'footnote-definition)
  905. (org-footnote-goto-previous-reference
  906. (org-element-property :label context)))
  907. ((or special (not (org-footnote--allow-reference-p)))
  908. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | [n]ormalize | \
  909. \[d]elete")
  910. (pcase (read-char-exclusive)
  911. (?s (org-footnote-sort))
  912. (?r (org-footnote-renumber-fn:N))
  913. (?S (org-footnote-renumber-fn:N)
  914. (org-footnote-sort))
  915. (?n (org-footnote-normalize))
  916. (?d (org-footnote-delete))
  917. (char (error "No such footnote command %c" char))))
  918. (t (org-footnote-new)))))
  919. (provide 'org-footnote)
  920. ;; Local variables:
  921. ;; generated-autoload-file: "org-loaddefs.el"
  922. ;; End:
  923. ;;; org-footnote.el ends here