org-footnote.el 37 KB

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