org-footnote.el 36 KB

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