org-footnote.el 36 KB

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