org-footnote.el 37 KB

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