org-footnote.el 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. ;;; org-footnote.el --- Footnote support in Org and elsewhere
  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. (org-footnote-create-definition label)
  505. (org-footnote-auto-adjust-maybe)
  506. (if (ignore-errors (org-footnote-goto-definition label))
  507. (forward-char)
  508. ;; Definition was created outside current scope: edit it
  509. ;; remotely.
  510. (org-edit-footnote-reference))))))
  511. (defvar org-blank-before-new-entry) ; Silence byte-compiler.
  512. (defun org-footnote-create-definition (label)
  513. "Start the definition of a footnote with label LABEL.
  514. Return buffer position at the beginning of the definition. In an
  515. Org buffer, this function doesn't move point."
  516. (let ((label (org-footnote-normalize-label label))
  517. electric-indent-mode) ; Prevent wrong indentation.
  518. (cond
  519. ;; In an Org document.
  520. ((derived-mode-p 'org-mode)
  521. ;; If `org-footnote-section' is defined, find it, or create it
  522. ;; at the end of the buffer.
  523. (org-with-wide-buffer
  524. (cond
  525. ((not org-footnote-section)
  526. (org-footnote--goto-local-insertion-point))
  527. ((save-excursion
  528. (goto-char (point-min))
  529. (re-search-forward
  530. (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section) "[ \t]*$")
  531. nil t))
  532. (goto-char (match-end 0))
  533. (forward-line)
  534. (unless (bolp) (insert "\n")))
  535. (t
  536. (goto-char (point-max))
  537. (unless (bolp) (insert "\n"))
  538. ;; Insert new section. Separate it from the previous one
  539. ;; with a blank line, unless `org-blank-before-new-entry'
  540. ;; explicitly says no.
  541. (when (and (cdr (assq 'heading org-blank-before-new-entry))
  542. (zerop (save-excursion (org-back-over-empty-lines))))
  543. (insert "\n"))
  544. (insert "* " org-footnote-section "\n")))
  545. (when (zerop (org-back-over-empty-lines)) (insert "\n"))
  546. (insert "[" label "] \n")
  547. (line-beginning-position 0)))
  548. (t
  549. ;; In a non-Org file. Search for footnote tag, or create it if
  550. ;; specified (at the end of buffer, or before signature if in
  551. ;; Message mode). Set point after any definition already there.
  552. (let ((tag (and org-footnote-tag-for-non-org-mode-files
  553. (concat "^" (regexp-quote
  554. org-footnote-tag-for-non-org-mode-files)
  555. "[ \t]*$")))
  556. (max (if (and (derived-mode-p 'message-mode)
  557. (goto-char (point-max))
  558. (re-search-backward
  559. message-signature-separator nil t))
  560. (progn
  561. ;; Ensure one blank line separates last
  562. ;; footnote from signature.
  563. (beginning-of-line)
  564. (open-line 2)
  565. (point-marker))
  566. (point-max-marker))))
  567. (set-marker-insertion-type max t)
  568. (goto-char max)
  569. ;; Check if the footnote tag is defined but missing. In this
  570. ;; case, insert it, before any footnote or one blank line
  571. ;; after any previous text.
  572. (when (and tag (not (re-search-backward tag nil t)))
  573. (skip-chars-backward " \t\r\n")
  574. (while (re-search-backward org-footnote-definition-re nil t))
  575. (unless (bolp) (newline 2))
  576. (insert org-footnote-tag-for-non-org-mode-files "\n\n"))
  577. ;; Remove superfluous white space and clear marker.
  578. (goto-char max)
  579. (skip-chars-backward " \t\r\n")
  580. (delete-region (point) max)
  581. (unless (bolp) (newline))
  582. (set-marker max nil))
  583. (when (zerop (org-back-over-empty-lines)) (insert "\n"))
  584. (insert "[" label "] \n")
  585. (backward-char)
  586. (line-beginning-position)))))
  587. ;;;###autoload
  588. (defun org-footnote-action (&optional special)
  589. "Do the right thing for footnotes.
  590. When at a footnote reference, jump to the definition.
  591. When at a definition, jump to the references if they exist, offer
  592. to create them otherwise.
  593. When neither at definition or reference, create a new footnote,
  594. interactively if possible.
  595. With prefix arg SPECIAL, or when no footnote can be created,
  596. offer additional commands in a menu."
  597. (interactive "P")
  598. (let* ((context (and (not special) (org-element-context)))
  599. (type (org-element-type context)))
  600. (cond
  601. ((eq type 'footnote-reference)
  602. (let ((label (org-element-property :label context)))
  603. (cond
  604. ;; Anonymous footnote: move point at the beginning of its
  605. ;; definition.
  606. ((not label)
  607. (goto-char (org-element-property :contents-begin context)))
  608. ;; Check if a definition exists: then move to it.
  609. ((let ((p (nth 1 (org-footnote-get-definition label))))
  610. (when p (org-footnote-goto-definition label p))))
  611. ;; No definition exists: offer to create it.
  612. ((yes-or-no-p (format "No definition for %s. Create one? " label))
  613. (let ((p (org-footnote-create-definition label)))
  614. (or (ignore-errors (org-footnote-goto-definition label p))
  615. ;; Since definition was created outside current scope,
  616. ;; edit it remotely.
  617. (org-edit-footnote-reference)))))))
  618. ((eq type 'footnote-definition)
  619. (org-footnote-goto-previous-reference
  620. (org-element-property :label context)))
  621. ((or special (not (org-footnote--allow-reference-p)))
  622. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | \
  623. ->[n]umeric | [d]elete")
  624. (let ((c (read-char-exclusive)))
  625. (cond
  626. ((eq c ?s) (org-footnote-normalize 'sort))
  627. ((eq c ?r) (org-footnote-renumber-fn:N))
  628. ((eq c ?S)
  629. (org-footnote-renumber-fn:N)
  630. (org-footnote-normalize 'sort))
  631. ((eq c ?n) (org-footnote-normalize))
  632. ((eq c ?d) (org-footnote-delete))
  633. (t (error "No such footnote command %c" c)))))
  634. (t (org-footnote-new)))))
  635. ;;;###autoload
  636. (defun org-footnote-normalize (&optional sort-only)
  637. "Collect the footnotes in various formats and normalize them.
  638. This finds the different sorts of footnotes allowed in Org, and
  639. normalizes them to the usual [N] format.
  640. When SORT-ONLY is set, only sort the footnote definitions into the
  641. referenced sequence."
  642. ;; This is based on Paul's function, but rewritten.
  643. ;;
  644. ;; Re-create `org-with-limited-levels', but not limited to Org
  645. ;; buffers.
  646. (let* ((limit-level
  647. (and (boundp 'org-inlinetask-min-level)
  648. org-inlinetask-min-level
  649. (1- org-inlinetask-min-level)))
  650. (nstars (and limit-level
  651. (if org-odd-levels-only (1- (* limit-level 2))
  652. limit-level)))
  653. (org-outline-regexp
  654. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  655. (count 0)
  656. ins-point ref ref-table)
  657. (org-with-wide-buffer
  658. ;; 1. Find every footnote reference, extract the definition, and
  659. ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
  660. ;; normalize references.
  661. (goto-char (point-min))
  662. (while (setq ref (org-footnote-get-next-reference))
  663. (let* ((lbl (car ref))
  664. (pos (nth 1 ref))
  665. ;; When footnote isn't anonymous, check if it's label
  666. ;; (REF) is already stored in REF-TABLE. In that case,
  667. ;; extract number used to identify it (MARKER). If
  668. ;; footnote is unknown, increment the global counter
  669. ;; (COUNT) to create an unused identifier.
  670. (a (and lbl (assoc lbl ref-table)))
  671. (marker (or (nth 1 a) (incf count)))
  672. ;; Is the reference inline or pointing to an inline
  673. ;; footnote?
  674. (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
  675. ;; Replace footnote reference with [MARKER]. Maybe fill
  676. ;; paragraph once done. If SORT-ONLY is non-nil, only move
  677. ;; to the end of reference found to avoid matching it twice.
  678. (if sort-only (goto-char (nth 2 ref))
  679. (delete-region (nth 1 ref) (nth 2 ref))
  680. (goto-char (nth 1 ref))
  681. (insert (format "[%d]" marker))
  682. (and inlinep
  683. org-footnote-fill-after-inline-note-extraction
  684. (org-fill-paragraph)))
  685. ;; Add label (REF), identifier (MARKER), definition (DEF)
  686. ;; type (INLINEP) and position (POS) to REF-TABLE if data was
  687. ;; unknown.
  688. (unless a
  689. (let ((def (or (nth 3 ref) ; Inline definition.
  690. (nth 3 (org-footnote-get-definition lbl)))))
  691. (push (list lbl marker def
  692. ;; Reference beginning position is a marker
  693. ;; to preserve it during further buffer
  694. ;; modifications.
  695. inlinep (copy-marker pos)) ref-table)))))
  696. ;; 2. Find and remove the footnote section, if any. Also
  697. ;; determine where footnotes shall be inserted (INS-POINT).
  698. (cond
  699. ((and org-footnote-section (derived-mode-p 'org-mode))
  700. (goto-char (point-min))
  701. (if (re-search-forward
  702. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  703. "[ \t]*$") nil t)
  704. (delete-region (match-beginning 0) (org-end-of-subtree t t)))
  705. ;; A new footnote section is inserted by default at the end of
  706. ;; the buffer.
  707. (goto-char (point-max))
  708. (skip-chars-backward " \r\t\n")
  709. (forward-line)
  710. (unless (bolp) (newline)))
  711. ;; No footnote section set: Footnotes will be added at the end
  712. ;; of the section containing their first reference.
  713. ((derived-mode-p 'org-mode))
  714. (t
  715. ;; Remove any left-over tag in the buffer, if one is set up.
  716. (when org-footnote-tag-for-non-org-mode-files
  717. (let ((tag (concat "^" (regexp-quote
  718. org-footnote-tag-for-non-org-mode-files)
  719. "[ \t]*$")))
  720. (goto-char (point-min))
  721. (while (re-search-forward tag nil t)
  722. (replace-match "")
  723. (delete-region (point) (progn (forward-line) (point))))))
  724. ;; In Message mode, ensure footnotes are inserted before the
  725. ;; signature.
  726. (if (and (derived-mode-p 'message-mode)
  727. (goto-char (point-max))
  728. (re-search-backward message-signature-separator nil t))
  729. (beginning-of-line)
  730. (goto-char (point-max)))))
  731. (setq ins-point (point-marker))
  732. ;; 3. Clean-up REF-TABLE.
  733. (setq ref-table
  734. (delq nil
  735. (mapcar
  736. (lambda (x)
  737. (cond
  738. ;; When only sorting, ignore inline footnotes.
  739. ;; Also clear position marker.
  740. ((and sort-only (nth 3 x))
  741. (set-marker (nth 4 x) nil) nil)
  742. ;; No definition available: provide one.
  743. ((not (nth 2 x))
  744. (append
  745. (list (car x) (nth 1 x)
  746. (format "DEFINITION NOT FOUND: %s" (car x)))
  747. (nthcdr 3 x)))
  748. (t x)))
  749. ref-table)))
  750. (setq ref-table (nreverse ref-table))
  751. ;; 4. Remove left-over definitions in the buffer.
  752. (dolist (x ref-table)
  753. (unless (nth 3 x) (org-footnote-delete-definitions (car x))))
  754. ;; 5. Insert the footnotes again in the buffer, at the
  755. ;; appropriate spot.
  756. (goto-char ins-point)
  757. (cond
  758. ;; No footnote: exit.
  759. ((not ref-table))
  760. ;; Cases when footnotes should be inserted in one place.
  761. ((or (not (derived-mode-p 'org-mode)) org-footnote-section)
  762. ;; Insert again the section title, if any. Ensure that title,
  763. ;; or the subsequent footnotes, will be separated by a blank
  764. ;; lines from the rest of the document. In an Org buffer,
  765. ;; separate section with a blank line, unless explicitly stated
  766. ;; in `org-blank-before-new-entry'.
  767. (if (not (derived-mode-p 'org-mode))
  768. (progn (skip-chars-backward " \t\n\r")
  769. (delete-region (point) ins-point)
  770. (unless (bolp) (newline))
  771. (when org-footnote-tag-for-non-org-mode-files
  772. (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
  773. (when (and (cdr (assq 'heading org-blank-before-new-entry))
  774. (zerop (save-excursion (org-back-over-empty-lines))))
  775. (insert "\n"))
  776. (insert "* " org-footnote-section "\n"))
  777. (set-marker ins-point nil)
  778. ;; Insert the footnotes, separated by a blank line.
  779. (insert
  780. (mapconcat
  781. (lambda (x)
  782. ;; Clean markers.
  783. (set-marker (nth 4 x) nil)
  784. (format "\n[%s] %s" (nth (if sort-only 0 1) x) (nth 2 x)))
  785. ref-table "\n"))
  786. (unless (eobp) (insert "\n\n")))
  787. ;; Each footnote definition has to be inserted at the end of the
  788. ;; section where its first reference belongs.
  789. (t
  790. (dolist (x ref-table)
  791. (let ((pos (nth 4 x)))
  792. (goto-char pos)
  793. ;; Clean marker.
  794. (set-marker pos nil))
  795. (org-footnote--goto-local-insertion-point)
  796. (insert (format "\n[%s] %s\n"
  797. (nth (if sort-only 0 1) x)
  798. (nth 2 x)))))))))
  799. (defun org-footnote--goto-local-insertion-point ()
  800. "Find insertion point for footnote, just before next outline heading.
  801. Assume insertion point is within currently accessible part of the buffer."
  802. (org-with-limited-levels (outline-next-heading))
  803. ;; Skip file local variables. See `modify-file-local-variable'.
  804. (when (eobp)
  805. (let ((case-fold-search t))
  806. (re-search-backward "^[ \t]*# +Local Variables:"
  807. (max (- (point-max) 3000) (point-min))
  808. t)))
  809. (skip-chars-backward " \t\n")
  810. (forward-line)
  811. (unless (bolp) (insert "\n")))
  812. (defun org-footnote-delete-references (label)
  813. "Delete every reference to footnote LABEL.
  814. Return the number of footnotes removed."
  815. (save-excursion
  816. (goto-char (point-min))
  817. (let (ref (nref 0))
  818. (while (setq ref (org-footnote-get-next-reference label))
  819. (goto-char (nth 1 ref))
  820. (delete-region (nth 1 ref) (nth 2 ref))
  821. (incf nref))
  822. nref)))
  823. (defun org-footnote-delete-definitions (label)
  824. "Delete every definition of the footnote LABEL.
  825. Return the number of footnotes removed."
  826. (save-excursion
  827. (goto-char (point-min))
  828. (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
  829. (ndef 0))
  830. (while (re-search-forward def-re nil t)
  831. (let ((full-def (org-footnote-at-definition-p)))
  832. (when full-def
  833. ;; Remove the footnote, and all blank lines before it.
  834. (goto-char (nth 1 full-def))
  835. (skip-chars-backward " \r\t\n")
  836. (unless (bolp) (forward-line))
  837. (delete-region (point) (nth 2 full-def))
  838. (incf ndef))))
  839. ndef)))
  840. (defun org-footnote-delete (&optional label)
  841. "Delete the footnote at point.
  842. This will remove the definition (even multiple definitions if they exist)
  843. and all references of a footnote label.
  844. If LABEL is non-nil, delete that footnote instead."
  845. (catch 'done
  846. (let* ((nref 0) (ndef 0) x
  847. ;; 1. Determine LABEL of footnote at point.
  848. (label (cond
  849. ;; LABEL is provided as argument.
  850. (label)
  851. ;; Footnote reference at point. If the footnote is
  852. ;; anonymous, delete it and exit instead.
  853. ((setq x (org-footnote-at-reference-p))
  854. (or (car x)
  855. (progn
  856. (delete-region (nth 1 x) (nth 2 x))
  857. (message "Anonymous footnote removed")
  858. (throw 'done t))))
  859. ;; Footnote definition at point.
  860. ((setq x (org-footnote-at-definition-p))
  861. (car x))
  862. (t (error "Don't know which footnote to remove")))))
  863. ;; 2. Now that LABEL is non-nil, find every reference and every
  864. ;; definition, and delete them.
  865. (setq nref (org-footnote-delete-references label)
  866. ndef (org-footnote-delete-definitions label))
  867. ;; 3. Verify consistency of footnotes and notify user.
  868. (org-footnote-auto-adjust-maybe)
  869. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  870. ndef nref label))))
  871. (defun org-footnote-renumber-fn:N ()
  872. "Renumber the simple footnotes like fn:17 into a sequence in the document."
  873. (interactive)
  874. (let (map (n 0))
  875. (org-with-wide-buffer
  876. (goto-char (point-min))
  877. (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
  878. (save-excursion
  879. (goto-char (match-beginning 0))
  880. ;; Ensure match is a footnote reference or definition.
  881. (when (save-match-data (if (bolp)
  882. (org-footnote-at-definition-p)
  883. (org-footnote-at-reference-p)))
  884. (let ((new-val (or (cdr (assoc (match-string 1) map))
  885. (number-to-string (incf n)))))
  886. (unless (assoc (match-string 1) map)
  887. (push (cons (match-string 1) new-val) map))
  888. (replace-match new-val nil nil nil 1))))))))
  889. (defun org-footnote-auto-adjust-maybe ()
  890. "Renumber and/or sort footnotes according to user settings."
  891. (when (memq org-footnote-auto-adjust '(t renumber))
  892. (org-footnote-renumber-fn:N))
  893. (when (memq org-footnote-auto-adjust '(t sort))
  894. (let ((label (car (org-footnote-at-definition-p))))
  895. (org-footnote-normalize 'sort)
  896. (when label
  897. (goto-char (point-min))
  898. (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
  899. nil t)
  900. (progn (insert " ")
  901. (just-one-space)))))))
  902. (provide 'org-footnote)
  903. ;; Local variables:
  904. ;; generated-autoload-file: "org-loaddefs.el"
  905. ;; End:
  906. ;;; org-footnote.el ends here