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