org-footnote.el 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. ;;; org-footnote.el --- Footnote support in Org -*- lexical-binding: t; -*-
  2. ;;
  3. ;; Copyright (C) 2009-2016 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 &optional keep-lead))
  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 (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 "%s" (substitute-command-keys
  469. "Edit definition and go back with \
  470. `\\[org-mark-ring-goto]' or, if unique, with `\\[org-ctrl-c-ctrl-c]'.")))
  471. t))
  472. (defun org-footnote-goto-previous-reference (label)
  473. "Find the first closest (to point) reference of footnote with label LABEL."
  474. (interactive "sLabel: ")
  475. (org-mark-ring-push)
  476. (let ((label (org-footnote-normalize-label label))
  477. ref)
  478. (save-excursion
  479. (setq ref (or (org-footnote-get-next-reference label t)
  480. (org-footnote-get-next-reference label)
  481. (save-restriction
  482. (widen)
  483. (or
  484. (org-footnote-get-next-reference label t)
  485. (org-footnote-get-next-reference label))))))
  486. (if (not ref)
  487. (error "Cannot find reference of footnote %s" label)
  488. (goto-char (nth 1 ref))
  489. (org-show-context 'link-search))))
  490. ;;;; Getters
  491. (defun org-footnote-normalize-label (label)
  492. "Return LABEL without \"fn:\" prefix.
  493. If LABEL is the empty string or constituted of white spaces only,
  494. return nil instead."
  495. (pcase (org-trim label)
  496. ("" nil)
  497. ((pred (string-prefix-p "fn:")) (substring label 3))
  498. (_ label)))
  499. (defun org-footnote-get-definition (label)
  500. "Return label, boundaries and definition of the footnote LABEL."
  501. (let* ((label (regexp-quote (org-footnote-normalize-label label)))
  502. (re (format "^\\[fn:%s\\]\\|.\\[fn:%s:" label label)))
  503. (org-with-wide-buffer
  504. (goto-char (point-min))
  505. (catch 'found
  506. (while (re-search-forward re nil t)
  507. (let* ((datum (progn (backward-char) (org-element-context)))
  508. (type (org-element-type datum)))
  509. (when (memq type '(footnote-definition footnote-reference))
  510. (throw 'found
  511. (list
  512. label
  513. (org-element-property :begin datum)
  514. (org-element-property :end datum)
  515. (let ((cbeg (org-element-property :contents-begin datum)))
  516. (if (not cbeg) ""
  517. (replace-regexp-in-string
  518. "[ \t\n]*\\'"
  519. ""
  520. (buffer-substring-no-properties
  521. cbeg
  522. (org-element-property :contents-end datum))))))))))
  523. nil))))
  524. (defun org-footnote-all-labels ()
  525. "List all defined footnote labels used throughout the buffer.
  526. This function ignores narrowing, if any."
  527. (org-with-wide-buffer
  528. (goto-char (point-min))
  529. (let (all)
  530. (while (re-search-forward org-footnote-re nil t)
  531. (backward-char)
  532. (let ((context (org-element-context)))
  533. (when (memq (org-element-type context)
  534. '(footnote-definition footnote-reference))
  535. (let ((label (org-element-property :label context)))
  536. (when label (cl-pushnew label all :test #'equal))))))
  537. all)))
  538. (defun org-footnote-unique-label (&optional current)
  539. "Return a new unique footnote label.
  540. The function returns the first numeric label currently unused.
  541. Optional argument CURRENT is the list of labels active in the
  542. buffer."
  543. (let ((current (or current (org-footnote-all-labels))))
  544. (let ((count 1))
  545. (while (member (number-to-string count) current)
  546. (cl-incf count))
  547. (number-to-string count))))
  548. ;;;; Adding, Deleting Footnotes
  549. (defun org-footnote-new ()
  550. "Insert a new footnote.
  551. This command prompts for a label. If this is a label referencing an
  552. existing label, only insert the label. If the footnote label is empty
  553. or new, let the user edit the definition of the footnote."
  554. (interactive)
  555. (unless (org-footnote--allow-reference-p)
  556. (user-error "Cannot insert a footnote here"))
  557. (let* ((all (org-footnote-all-labels))
  558. (label
  559. (if (eq org-footnote-auto-label 'random)
  560. (format "%x" (random most-positive-fixnum))
  561. (org-footnote-normalize-label
  562. (let ((propose (org-footnote-unique-label all)))
  563. (if (eq org-footnote-auto-label t) propose
  564. (completing-read
  565. "Label (leave empty for anonymous): "
  566. (mapcar #'list all) nil nil
  567. (and (eq org-footnote-auto-label 'confirm) propose))))))))
  568. (cond ((not label)
  569. (insert "[fn::]")
  570. (backward-char 1))
  571. ((member label all)
  572. (insert "[fn:" label "]")
  573. (message "New reference to existing note"))
  574. (org-footnote-define-inline
  575. (insert "[fn:" label ":]")
  576. (backward-char 1)
  577. (org-footnote-auto-adjust-maybe))
  578. (t
  579. (insert "[fn:" label "]")
  580. (let ((p (org-footnote-create-definition label)))
  581. ;; `org-footnote-goto-definition' needs to be called
  582. ;; after `org-footnote-auto-adjust-maybe'. Otherwise
  583. ;; both label and location of the definition are lost.
  584. ;; On the contrary, it needs to be called before
  585. ;; `org-edit-footnote-reference' so that the remote
  586. ;; editing buffer can display the correct label.
  587. (if (ignore-errors (org-footnote-goto-definition label p))
  588. (org-footnote-auto-adjust-maybe)
  589. ;; Definition was created outside current scope: edit
  590. ;; it remotely.
  591. (org-footnote-auto-adjust-maybe)
  592. (org-edit-footnote-reference)))))))
  593. (defun org-footnote-create-definition (label)
  594. "Start the definition of a footnote with label LABEL.
  595. Return buffer position at the beginning of the definition. This
  596. function doesn't move point."
  597. (let ((label (org-footnote-normalize-label label))
  598. electric-indent-mode) ; Prevent wrong indentation.
  599. (org-with-wide-buffer
  600. (cond
  601. ((not org-footnote-section) (org-footnote--goto-local-insertion-point))
  602. ((save-excursion
  603. (goto-char (point-min))
  604. (re-search-forward
  605. (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section) "[ \t]*$")
  606. nil t))
  607. (goto-char (match-end 0))
  608. (forward-line)
  609. (unless (bolp) (insert "\n")))
  610. (t (org-footnote--clear-footnote-section)))
  611. (when (zerop (org-back-over-empty-lines)) (insert "\n"))
  612. (insert "[fn:" label "] \n")
  613. (line-beginning-position 0))))
  614. (defun org-footnote-delete-references (label)
  615. "Delete every reference to footnote LABEL.
  616. Return the number of footnotes removed."
  617. (save-excursion
  618. (goto-char (point-min))
  619. (let (ref (nref 0))
  620. (while (setq ref (org-footnote-get-next-reference label))
  621. (goto-char (nth 1 ref))
  622. (delete-region (nth 1 ref) (nth 2 ref))
  623. (cl-incf nref))
  624. nref)))
  625. (defun org-footnote-delete-definitions (label)
  626. "Delete every definition of the footnote LABEL.
  627. Return the number of footnotes removed."
  628. (save-excursion
  629. (goto-char (point-min))
  630. (let ((def-re (format "^\\[fn:%s\\]" (regexp-quote label)))
  631. (ndef 0))
  632. (while (re-search-forward def-re nil t)
  633. (let ((full-def (org-footnote-at-definition-p)))
  634. (when full-def
  635. ;; Remove the footnote, and all blank lines before it.
  636. (goto-char (nth 1 full-def))
  637. (skip-chars-backward " \r\t\n")
  638. (unless (bolp) (forward-line))
  639. (delete-region (point) (nth 2 full-def))
  640. (cl-incf ndef))))
  641. ndef)))
  642. (defun org-footnote-delete (&optional label)
  643. "Delete the footnote at point.
  644. This will remove the definition (even multiple definitions if they exist)
  645. and all references of a footnote label.
  646. If LABEL is non-nil, delete that footnote instead."
  647. (catch 'done
  648. (let* ((nref 0) (ndef 0) x
  649. ;; 1. Determine LABEL of footnote at point.
  650. (label (cond
  651. ;; LABEL is provided as argument.
  652. (label)
  653. ;; Footnote reference at point. If the footnote is
  654. ;; anonymous, delete it and exit instead.
  655. ((setq x (org-footnote-at-reference-p))
  656. (or (car x)
  657. (progn
  658. (delete-region (nth 1 x) (nth 2 x))
  659. (message "Anonymous footnote removed")
  660. (throw 'done t))))
  661. ;; Footnote definition at point.
  662. ((setq x (org-footnote-at-definition-p))
  663. (car x))
  664. (t (error "Don't know which footnote to remove")))))
  665. ;; 2. Now that LABEL is non-nil, find every reference and every
  666. ;; definition, and delete them.
  667. (setq nref (org-footnote-delete-references label)
  668. ndef (org-footnote-delete-definitions label))
  669. ;; 3. Verify consistency of footnotes and notify user.
  670. (org-footnote-auto-adjust-maybe)
  671. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  672. ndef nref label))))
  673. ;;;; Sorting, Renumbering, Normalizing
  674. (defun org-footnote-renumber-fn:N ()
  675. "Order numbered footnotes into a sequence in the document."
  676. (interactive)
  677. (let ((references (org-footnote--collect-references)))
  678. (unwind-protect
  679. (let* ((c 0)
  680. (references (cl-remove-if-not
  681. (lambda (r) (string-match-p "\\`[0-9]+\\'" (car r)))
  682. references))
  683. (alist (mapcar (lambda (l) (cons l (number-to-string (cl-incf c))))
  684. (delete-dups (mapcar #'car references)))))
  685. (org-with-wide-buffer
  686. ;; Re-number references.
  687. (dolist (ref references)
  688. (goto-char (nth 1 ref))
  689. (org-footnote--set-label (cdr (assoc (nth 0 ref) alist))))
  690. ;; Re-number definitions.
  691. (goto-char (point-min))
  692. (while (re-search-forward "^\\[fn:\\([0-9]+\\)\\]" nil t)
  693. (replace-match (or (cdr (assoc (match-string 1) alist))
  694. ;; Un-referenced definitions get
  695. ;; higher numbers.
  696. (number-to-string (cl-incf c)))
  697. nil nil nil 1))))
  698. (dolist (r references) (set-marker (nth 1 r) nil)))))
  699. (defun org-footnote-sort ()
  700. "Rearrange footnote definitions in the current buffer.
  701. Sort footnote definitions so they match order of footnote
  702. references. Also relocate definitions at the end of their
  703. relative section or within a single footnote section, according
  704. to `org-footnote-section'. Inline definitions are ignored."
  705. (let ((references (org-footnote--collect-references)))
  706. (unwind-protect
  707. (let ((definitions (org-footnote--collect-definitions 'delete)))
  708. (org-with-wide-buffer
  709. (org-footnote--clear-footnote-section)
  710. ;; Insert footnote definitions at the appropriate location,
  711. ;; separated by a blank line. Each definition is inserted
  712. ;; only once throughout the buffer.
  713. (let (inserted)
  714. (dolist (cell references)
  715. (let ((label (car cell))
  716. (nested (not (nth 2 cell)))
  717. (inline (nth 3 cell)))
  718. (unless (or (member label inserted) inline)
  719. (push label inserted)
  720. (unless (or org-footnote-section nested)
  721. ;; If `org-footnote-section' is non-nil, or
  722. ;; reference is nested, point is already at the
  723. ;; correct position. Otherwise, move at the
  724. ;; appropriate location within the section
  725. ;; containing the reference.
  726. (goto-char (nth 1 cell))
  727. (org-footnote--goto-local-insertion-point))
  728. (insert "\n"
  729. (or (cdr (assoc label definitions))
  730. (format "[fn:%s] DEFINITION NOT FOUND." label))
  731. "\n"))))
  732. ;; Insert un-referenced footnote definitions at the end.
  733. (let ((unreferenced
  734. (cl-remove-if (lambda (d) (member (car d) inserted))
  735. definitions)))
  736. (dolist (d unreferenced) (insert "\n" (cdr d) "\n"))))))
  737. ;; Clear dangling markers in the buffer.
  738. (dolist (r references) (set-marker (nth 1 r) nil)))))
  739. (defun org-footnote-normalize ()
  740. "Turn every footnote in buffer into a numbered one."
  741. (interactive)
  742. (let ((references (org-footnote--collect-references 'anonymous)))
  743. (unwind-protect
  744. (let ((n 0)
  745. (translations nil)
  746. (definitions nil))
  747. (org-with-wide-buffer
  748. ;; Update label for reference. We need to do this before
  749. ;; clearing definitions in order to rename nested footnotes
  750. ;; before they are deleted.
  751. (dolist (cell references)
  752. (let* ((label (car cell))
  753. (anonymous (not label))
  754. (new
  755. (cond
  756. ;; In order to differentiate anonymous
  757. ;; references from regular ones, set their
  758. ;; labels to integers, not strings.
  759. (anonymous (setcar cell (cl-incf n)))
  760. ((cdr (assoc label translations)))
  761. (t (let ((l (number-to-string (cl-incf n))))
  762. (push (cons label l) translations)
  763. l)))))
  764. (goto-char (nth 1 cell)) ; Move to reference's start.
  765. (org-footnote--set-label
  766. (if anonymous (number-to-string new) new))
  767. (let ((size (nth 3 cell)))
  768. ;; Transform inline footnotes into regular references
  769. ;; and retain their definition for later insertion as
  770. ;; a regular footnote definition.
  771. (when size
  772. (let ((def (concat
  773. (format "[fn:%s] " new)
  774. (org-trim
  775. (substring
  776. (delete-and-extract-region
  777. (point) (+ (point) size 1))
  778. 1)))))
  779. (push (cons (if anonymous new label) def) definitions)
  780. (when org-footnote-fill-after-inline-note-extraction
  781. (org-fill-paragraph)))))))
  782. ;; Collect definitions. Update labels according to ALIST.
  783. (let ((definitions
  784. (nconc definitions
  785. (org-footnote--collect-definitions 'delete)))
  786. (inserted))
  787. (org-footnote--clear-footnote-section)
  788. (dolist (cell references)
  789. (let* ((label (car cell))
  790. (anonymous (integerp label))
  791. (pos (nth 1 cell)))
  792. ;; Move to appropriate location, if required. When
  793. ;; there is a footnote section or reference is
  794. ;; nested, point is already at the expected location.
  795. (unless (or org-footnote-section (not (nth 2 cell)))
  796. (goto-char pos)
  797. (org-footnote--goto-local-insertion-point))
  798. ;; Insert new definition once label is updated.
  799. (unless (member label inserted)
  800. (push label inserted)
  801. (let ((stored (cdr (assoc label definitions)))
  802. ;; Anonymous footnotes' label is already
  803. ;; up-to-date.
  804. (new (if anonymous label
  805. (cdr (assoc label translations)))))
  806. (insert "\n"
  807. (cond
  808. ((not stored)
  809. (format "[fn:%s] DEFINITION NOT FOUND." new))
  810. (anonymous stored)
  811. (t
  812. (replace-regexp-in-string
  813. "\\`\\[fn:\\(.*?\\)\\]" new stored nil nil 1)))
  814. "\n")))))
  815. ;; Insert un-referenced footnote definitions at the end.
  816. (let ((unreferenced
  817. (cl-remove-if (lambda (d) (member (car d) inserted))
  818. definitions)))
  819. (dolist (d unreferenced)
  820. (insert "\n"
  821. (replace-regexp-in-string
  822. org-footnote-definition-re
  823. (format "[fn:%d]" (cl-incf n))
  824. (cdr d))
  825. "\n"))))))
  826. ;; Clear dangling markers.
  827. (dolist (r references) (set-marker (nth 1 r) nil)))))
  828. (defun org-footnote-auto-adjust-maybe ()
  829. "Renumber and/or sort footnotes according to user settings."
  830. (when (memq org-footnote-auto-adjust '(t renumber))
  831. (org-footnote-renumber-fn:N))
  832. (when (memq org-footnote-auto-adjust '(t sort))
  833. (let ((label (car (org-footnote-at-definition-p))))
  834. (org-footnote-sort)
  835. (when label
  836. (goto-char (point-min))
  837. (and (re-search-forward (format "^\\[fn:%s\\]" (regexp-quote label))
  838. nil t)
  839. (progn (insert " ")
  840. (just-one-space)))))))
  841. ;;;; End-user interface
  842. ;;;###autoload
  843. (defun org-footnote-action (&optional special)
  844. "Do the right thing for footnotes.
  845. When at a footnote reference, jump to the definition.
  846. When at a definition, jump to the references if they exist, offer
  847. to create them otherwise.
  848. When neither at definition or reference, create a new footnote,
  849. interactively if possible.
  850. With prefix arg SPECIAL, or when no footnote can be created,
  851. offer additional commands in a menu."
  852. (interactive "P")
  853. (let* ((context (and (not special) (org-element-context)))
  854. (type (org-element-type context)))
  855. (cond
  856. ;; On white space after element, insert a new footnote.
  857. ((and context
  858. (> (point)
  859. (save-excursion
  860. (goto-char (org-element-property :end context))
  861. (skip-chars-backward " \t")
  862. (point))))
  863. (org-footnote-new))
  864. ((eq type 'footnote-reference)
  865. (let ((label (org-element-property :label context)))
  866. (cond
  867. ;; Anonymous footnote: move point at the beginning of its
  868. ;; definition.
  869. ((not label)
  870. (goto-char (org-element-property :contents-begin context)))
  871. ;; Check if a definition exists: then move to it.
  872. ((let ((p (nth 1 (org-footnote-get-definition label))))
  873. (when p (org-footnote-goto-definition label p))))
  874. ;; No definition exists: offer to create it.
  875. ((yes-or-no-p (format "No definition for %s. Create one? " label))
  876. (let ((p (org-footnote-create-definition label)))
  877. (or (ignore-errors (org-footnote-goto-definition label p))
  878. ;; Since definition was created outside current scope,
  879. ;; edit it remotely.
  880. (org-edit-footnote-reference)))))))
  881. ((eq type 'footnote-definition)
  882. (org-footnote-goto-previous-reference
  883. (org-element-property :label context)))
  884. ((or special (not (org-footnote--allow-reference-p)))
  885. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | [n]ormalize | \
  886. \[d]elete")
  887. (pcase (read-char-exclusive)
  888. (?s (org-footnote-sort))
  889. (?r (org-footnote-renumber-fn:N))
  890. (?S (org-footnote-renumber-fn:N)
  891. (org-footnote-sort))
  892. (?n (org-footnote-normalize))
  893. (?d (org-footnote-delete))
  894. (char (error "No such footnote command %c" char))))
  895. (t (org-footnote-new)))))
  896. (provide 'org-footnote)
  897. ;; Local variables:
  898. ;; generated-autoload-file: "org-loaddefs.el"
  899. ;; End:
  900. ;;; org-footnote.el ends here