org-footnote.el 39 KB

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