org-footnote.el 36 KB

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