org-footnote.el 36 KB

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