org-footnote.el 37 KB

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