org-footnote.el 36 KB

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