org-footnote.el 37 KB

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