org-footnote.el 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  1. ;;; org-footnote.el --- Footnote support in Org and elsewhere
  2. ;;
  3. ;; Copyright (C) 2009-2016 Free Software Foundation, Inc.
  4. ;;
  5. ;; Author: Carsten Dominik <carsten at orgmode dot org>
  6. ;; Keywords: outlines, hypermedia, calendar, wp
  7. ;; Homepage: http://orgmode.org
  8. ;;
  9. ;; This file is part of GNU Emacs.
  10. ;;
  11. ;; GNU Emacs is free software: you can redistribute it and/or modify
  12. ;; it under the terms of the GNU General Public License as published by
  13. ;; the Free Software Foundation, either version 3 of the License, or
  14. ;; (at your option) any later version.
  15. ;; GNU Emacs is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. ;; GNU General Public License for more details.
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  21. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  22. ;;
  23. ;;; Commentary:
  24. ;; This file contains the code dealing with footnotes in Org-mode.
  25. ;; 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 "%s" (substitute-command-keys
  353. "Edit definition and go back with \
  354. `\\[org-mark-ring-goto]' or, if unique, with `\\[org-ctrl-c-ctrl-c]'.")))
  355. t))
  356. (defun org-footnote-goto-previous-reference (label)
  357. "Find the first closest (to point) reference of footnote with label LABEL."
  358. (interactive "sLabel: ")
  359. (org-mark-ring-push)
  360. (let* ((label (org-footnote-normalize-label label)) ref)
  361. (save-excursion
  362. (setq ref (or (org-footnote-get-next-reference label t)
  363. (org-footnote-get-next-reference label)
  364. (save-restriction
  365. (widen)
  366. (or
  367. (org-footnote-get-next-reference label t)
  368. (org-footnote-get-next-reference label))))))
  369. (if (not ref)
  370. (error "Cannot find reference of footnote %s" label)
  371. (goto-char (nth 1 ref))
  372. (org-show-context 'link-search))))
  373. (defun org-footnote-normalize-label (label)
  374. "Return LABEL as an appropriate string."
  375. (cond
  376. ((numberp label) (number-to-string label))
  377. ((equal "" label) nil)
  378. ((not (string-match "^[0-9]+$\\|^fn:" label))
  379. (concat "fn:" label))
  380. (t label)))
  381. (defun org-footnote-all-labels (&optional with-defs)
  382. "Return list with all defined foot labels used in the buffer.
  383. If WITH-DEFS is non-nil, also associate the definition to each
  384. label. The function will then return an alist whose key is label
  385. and value definition."
  386. (let* (rtn
  387. (push-to-rtn
  388. (function
  389. ;; Depending on WITH-DEFS, store label or (label . def) of
  390. ;; footnote reference/definition given as argument in RTN.
  391. (lambda (el)
  392. (let ((lbl (car el)))
  393. (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
  394. (save-excursion
  395. (save-restriction
  396. (widen)
  397. ;; Find all labels found in definitions.
  398. (goto-char (point-min))
  399. (let (def)
  400. (while (re-search-forward org-footnote-definition-re nil t)
  401. (when (setq def (org-footnote-at-definition-p))
  402. (funcall push-to-rtn def))))
  403. ;; Find all labels found in references.
  404. (goto-char (point-min))
  405. (let (ref)
  406. (while (setq ref (org-footnote-get-next-reference))
  407. (goto-char (nth 2 ref))
  408. (and (car ref) ; ignore anonymous footnotes
  409. (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
  410. (funcall push-to-rtn ref))))))
  411. rtn))
  412. (defun org-footnote-unique-label (&optional current)
  413. "Return a new unique footnote label.
  414. The function returns the first \"fn:N\" or \"N\" label that is
  415. currently not used.
  416. Optional argument CURRENT is the list of labels active in the
  417. buffer."
  418. (unless current (setq current (org-footnote-all-labels)))
  419. (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
  420. (cnt 1))
  421. (while (member (format fmt cnt) current)
  422. (incf cnt))
  423. (format fmt cnt)))
  424. (defun org-footnote--allow-reference-p ()
  425. "Non-nil when a footnote reference can be inserted at point."
  426. ;; XXX: This is similar to `org-footnote-in-valid-context-p' but
  427. ;; more accurate and usually faster, except in some corner cases.
  428. ;; It may replace it after doing proper benchmarks as it would be
  429. ;; used in fontification.
  430. (unless (bolp)
  431. (let* ((context (org-element-context))
  432. (type (org-element-type context)))
  433. (cond
  434. ;; No footnote reference in attributes.
  435. ((let ((post (org-element-property :post-affiliated context)))
  436. (and post (< (point) post)))
  437. nil)
  438. ;; Paragraphs and blank lines at top of document are fine.
  439. ((memq type '(nil paragraph)))
  440. ;; So are contents of verse blocks.
  441. ((eq type 'verse-block)
  442. (and (>= (point) (org-element-property :contents-begin context))
  443. (< (point) (org-element-property :contents-end context))))
  444. ;; In an headline or inlinetask, point must be either on the
  445. ;; heading itself or on the blank lines below.
  446. ((memq type '(headline inlinetask))
  447. (or (not (org-at-heading-p))
  448. (and (save-excursion (beginning-of-line)
  449. (and (let ((case-fold-search t))
  450. (not (looking-at "\\*+ END[ \t]*$")))
  451. (looking-at org-complex-heading-regexp)))
  452. (match-beginning 4)
  453. (>= (point) (match-beginning 4))
  454. (or (not (match-beginning 5))
  455. (< (point) (match-beginning 5))))))
  456. ;; White spaces after an object or blank lines after an element
  457. ;; are OK.
  458. ((>= (point)
  459. (save-excursion (goto-char (org-element-property :end context))
  460. (skip-chars-backward " \r\t\n")
  461. (if (memq type org-element-all-objects) (point)
  462. (1+ (line-beginning-position 2))))))
  463. ;; Other elements are invalid.
  464. ((memq type org-element-all-elements) nil)
  465. ;; Just before object is fine.
  466. ((= (point) (org-element-property :begin context)))
  467. ;; Within recursive object too, but not in a link.
  468. ((eq type 'link) nil)
  469. ((let ((cbeg (org-element-property :contents-begin context))
  470. (cend (org-element-property :contents-end context)))
  471. (and cbeg (>= (point) cbeg) (<= (point) cend))))))))
  472. (defun org-footnote-new ()
  473. "Insert a new footnote.
  474. This command prompts for a label. If this is a label referencing an
  475. existing label, only insert the label. If the footnote label is empty
  476. or new, let the user edit the definition of the footnote."
  477. (interactive)
  478. (unless (org-footnote--allow-reference-p)
  479. (user-error "Cannot insert a footnote here"))
  480. (let* ((all (org-footnote-all-labels))
  481. (label
  482. (org-footnote-normalize-label
  483. (if (eq org-footnote-auto-label 'random)
  484. (format "fn:%x" (random most-positive-fixnum))
  485. (let ((propose (org-footnote-unique-label all)))
  486. (if (memq org-footnote-auto-label '(t plain)) propose
  487. (org-icompleting-read
  488. "Label (leave empty for anonymous): "
  489. (mapcar #'list all) nil nil
  490. (and (eq org-footnote-auto-label 'confirm) propose))))))))
  491. (cond ((not label)
  492. (insert "[fn::]")
  493. (backward-char 1))
  494. ((member label all)
  495. (insert "[" label "]")
  496. (message "New reference to existing note"))
  497. (org-footnote-define-inline
  498. (insert "[" label ":]")
  499. (backward-char 1)
  500. (org-footnote-auto-adjust-maybe))
  501. (t
  502. (insert "[" label "]")
  503. (let ((p (org-footnote-create-definition label)))
  504. ;; `org-footnote-goto-definition' needs to be called
  505. ;; after `org-footnote-auto-adjust-maybe'. Otherwise
  506. ;; both label and location of the definition are lost.
  507. ;; On the contrary, it needs to be called before
  508. ;; `org-edit-footnote-reference' so that the remote
  509. ;; editing buffer can display the correct label.
  510. (if (ignore-errors (org-footnote-goto-definition label p))
  511. (org-footnote-auto-adjust-maybe)
  512. ;; Definition was created outside current scope: edit
  513. ;; it remotely.
  514. (org-footnote-auto-adjust-maybe)
  515. (org-edit-footnote-reference)))))))
  516. (defvar org-blank-before-new-entry) ; Silence byte-compiler.
  517. (defun org-footnote-create-definition (label)
  518. "Start the definition of a footnote with label LABEL.
  519. Return buffer position at the beginning of the definition. In an
  520. Org buffer, this function doesn't move point."
  521. (let ((label (org-footnote-normalize-label label))
  522. electric-indent-mode) ; Prevent wrong indentation.
  523. (cond
  524. ;; In an Org document.
  525. ((derived-mode-p 'org-mode)
  526. ;; If `org-footnote-section' is defined, find it, or create it
  527. ;; at the end of the buffer.
  528. (org-with-wide-buffer
  529. (cond
  530. ((not org-footnote-section)
  531. (org-footnote--goto-local-insertion-point))
  532. ((save-excursion
  533. (goto-char (point-min))
  534. (re-search-forward
  535. (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section) "[ \t]*$")
  536. nil t))
  537. (goto-char (match-end 0))
  538. (forward-line)
  539. (unless (bolp) (insert "\n")))
  540. (t
  541. (goto-char (point-max))
  542. (unless (bolp) (insert "\n"))
  543. ;; Insert new section. Separate it from the previous one
  544. ;; with a blank line, unless `org-blank-before-new-entry'
  545. ;; explicitly says no.
  546. (when (and (cdr (assq 'heading org-blank-before-new-entry))
  547. (zerop (save-excursion (org-back-over-empty-lines))))
  548. (insert "\n"))
  549. (insert "* " org-footnote-section "\n")))
  550. (when (zerop (org-back-over-empty-lines)) (insert "\n"))
  551. (insert "[" label "] \n")
  552. (line-beginning-position 0)))
  553. (t
  554. ;; In a non-Org file. Search for footnote tag, or create it if
  555. ;; specified (at the end of buffer, or before signature if in
  556. ;; Message mode). Set point after any definition already there.
  557. (let ((tag (and org-footnote-tag-for-non-org-mode-files
  558. (concat "^" (regexp-quote
  559. org-footnote-tag-for-non-org-mode-files)
  560. "[ \t]*$")))
  561. (max (if (and (derived-mode-p 'message-mode)
  562. (goto-char (point-max))
  563. (re-search-backward
  564. message-signature-separator nil t))
  565. (progn
  566. ;; Ensure one blank line separates last
  567. ;; footnote from signature.
  568. (beginning-of-line)
  569. (open-line 2)
  570. (point-marker))
  571. (point-max-marker))))
  572. (set-marker-insertion-type max t)
  573. (goto-char max)
  574. ;; Check if the footnote tag is defined but missing. In this
  575. ;; case, insert it, before any footnote or one blank line
  576. ;; after any previous text.
  577. (when (and tag (not (re-search-backward tag nil t)))
  578. (skip-chars-backward " \t\r\n")
  579. (while (re-search-backward org-footnote-definition-re nil t))
  580. (unless (bolp) (newline 2))
  581. (insert org-footnote-tag-for-non-org-mode-files "\n\n"))
  582. ;; Remove superfluous white space and clear marker.
  583. (goto-char max)
  584. (skip-chars-backward " \t\r\n")
  585. (delete-region (point) max)
  586. (unless (bolp) (newline))
  587. (set-marker max nil))
  588. (when (zerop (org-back-over-empty-lines)) (insert "\n"))
  589. (insert "[" label "] \n")
  590. (backward-char)
  591. (line-beginning-position)))))
  592. ;;;###autoload
  593. (defun org-footnote-action (&optional special)
  594. "Do the right thing for footnotes.
  595. When at a footnote reference, jump to the definition.
  596. When at a definition, jump to the references if they exist, offer
  597. to create them otherwise.
  598. When neither at definition or reference, create a new footnote,
  599. interactively if possible.
  600. With prefix arg SPECIAL, or when no footnote can be created,
  601. offer additional commands in a menu."
  602. (interactive "P")
  603. (let* ((context (and (not special) (org-element-context)))
  604. (type (org-element-type context)))
  605. (cond
  606. ;; On white space after element, insert a new footnote.
  607. ((and context
  608. (> (point)
  609. (save-excursion
  610. (goto-char (org-element-property :end context))
  611. (skip-chars-backward " \t")
  612. (point))))
  613. (org-footnote-new))
  614. ((eq type 'footnote-reference)
  615. (let ((label (org-element-property :label context)))
  616. (cond
  617. ;; Anonymous footnote: move point at the beginning of its
  618. ;; definition.
  619. ((not label)
  620. (goto-char (org-element-property :contents-begin context)))
  621. ;; Check if a definition exists: then move to it.
  622. ((let ((p (nth 1 (org-footnote-get-definition label))))
  623. (when p (org-footnote-goto-definition label p))))
  624. ;; No definition exists: offer to create it.
  625. ((yes-or-no-p (format "No definition for %s. Create one? " label))
  626. (let ((p (org-footnote-create-definition label)))
  627. (or (ignore-errors (org-footnote-goto-definition label p))
  628. ;; Since definition was created outside current scope,
  629. ;; edit it remotely.
  630. (org-edit-footnote-reference)))))))
  631. ((eq type 'footnote-definition)
  632. (org-footnote-goto-previous-reference
  633. (org-element-property :label context)))
  634. ((or special (not (org-footnote--allow-reference-p)))
  635. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | \
  636. ->[n]umeric | [d]elete")
  637. (let ((c (read-char-exclusive)))
  638. (cond
  639. ((eq c ?s) (org-footnote-normalize 'sort))
  640. ((eq c ?r) (org-footnote-renumber-fn:N))
  641. ((eq c ?S)
  642. (org-footnote-renumber-fn:N)
  643. (org-footnote-normalize 'sort))
  644. ((eq c ?n) (org-footnote-normalize))
  645. ((eq c ?d) (org-footnote-delete))
  646. (t (error "No such footnote command %c" c)))))
  647. (t (org-footnote-new)))))
  648. ;;;###autoload
  649. (defun org-footnote-normalize (&optional sort-only)
  650. "Collect the footnotes in various formats and normalize them.
  651. This finds the different sorts of footnotes allowed in Org, and
  652. normalizes them to the usual [N] format.
  653. When SORT-ONLY is set, only sort the footnote definitions into the
  654. referenced sequence."
  655. ;; This is based on Paul's function, but rewritten.
  656. ;;
  657. ;; Re-create `org-with-limited-levels', but not limited to Org
  658. ;; buffers.
  659. (let* ((limit-level
  660. (and (boundp 'org-inlinetask-min-level)
  661. org-inlinetask-min-level
  662. (1- org-inlinetask-min-level)))
  663. (nstars (and limit-level
  664. (if org-odd-levels-only (1- (* limit-level 2))
  665. limit-level)))
  666. (org-outline-regexp
  667. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  668. (count 0)
  669. ins-point ref ref-table)
  670. (org-with-wide-buffer
  671. ;; 1. Find every footnote reference, extract the definition, and
  672. ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
  673. ;; normalize references.
  674. (goto-char (point-min))
  675. (while (setq ref (org-footnote-get-next-reference))
  676. (let* ((lbl (car ref))
  677. (pos (nth 1 ref))
  678. ;; When footnote isn't anonymous, check if it's label
  679. ;; (REF) is already stored in REF-TABLE. In that case,
  680. ;; extract number used to identify it (MARKER). If
  681. ;; footnote is unknown, increment the global counter
  682. ;; (COUNT) to create an unused identifier.
  683. (a (and lbl (assoc lbl ref-table)))
  684. (marker (or (nth 1 a) (incf count)))
  685. ;; Is the reference inline or pointing to an inline
  686. ;; footnote?
  687. (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
  688. ;; Replace footnote reference with [MARKER]. Maybe fill
  689. ;; paragraph once done. If SORT-ONLY is non-nil, only move
  690. ;; to the end of reference found to avoid matching it twice.
  691. (if sort-only (goto-char (nth 2 ref))
  692. (delete-region (nth 1 ref) (nth 2 ref))
  693. (goto-char (nth 1 ref))
  694. (insert (format "[%d]" marker))
  695. (and inlinep
  696. org-footnote-fill-after-inline-note-extraction
  697. (org-fill-paragraph)))
  698. ;; Add label (REF), identifier (MARKER), definition (DEF)
  699. ;; type (INLINEP) and position (POS) to REF-TABLE if data was
  700. ;; unknown.
  701. (unless a
  702. (let ((def (or (nth 3 ref) ; Inline definition.
  703. (nth 3 (org-footnote-get-definition lbl)))))
  704. (push (list lbl marker def
  705. ;; Reference beginning position is a marker
  706. ;; to preserve it during further buffer
  707. ;; modifications.
  708. inlinep (copy-marker pos)) ref-table)))))
  709. ;; 2. Find and remove the footnote section, if any. Also
  710. ;; determine where footnotes shall be inserted (INS-POINT).
  711. (cond
  712. ((and org-footnote-section (derived-mode-p 'org-mode))
  713. (goto-char (point-min))
  714. (if (re-search-forward
  715. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  716. "[ \t]*$") nil t)
  717. (delete-region (match-beginning 0) (org-end-of-subtree t t)))
  718. ;; A new footnote section is inserted by default at the end of
  719. ;; the buffer.
  720. (goto-char (point-max))
  721. (skip-chars-backward " \r\t\n")
  722. (forward-line)
  723. (unless (bolp) (newline)))
  724. ;; No footnote section set: Footnotes will be added at the end
  725. ;; of the section containing their first reference.
  726. ((derived-mode-p 'org-mode))
  727. (t
  728. ;; Remove any left-over tag in the buffer, if one is set up.
  729. (when org-footnote-tag-for-non-org-mode-files
  730. (let ((tag (concat "^" (regexp-quote
  731. org-footnote-tag-for-non-org-mode-files)
  732. "[ \t]*$")))
  733. (goto-char (point-min))
  734. (while (re-search-forward tag nil t)
  735. (replace-match "")
  736. (delete-region (point) (progn (forward-line) (point))))))
  737. ;; In Message mode, ensure footnotes are inserted before the
  738. ;; signature.
  739. (if (and (derived-mode-p 'message-mode)
  740. (goto-char (point-max))
  741. (re-search-backward message-signature-separator nil t))
  742. (beginning-of-line)
  743. (goto-char (point-max)))))
  744. (setq ins-point (point-marker))
  745. ;; 3. Clean-up REF-TABLE.
  746. (setq ref-table
  747. (delq nil
  748. (mapcar
  749. (lambda (x)
  750. (cond
  751. ;; When only sorting, ignore inline footnotes.
  752. ;; Also clear position marker.
  753. ((and sort-only (nth 3 x))
  754. (set-marker (nth 4 x) nil) nil)
  755. ;; No definition available: provide one.
  756. ((not (nth 2 x))
  757. (append
  758. (list (car x) (nth 1 x)
  759. (format "DEFINITION NOT FOUND: %s" (car x)))
  760. (nthcdr 3 x)))
  761. (t x)))
  762. ref-table)))
  763. (setq ref-table (nreverse ref-table))
  764. ;; 4. Remove left-over definitions in the buffer.
  765. (dolist (x ref-table)
  766. (unless (nth 3 x) (org-footnote-delete-definitions (car x))))
  767. ;; 5. Insert the footnotes again in the buffer, at the
  768. ;; appropriate spot.
  769. (goto-char ins-point)
  770. (cond
  771. ;; No footnote: exit.
  772. ((not ref-table))
  773. ;; Cases when footnotes should be inserted in one place.
  774. ((or (not (derived-mode-p 'org-mode)) org-footnote-section)
  775. ;; Insert again the section title, if any. Ensure that title,
  776. ;; or the subsequent footnotes, will be separated by a blank
  777. ;; lines from the rest of the document. In an Org buffer,
  778. ;; separate section with a blank line, unless explicitly stated
  779. ;; in `org-blank-before-new-entry'.
  780. (if (not (derived-mode-p 'org-mode))
  781. (progn (skip-chars-backward " \t\n\r")
  782. (delete-region (point) ins-point)
  783. (unless (bolp) (newline))
  784. (when org-footnote-tag-for-non-org-mode-files
  785. (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
  786. (when (and (cdr (assq 'heading org-blank-before-new-entry))
  787. (zerop (save-excursion (org-back-over-empty-lines))))
  788. (insert "\n"))
  789. (insert "* " org-footnote-section "\n"))
  790. (set-marker ins-point nil)
  791. ;; Insert the footnotes, separated by a blank line.
  792. (insert
  793. (mapconcat
  794. (lambda (x)
  795. ;; Clean markers.
  796. (set-marker (nth 4 x) nil)
  797. (format "\n[%s] %s" (nth (if sort-only 0 1) x) (nth 2 x)))
  798. ref-table "\n"))
  799. (unless (eobp) (insert "\n\n")))
  800. ;; Each footnote definition has to be inserted at the end of the
  801. ;; section where its first reference belongs.
  802. (t
  803. (dolist (x ref-table)
  804. (let ((pos (nth 4 x)))
  805. (goto-char pos)
  806. ;; Clean marker.
  807. (set-marker pos nil))
  808. (org-footnote--goto-local-insertion-point)
  809. (insert (format "\n[%s] %s\n"
  810. (nth (if sort-only 0 1) x)
  811. (nth 2 x)))))))))
  812. (defun org-footnote--goto-local-insertion-point ()
  813. "Find insertion point for footnote, just before next outline heading.
  814. Assume insertion point is within currently accessible part of the buffer."
  815. (org-with-limited-levels (outline-next-heading))
  816. ;; Skip file local variables. See `modify-file-local-variable'.
  817. (when (eobp)
  818. (let ((case-fold-search t))
  819. (re-search-backward "^[ \t]*# +Local Variables:"
  820. (max (- (point-max) 3000) (point-min))
  821. t)))
  822. (skip-chars-backward " \t\n")
  823. (forward-line)
  824. (unless (bolp) (insert "\n")))
  825. (defun org-footnote-delete-references (label)
  826. "Delete every reference to footnote LABEL.
  827. Return the number of footnotes removed."
  828. (save-excursion
  829. (goto-char (point-min))
  830. (let (ref (nref 0))
  831. (while (setq ref (org-footnote-get-next-reference label))
  832. (goto-char (nth 1 ref))
  833. (delete-region (nth 1 ref) (nth 2 ref))
  834. (incf nref))
  835. nref)))
  836. (defun org-footnote-delete-definitions (label)
  837. "Delete every definition of the footnote LABEL.
  838. Return the number of footnotes removed."
  839. (save-excursion
  840. (goto-char (point-min))
  841. (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
  842. (ndef 0))
  843. (while (re-search-forward def-re nil t)
  844. (let ((full-def (org-footnote-at-definition-p)))
  845. (when full-def
  846. ;; Remove the footnote, and all blank lines before it.
  847. (goto-char (nth 1 full-def))
  848. (skip-chars-backward " \r\t\n")
  849. (unless (bolp) (forward-line))
  850. (delete-region (point) (nth 2 full-def))
  851. (incf ndef))))
  852. ndef)))
  853. (defun org-footnote-delete (&optional label)
  854. "Delete the footnote at point.
  855. This will remove the definition (even multiple definitions if they exist)
  856. and all references of a footnote label.
  857. If LABEL is non-nil, delete that footnote instead."
  858. (catch 'done
  859. (let* ((nref 0) (ndef 0) x
  860. ;; 1. Determine LABEL of footnote at point.
  861. (label (cond
  862. ;; LABEL is provided as argument.
  863. (label)
  864. ;; Footnote reference at point. If the footnote is
  865. ;; anonymous, delete it and exit instead.
  866. ((setq x (org-footnote-at-reference-p))
  867. (or (car x)
  868. (progn
  869. (delete-region (nth 1 x) (nth 2 x))
  870. (message "Anonymous footnote removed")
  871. (throw 'done t))))
  872. ;; Footnote definition at point.
  873. ((setq x (org-footnote-at-definition-p))
  874. (car x))
  875. (t (error "Don't know which footnote to remove")))))
  876. ;; 2. Now that LABEL is non-nil, find every reference and every
  877. ;; definition, and delete them.
  878. (setq nref (org-footnote-delete-references label)
  879. ndef (org-footnote-delete-definitions label))
  880. ;; 3. Verify consistency of footnotes and notify user.
  881. (org-footnote-auto-adjust-maybe)
  882. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  883. ndef nref label))))
  884. (defun org-footnote-renumber-fn:N ()
  885. "Renumber the simple footnotes like fn:17 into a sequence in the document."
  886. (interactive)
  887. (let (map (n 0))
  888. (org-with-wide-buffer
  889. (goto-char (point-min))
  890. (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
  891. (save-excursion
  892. (goto-char (match-beginning 0))
  893. ;; Ensure match is a footnote reference or definition.
  894. (when (save-match-data (if (bolp)
  895. (org-footnote-at-definition-p)
  896. (org-footnote-at-reference-p)))
  897. (let ((new-val (or (cdr (assoc (match-string 1) map))
  898. (number-to-string (incf n)))))
  899. (unless (assoc (match-string 1) map)
  900. (push (cons (match-string 1) new-val) map))
  901. (replace-match new-val nil nil nil 1))))))))
  902. (defun org-footnote-auto-adjust-maybe ()
  903. "Renumber and/or sort footnotes according to user settings."
  904. (when (memq org-footnote-auto-adjust '(t renumber))
  905. (org-footnote-renumber-fn:N))
  906. (when (memq org-footnote-auto-adjust '(t sort))
  907. (let ((label (car (org-footnote-at-definition-p))))
  908. (org-footnote-normalize 'sort)
  909. (when label
  910. (goto-char (point-min))
  911. (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
  912. nil t)
  913. (progn (insert " ")
  914. (just-one-space)))))))
  915. (provide 'org-footnote)
  916. ;; Local variables:
  917. ;; generated-autoload-file: "org-loaddefs.el"
  918. ;; End:
  919. ;;; org-footnote.el ends here