org-footnote.el 37 KB

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