org-footnote.el 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. ;;; org-footnote.el --- Footnote support in Org -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2009-2018 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-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. Leave point
  276. within the new section."
  277. (when org-footnote-section
  278. (goto-char (point-min))
  279. (let ((regexp (format "^\\*+ +%s[ \t]*$"
  280. (regexp-quote org-footnote-section))))
  281. (while (re-search-forward regexp nil t)
  282. (delete-region
  283. (match-beginning 0)
  284. (org-end-of-subtree t t))))
  285. (goto-char (point-max))
  286. ;; Clean-up blank lines at the end of the buffer.
  287. (skip-chars-backward " \r\t\n")
  288. (unless (bobp)
  289. (forward-line)
  290. (when (eolp) (insert "\n")))
  291. (delete-region (point) (point-max))
  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-chars-backward " \t\n")
  397. (unless (bobp) (forward-line))
  398. (unless (bolp) (insert "\n")))
  399. ;;;; Navigation
  400. (defun org-footnote-get-next-reference (&optional label backward limit)
  401. "Return complete reference of the next footnote.
  402. If LABEL is provided, get the next reference of that footnote. If
  403. BACKWARD is non-nil, find previous reference instead. LIMIT is
  404. the buffer position bounding the search.
  405. Return value is a list like those provided by `org-footnote-at-reference-p'.
  406. If no footnote is found, return nil."
  407. (save-excursion
  408. (let* ((label-fmt (if label (format "\\[fn:%s[]:]" label) org-footnote-re)))
  409. (catch 'exit
  410. (while t
  411. (unless (funcall (if backward #'re-search-backward #'re-search-forward)
  412. label-fmt limit t)
  413. (throw 'exit nil))
  414. (unless backward (backward-char))
  415. (let ((ref (org-footnote-at-reference-p)))
  416. (when ref (throw 'exit ref))))))))
  417. (defun org-footnote-next-reference-or-definition (limit)
  418. "Move point to next footnote reference or definition.
  419. LIMIT is the buffer position bounding the search.
  420. Return value is a list like those provided by
  421. `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
  422. If no footnote is found, return nil."
  423. (let* (ref (origin (point)))
  424. (catch 'exit
  425. (while t
  426. (unless (re-search-forward org-footnote-re limit t)
  427. (goto-char origin)
  428. (throw 'exit nil))
  429. ;; Beware: with non-inline footnotes point will be just after
  430. ;; the closing square bracket.
  431. (backward-char)
  432. (cond
  433. ((setq ref (org-footnote-at-reference-p))
  434. (throw 'exit ref))
  435. ;; Definition: also grab the last square bracket, matched in
  436. ;; `org-footnote-re' for non-inline footnotes.
  437. ((save-match-data (org-footnote-at-definition-p))
  438. (let ((end (match-end 0)))
  439. (throw 'exit
  440. (list nil (match-beginning 0)
  441. (if (eq (char-before end) ?\]) end (1+ end)))))))))))
  442. (defun org-footnote-goto-definition (label &optional location)
  443. "Move point to the definition of the footnote LABEL.
  444. LOCATION, when non-nil specifies the buffer position of the
  445. definition.
  446. Throw an error if there is no definition or if it cannot be
  447. reached from current narrowed part of buffer. Return a non-nil
  448. value if point was successfully moved."
  449. (interactive "sLabel: ")
  450. (let* ((label (org-footnote-normalize-label label))
  451. (def-start (or location (nth 1 (org-footnote-get-definition label)))))
  452. (cond
  453. ((not def-start)
  454. (user-error "Cannot find definition of footnote %s" label))
  455. ((or (> def-start (point-max)) (< def-start (point-min)))
  456. (user-error "Definition is outside narrowed part of buffer")))
  457. (org-mark-ring-push)
  458. (goto-char def-start)
  459. (looking-at (format "\\[fn:%s[]:] ?" (regexp-quote label)))
  460. (goto-char (match-end 0))
  461. (org-show-context 'link-search)
  462. (when (derived-mode-p 'org-mode)
  463. (message "%s" (substitute-command-keys
  464. "Edit definition and go back with \
  465. `\\[org-mark-ring-goto]' or, if unique, with `\\[org-ctrl-c-ctrl-c]'.")))
  466. t))
  467. (defun org-footnote-goto-previous-reference (label)
  468. "Find the first closest (to point) reference of footnote with label LABEL."
  469. (interactive "sLabel: ")
  470. (org-mark-ring-push)
  471. (let ((label (org-footnote-normalize-label label))
  472. ref)
  473. (save-excursion
  474. (setq ref (or (org-footnote-get-next-reference label t)
  475. (org-footnote-get-next-reference label)
  476. (save-restriction
  477. (widen)
  478. (or
  479. (org-footnote-get-next-reference label t)
  480. (org-footnote-get-next-reference label))))))
  481. (if (not ref)
  482. (error "Cannot find reference of footnote %s" label)
  483. (goto-char (nth 1 ref))
  484. (org-show-context 'link-search))))
  485. ;;;; Getters
  486. (defun org-footnote-normalize-label (label)
  487. "Return LABEL without \"fn:\" prefix.
  488. If LABEL is the empty string or constituted of white spaces only,
  489. return nil instead."
  490. (pcase (org-trim label)
  491. ("" nil)
  492. ((pred (string-prefix-p "fn:")) (substring label 3))
  493. (_ label)))
  494. (defun org-footnote-get-definition (label)
  495. "Return label, boundaries and definition of the footnote LABEL."
  496. (let* ((label (regexp-quote (org-footnote-normalize-label label)))
  497. (re (format "^\\[fn:%s\\]\\|.\\[fn:%s:" label label)))
  498. (org-with-wide-buffer
  499. (goto-char (point-min))
  500. (catch 'found
  501. (while (re-search-forward re nil t)
  502. (let* ((datum (progn (backward-char) (org-element-context)))
  503. (type (org-element-type datum)))
  504. (when (memq type '(footnote-definition footnote-reference))
  505. (throw 'found
  506. (list
  507. label
  508. (org-element-property :begin datum)
  509. (org-element-property :end datum)
  510. (let ((cbeg (org-element-property :contents-begin datum)))
  511. (if (not cbeg) ""
  512. (replace-regexp-in-string
  513. "[ \t\n]*\\'"
  514. ""
  515. (buffer-substring-no-properties
  516. cbeg
  517. (org-element-property :contents-end datum))))))))))
  518. nil))))
  519. (defun org-footnote-all-labels ()
  520. "List all defined footnote labels used throughout the buffer.
  521. This function ignores narrowing, if any."
  522. (org-with-wide-buffer
  523. (goto-char (point-min))
  524. (let (all)
  525. (while (re-search-forward org-footnote-re nil t)
  526. (backward-char)
  527. (let ((context (org-element-context)))
  528. (when (memq (org-element-type context)
  529. '(footnote-definition footnote-reference))
  530. (let ((label (org-element-property :label context)))
  531. (when label (cl-pushnew label all :test #'equal))))))
  532. all)))
  533. (defun org-footnote-unique-label (&optional current)
  534. "Return a new unique footnote label.
  535. The function returns the first numeric label currently unused.
  536. Optional argument CURRENT is the list of labels active in the
  537. buffer."
  538. (let ((current (or current (org-footnote-all-labels))))
  539. (let ((count 1))
  540. (while (member (number-to-string count) current)
  541. (cl-incf count))
  542. (number-to-string count))))
  543. ;;;; Adding, Deleting Footnotes
  544. (defun org-footnote-new ()
  545. "Insert a new footnote.
  546. This command prompts for a label. If this is a label referencing an
  547. existing label, only insert the label. If the footnote label is empty
  548. or new, let the user edit the definition of the footnote."
  549. (interactive)
  550. (unless (org-footnote--allow-reference-p)
  551. (user-error "Cannot insert a footnote here"))
  552. (let* ((all (org-footnote-all-labels))
  553. (label
  554. (if (eq org-footnote-auto-label 'random)
  555. (format "%x" (random most-positive-fixnum))
  556. (org-footnote-normalize-label
  557. (let ((propose (org-footnote-unique-label all)))
  558. (if (eq org-footnote-auto-label t) propose
  559. (completing-read
  560. "Label (leave empty for anonymous): "
  561. (mapcar #'list all) nil nil
  562. (and (eq org-footnote-auto-label 'confirm) propose))))))))
  563. (cond ((not label)
  564. (insert "[fn::]")
  565. (backward-char 1))
  566. ((member label all)
  567. (insert "[fn:" label "]")
  568. (message "New reference to existing note"))
  569. (org-footnote-define-inline
  570. (insert "[fn:" label ":]")
  571. (backward-char 1)
  572. (org-footnote-auto-adjust-maybe))
  573. (t
  574. (insert "[fn:" label "]")
  575. (let ((p (org-footnote-create-definition label)))
  576. ;; `org-footnote-goto-definition' needs to be called
  577. ;; after `org-footnote-auto-adjust-maybe'. Otherwise
  578. ;; both label and location of the definition are lost.
  579. ;; On the contrary, it needs to be called before
  580. ;; `org-edit-footnote-reference' so that the remote
  581. ;; editing buffer can display the correct label.
  582. (if (ignore-errors (org-footnote-goto-definition label p))
  583. (org-footnote-auto-adjust-maybe)
  584. ;; Definition was created outside current scope: edit
  585. ;; it remotely.
  586. (org-footnote-auto-adjust-maybe)
  587. (org-edit-footnote-reference)))))))
  588. (defun org-footnote-create-definition (label)
  589. "Start the definition of a footnote with label LABEL.
  590. Return buffer position at the beginning of the definition. This
  591. function doesn't move point."
  592. (let ((label (org-footnote-normalize-label label))
  593. electric-indent-mode) ; Prevent wrong indentation.
  594. (org-preserve-local-variables
  595. (org-with-wide-buffer
  596. (cond
  597. ((not org-footnote-section) (org-footnote--goto-local-insertion-point))
  598. ((save-excursion
  599. (goto-char (point-min))
  600. (re-search-forward
  601. (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section) "[ \t]*$")
  602. nil t))
  603. (goto-char (match-end 0))
  604. (forward-line)
  605. (unless (bolp) (insert "\n")))
  606. (t (org-footnote--clear-footnote-section)))
  607. (when (zerop (org-back-over-empty-lines)) (insert "\n"))
  608. (insert "[fn:" label "] \n")
  609. (line-beginning-position 0)))))
  610. (defun org-footnote-delete-references (label)
  611. "Delete every reference to footnote LABEL.
  612. Return the number of footnotes removed."
  613. (save-excursion
  614. (goto-char (point-min))
  615. (let (ref (nref 0))
  616. (while (setq ref (org-footnote-get-next-reference label))
  617. (goto-char (nth 1 ref))
  618. (delete-region (nth 1 ref) (nth 2 ref))
  619. (cl-incf nref))
  620. nref)))
  621. (defun org-footnote-delete-definitions (label)
  622. "Delete every definition of the footnote LABEL.
  623. Return the number of footnotes removed."
  624. (save-excursion
  625. (goto-char (point-min))
  626. (let ((def-re (format "^\\[fn:%s\\]" (regexp-quote label)))
  627. (ndef 0))
  628. (while (re-search-forward def-re nil t)
  629. (pcase (org-footnote-at-definition-p)
  630. (`(,_ ,start ,end ,_)
  631. ;; Remove the footnote, and all blank lines before it.
  632. (delete-region (progn
  633. (goto-char start)
  634. (skip-chars-backward " \r\t\n")
  635. (if (bobp) (point) (line-beginning-position 2)))
  636. (progn
  637. (goto-char end)
  638. (skip-chars-backward " \r\t\n")
  639. (if (bobp) (point) (line-beginning-position 2))))
  640. (cl-incf ndef))))
  641. ndef)))
  642. (defun org-footnote-delete (&optional label)
  643. "Delete the footnote at point.
  644. This will remove the definition (even multiple definitions if they exist)
  645. and all references of a footnote label.
  646. If LABEL is non-nil, delete that footnote instead."
  647. (catch 'done
  648. (org-preserve-local-variables
  649. (let* ((nref 0) (ndef 0) x
  650. ;; 1. Determine LABEL of footnote at point.
  651. (label (cond
  652. ;; LABEL is provided as argument.
  653. (label)
  654. ;; Footnote reference at point. If the footnote is
  655. ;; anonymous, delete it and exit instead.
  656. ((setq x (org-footnote-at-reference-p))
  657. (or (car x)
  658. (progn
  659. (delete-region (nth 1 x) (nth 2 x))
  660. (message "Anonymous footnote removed")
  661. (throw 'done t))))
  662. ;; Footnote definition at point.
  663. ((setq x (org-footnote-at-definition-p))
  664. (car x))
  665. (t (error "Don't know which footnote to remove")))))
  666. ;; 2. Now that LABEL is non-nil, find every reference and every
  667. ;; definition, and delete them.
  668. (setq nref (org-footnote-delete-references label)
  669. ndef (org-footnote-delete-definitions label))
  670. ;; 3. Verify consistency of footnotes and notify user.
  671. (org-footnote-auto-adjust-maybe)
  672. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  673. ndef nref label)))))
  674. ;;;; Sorting, Renumbering, Normalizing
  675. (defun org-footnote-renumber-fn:N ()
  676. "Order numbered footnotes into a sequence in the document."
  677. (interactive)
  678. (let* ((c 0)
  679. (references (cl-remove-if-not
  680. (lambda (r) (string-match-p "\\`[0-9]+\\'" (car r)))
  681. (org-footnote--collect-references)))
  682. (alist (mapcar (lambda (l) (cons l (number-to-string (cl-incf c))))
  683. (delete-dups (mapcar #'car references)))))
  684. (org-with-wide-buffer
  685. ;; Re-number references.
  686. (dolist (ref references)
  687. (goto-char (nth 1 ref))
  688. (org-footnote--set-label (cdr (assoc (nth 0 ref) alist))))
  689. ;; Re-number definitions.
  690. (goto-char (point-min))
  691. (while (re-search-forward "^\\[fn:\\([0-9]+\\)\\]" nil t)
  692. (replace-match (or (cdr (assoc (match-string 1) alist))
  693. ;; Un-referenced definitions get higher
  694. ;; numbers.
  695. (number-to-string (cl-incf c)))
  696. nil nil nil 1)))))
  697. (defun org-footnote-sort ()
  698. "Rearrange footnote definitions in the current buffer.
  699. Sort footnote definitions so they match order of footnote
  700. references. Also relocate definitions at the end of their
  701. relative section or within a single footnote section, according
  702. to `org-footnote-section'. Inline definitions are ignored."
  703. (let ((references (org-footnote--collect-references)))
  704. (org-preserve-local-variables
  705. (let ((definitions (org-footnote--collect-definitions 'delete)))
  706. (org-with-wide-buffer
  707. (org-footnote--clear-footnote-section)
  708. ;; Insert footnote definitions at the appropriate location,
  709. ;; separated by a blank line. Each definition is inserted
  710. ;; only once throughout the buffer.
  711. (let (inserted)
  712. (dolist (cell references)
  713. (let ((label (car cell))
  714. (nested (not (nth 2 cell)))
  715. (inline (nth 3 cell)))
  716. (unless (or (member label inserted) inline)
  717. (push label inserted)
  718. (unless (or org-footnote-section nested)
  719. ;; If `org-footnote-section' is non-nil, or
  720. ;; reference is nested, point is already at the
  721. ;; correct position. Otherwise, move at the
  722. ;; appropriate location within the section
  723. ;; containing the reference.
  724. (goto-char (nth 1 cell))
  725. (org-footnote--goto-local-insertion-point))
  726. (insert "\n"
  727. (or (cdr (assoc label definitions))
  728. (format "[fn:%s] DEFINITION NOT FOUND." label))
  729. "\n"))))
  730. ;; Insert un-referenced footnote definitions at the end.
  731. (pcase-dolist (`(,label . ,definition) definitions)
  732. (unless (member label inserted)
  733. (insert "\n" definition "\n")))))))))
  734. (defun org-footnote-normalize ()
  735. "Turn every footnote in buffer into a numbered one."
  736. (interactive)
  737. (org-preserve-local-variables
  738. (let ((n 0)
  739. (translations nil)
  740. (definitions nil)
  741. (references (org-footnote--collect-references 'anonymous)))
  742. (org-with-wide-buffer
  743. ;; Update label for reference. We need to do this before
  744. ;; clearing definitions in order to rename nested footnotes
  745. ;; before they are deleted.
  746. (dolist (cell references)
  747. (let* ((label (car cell))
  748. (anonymous (not label))
  749. (new
  750. (cond
  751. ;; In order to differentiate anonymous references
  752. ;; from regular ones, set their labels to integers,
  753. ;; not strings.
  754. (anonymous (setcar cell (cl-incf n)))
  755. ((cdr (assoc label translations)))
  756. (t (let ((l (number-to-string (cl-incf n))))
  757. (push (cons label l) translations)
  758. l)))))
  759. (goto-char (nth 1 cell)) ; Move to reference's start.
  760. (org-footnote--set-label
  761. (if anonymous (number-to-string new) new))
  762. (let ((size (nth 3 cell)))
  763. ;; Transform inline footnotes into regular references and
  764. ;; retain their definition for later insertion as
  765. ;; a regular footnote definition.
  766. (when size
  767. (let ((def (concat
  768. (format "[fn:%s] " new)
  769. (org-trim
  770. (substring
  771. (delete-and-extract-region
  772. (point) (+ (point) size 1))
  773. 1)))))
  774. (push (cons (if anonymous new label) def) definitions)
  775. (when org-footnote-fill-after-inline-note-extraction
  776. (org-fill-paragraph)))))))
  777. ;; Collect definitions. Update labels according to ALIST.
  778. (let ((definitions
  779. (nconc definitions
  780. (org-footnote--collect-definitions 'delete)))
  781. (inserted))
  782. (org-footnote--clear-footnote-section)
  783. (dolist (cell references)
  784. (let* ((label (car cell))
  785. (anonymous (integerp label))
  786. (pos (nth 1 cell)))
  787. ;; Move to appropriate location, if required. When there
  788. ;; is a footnote section or reference is nested, point is
  789. ;; already at the expected location.
  790. (unless (or org-footnote-section (not (nth 2 cell)))
  791. (goto-char pos)
  792. (org-footnote--goto-local-insertion-point))
  793. ;; Insert new definition once label is updated.
  794. (unless (member label inserted)
  795. (push label inserted)
  796. (let ((stored (cdr (assoc label definitions)))
  797. ;; Anonymous footnotes' label is already
  798. ;; up-to-date.
  799. (new (if anonymous label
  800. (cdr (assoc label translations)))))
  801. (insert "\n"
  802. (cond
  803. ((not stored)
  804. (format "[fn:%s] DEFINITION NOT FOUND." new))
  805. (anonymous stored)
  806. (t
  807. (replace-regexp-in-string
  808. "\\`\\[fn:\\(.*?\\)\\]" new stored nil nil 1)))
  809. "\n")))))
  810. ;; Insert un-referenced footnote definitions at the end.
  811. (pcase-dolist (`(,label . ,definition) definitions)
  812. (unless (member label inserted)
  813. (insert "\n"
  814. (replace-regexp-in-string org-footnote-definition-re
  815. (format "[fn:%d]" (cl-incf n))
  816. definition)
  817. "\n"))))))))
  818. (defun org-footnote-auto-adjust-maybe ()
  819. "Renumber and/or sort footnotes according to user settings."
  820. (when (memq org-footnote-auto-adjust '(t renumber))
  821. (org-footnote-renumber-fn:N))
  822. (when (memq org-footnote-auto-adjust '(t sort))
  823. (let ((label (car (org-footnote-at-definition-p))))
  824. (org-footnote-sort)
  825. (when label
  826. (goto-char (point-min))
  827. (and (re-search-forward (format "^\\[fn:%s\\]" (regexp-quote label))
  828. nil t)
  829. (progn (insert " ")
  830. (just-one-space)))))))
  831. ;;;; End-user interface
  832. ;;;###autoload
  833. (defun org-footnote-action (&optional special)
  834. "Do the right thing for footnotes.
  835. When at a footnote reference, jump to the definition.
  836. When at a definition, jump to the references if they exist, offer
  837. to create them otherwise.
  838. When neither at definition or reference, create a new footnote,
  839. interactively if possible.
  840. With prefix arg SPECIAL, or when no footnote can be created,
  841. offer additional commands in a menu."
  842. (interactive "P")
  843. (let* ((context (and (not special) (org-element-context)))
  844. (type (org-element-type context)))
  845. (cond
  846. ;; On white space after element, insert a new footnote.
  847. ((and context
  848. (> (point)
  849. (save-excursion
  850. (goto-char (org-element-property :end context))
  851. (skip-chars-backward " \t")
  852. (point))))
  853. (org-footnote-new))
  854. ((eq type 'footnote-reference)
  855. (let ((label (org-element-property :label context)))
  856. (cond
  857. ;; Anonymous footnote: move point at the beginning of its
  858. ;; definition.
  859. ((not label)
  860. (goto-char (org-element-property :contents-begin context)))
  861. ;; Check if a definition exists: then move to it.
  862. ((let ((p (nth 1 (org-footnote-get-definition label))))
  863. (when p (org-footnote-goto-definition label p))))
  864. ;; No definition exists: offer to create it.
  865. ((yes-or-no-p (format "No definition for %s. Create one? " label))
  866. (let ((p (org-footnote-create-definition label)))
  867. (or (ignore-errors (org-footnote-goto-definition label p))
  868. ;; Since definition was created outside current scope,
  869. ;; edit it remotely.
  870. (org-edit-footnote-reference)))))))
  871. ((eq type 'footnote-definition)
  872. (org-footnote-goto-previous-reference
  873. (org-element-property :label context)))
  874. ((or special (not (org-footnote--allow-reference-p)))
  875. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | [n]ormalize | \
  876. \[d]elete")
  877. (pcase (read-char-exclusive)
  878. (?s (org-footnote-sort))
  879. (?r (org-footnote-renumber-fn:N))
  880. (?S (org-footnote-renumber-fn:N)
  881. (org-footnote-sort))
  882. (?n (org-footnote-normalize))
  883. (?d (org-footnote-delete))
  884. (char (error "No such footnote command %c" char))))
  885. (t (org-footnote-new)))))
  886. (provide 'org-footnote)
  887. ;; Local variables:
  888. ;; generated-autoload-file: "org-loaddefs.el"
  889. ;; End:
  890. ;;; org-footnote.el ends here