org-footnote.el 36 KB

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