org-footnote.el 35 KB

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