org-footnote.el 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. ;;; org-footnote.el --- Footnote support in Org and elsewhere
  2. ;;
  3. ;; Copyright (C) 2009, 2010 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. ;; Version: 7.7
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  23. ;;
  24. ;;; Commentary:
  25. ;; This file contains the code dealing with footnotes in Org-mode.
  26. ;; The code can also be used in arbitrary text modes to provide
  27. ;; footnotes. Compared to Steven L Baur's footnote.el it provides
  28. ;; better support for resuming editing. It is less configurable than
  29. ;; Steve's code, though.
  30. ;;; Code:
  31. (eval-when-compile
  32. (require 'cl))
  33. (require 'org-macs)
  34. (require 'org-compat)
  35. (declare-function org-combine-plists "org" (&rest plists))
  36. (declare-function org-in-commented-line "org" ())
  37. (declare-function org-in-indented-comment-line "org" ())
  38. (declare-function org-in-regexp "org" (re &optional nlines visually))
  39. (declare-function org-in-block-p "org" (names))
  40. (declare-function org-mark-ring-push "org" (&optional pos buffer))
  41. (declare-function outline-next-heading "outline")
  42. (declare-function org-trim "org" (s))
  43. (declare-function org-show-context "org" (&optional key))
  44. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  45. (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
  46. (declare-function org-in-verbatim-emphasis "org" ())
  47. (declare-function org-inside-latex-macro-p "org" ())
  48. (declare-function org-id-uuid "org" ())
  49. (declare-function org-fill-paragraph "org" (&optional justify))
  50. (declare-function org-export-preprocess-string "org-exp"
  51. (string &rest parameters))
  52. (defvar org-outline-regexp-bol) ; defined in org.el
  53. (defvar org-odd-levels-only) ;; defined in org.el
  54. (defvar org-bracket-link-regexp) ; defined in org.el
  55. (defvar message-signature-separator) ;; defined in message.el
  56. (defconst org-footnote-re
  57. ;; Only [1]-like footnotes are closed in this regexp, as footnotes
  58. ;; from other types might contain square brackets (i.e. links) in
  59. ;; their definition.
  60. ;;
  61. ;; `org-re' is used for regexp compatibility with XEmacs.
  62. (org-re (concat "\\[\\(?:"
  63. ;; Match inline footnotes.
  64. "fn:\\([-_[:word:]]+\\)?:\\|"
  65. ;; Match other footnotes.
  66. "\\(?:\\([0-9]+\\)\\]\\)\\|"
  67. "\\(fn:[-_[:word:]]+\\)"
  68. "\\)"))
  69. "Regular expression for matching footnotes.")
  70. (defconst org-footnote-definition-re
  71. (org-re "^\\(\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]\\)")
  72. "Regular expression matching the definition of a footnote.")
  73. (defvar org-footnote-forbidden-blocks '("example" "verse" "src" "ascii" "beamer"
  74. "docbook" "html" "latex" "odt")
  75. "Names of blocks where footnotes are not allowed.")
  76. (defgroup org-footnote nil
  77. "Footnotes in Org-mode."
  78. :tag "Org Footnote"
  79. :group 'org)
  80. (defcustom org-footnote-section "Footnotes"
  81. "Outline heading containing footnote definitions before export.
  82. This can be nil, to place footnotes locally at the end of the current
  83. outline node. If can also be the name of a special outline heading
  84. under which footnotes should be put.
  85. This variable defines the place where Org puts the definition
  86. automatically, i.e. when creating the footnote, and when sorting the notes.
  87. However, by hand you may place definitions *anywhere*.
  88. If this is a string, during export, all subtrees starting with this
  89. heading will be removed after extracting footnote definitions."
  90. :group 'org-footnote
  91. :type '(choice
  92. (string :tag "Collect footnotes under heading")
  93. (const :tag "Define footnotes locally" nil)))
  94. (defcustom org-footnote-tag-for-non-org-mode-files "Footnotes:"
  95. "Tag marking the beginning of footnote section.
  96. The Org-mode footnote engine can be used in arbitrary text files as well
  97. as in Org-mode. Outside Org-mode, new footnotes are always placed at
  98. the end of the file. When you normalize the notes, any line containing
  99. only this tag will be removed, a new one will be inserted at the end
  100. of the file, followed by the collected and normalized footnotes."
  101. :group 'org-footnote
  102. :type 'string)
  103. (defcustom org-footnote-define-inline nil
  104. "Non-nil means define footnotes inline, at reference location.
  105. When nil, footnotes will be defined in a special section near
  106. the end of the document. When t, the [fn:label:definition] notation
  107. will be used to define the footnote at the reference position."
  108. :group 'org-footnote
  109. :type 'boolean)
  110. (defcustom org-footnote-auto-label t
  111. "Non-nil means define automatically new labels for footnotes.
  112. Possible values are:
  113. nil prompt the user for each label
  114. t create unique labels of the form [fn:1], [fn:2], ...
  115. confirm like t, but let the user edit the created value. In particular,
  116. the label can be removed from the minibuffer, to create
  117. an anonymous footnote.
  118. random Automatically generate a unique, random label.
  119. plain Automatically create plain number labels like [1]"
  120. :group 'org-footnote
  121. :type '(choice
  122. (const :tag "Prompt for label" nil)
  123. (const :tag "Create automatic [fn:N]" t)
  124. (const :tag "Offer automatic [fn:N] for editing" confirm)
  125. (const :tag "Create a random label" random)
  126. (const :tag "Create automatic [N]" plain)))
  127. (defcustom org-footnote-auto-adjust nil
  128. "Non-nil means automatically adjust footnotes after insert/delete.
  129. When this is t, after each insertion or deletion of a footnote,
  130. simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
  131. If you want to have just sorting or just renumbering, set this variable
  132. to `sort' or `renumber'.
  133. The main values of this variable can be set with in-buffer options:
  134. #+STARTUP: fnadjust
  135. #+STARTUP: nofnadjust"
  136. :group 'org-footnote
  137. :type '(choice
  138. (const :tag "Renumber" renumber)
  139. (const :tag "Sort" sort)
  140. (const :tag "Renumber and Sort" t)))
  141. (defcustom org-footnote-fill-after-inline-note-extraction nil
  142. "Non-nil means fill paragraphs after extracting footnotes.
  143. When extracting inline footnotes, the lengths of lines can change a lot.
  144. When this option is set, paragraphs from which an inline footnote has been
  145. extracted will be filled again."
  146. :group 'org-footnote
  147. :type 'boolean)
  148. (defun org-footnote-in-valid-context-p ()
  149. "Is point in a context where footnotes are allowed?"
  150. (save-match-data
  151. (not (or (org-in-commented-line)
  152. (org-in-indented-comment-line)
  153. (org-in-verbatim-emphasis)
  154. ;; Avoid literal example.
  155. (save-excursion
  156. (beginning-of-line)
  157. (looking-at "[ \t]*:[ \t]+"))
  158. ;; Avoid cited text and headers in message-mode.
  159. (and (derived-mode-p 'message-mode)
  160. (or (save-excursion
  161. (beginning-of-line)
  162. (looking-at message-cite-prefix-regexp))
  163. (message-point-in-header-p)))
  164. ;; Avoid forbidden blocks.
  165. (org-in-block-p org-footnote-forbidden-blocks)))))
  166. (defun org-footnote-at-reference-p ()
  167. "Is the cursor at a footnote reference?
  168. If so, return a list containing its label, beginning and ending
  169. positions, and the definition, when inlined."
  170. (when (and (org-footnote-in-valid-context-p)
  171. (or (looking-at org-footnote-re)
  172. (org-in-regexp org-footnote-re)
  173. (save-excursion (re-search-backward org-footnote-re nil t)))
  174. ;; Only inline footnotes can start at bol.
  175. (or (eq (char-before (match-end 0)) 58)
  176. (/= (match-beginning 0) (point-at-bol))))
  177. (let* ((beg (match-beginning 0))
  178. (label (or (match-string 2) (match-string 3)
  179. ;; Anonymous footnotes don't have labels
  180. (and (match-string 1) (concat "fn:" (match-string 1)))))
  181. ;; Inline footnotes don't end at (match-end 0) as
  182. ;; `org-footnote-re' stops just after the second colon.
  183. ;; Find the real ending with `scan-sexps', so Org doesn't
  184. ;; get fooled by unrelated closing square brackets.
  185. (end (ignore-errors (scan-sexps beg 1))))
  186. ;; Point is really at a reference if it's located before true
  187. ;; ending of the footnote.
  188. (when (and end (< (point) end)
  189. ;; Verify match isn't a part of a link.
  190. (not (save-excursion
  191. (goto-char beg)
  192. (let ((linkp
  193. (save-match-data
  194. (org-in-regexp org-bracket-link-regexp))))
  195. (and linkp (< (point) (cdr linkp))))))
  196. ;; Verify point doesn't belong to a LaTeX macro.
  197. ;; Beware though, when two footnotes are side by
  198. ;; side, once the first one is changed into LaTeX,
  199. ;; the second one might then be considered as an
  200. ;; optional argument of the command. Thus, check
  201. ;; the `org-protected' property of that command.
  202. (or (not (org-inside-latex-macro-p))
  203. (and (get-text-property (1- beg) 'org-protected)
  204. (not (get-text-property beg 'org-protected)))))
  205. (list label beg end
  206. ;; Definition: ensure this is an inline footnote first.
  207. (and (or (not label) (match-string 1))
  208. (org-trim (buffer-substring (match-end 0) (1- end)))))))))
  209. (defun org-footnote-at-definition-p ()
  210. "Is the cursor at a footnote definition?
  211. This matches only pure definitions like [1] or [fn:name] at the beginning
  212. of a line. It does not match references like [fn:name:definition], where the
  213. footnote text is included and defined locally.
  214. The return value will be nil if not at a footnote definition, and a list with
  215. label, start, end and definition of the footnote otherwise."
  216. (when (org-footnote-in-valid-context-p)
  217. (save-excursion
  218. (end-of-line)
  219. (let ((lim (save-excursion (re-search-backward
  220. (concat org-outline-regexp-bol
  221. "\\|^[ \t]*$") nil t))))
  222. (when (re-search-backward org-footnote-definition-re lim t)
  223. (end-of-line)
  224. (list (match-string 2)
  225. (match-beginning 0)
  226. (save-match-data
  227. ;; In a message, limit search to signature.
  228. (let ((bound (and (derived-mode-p 'message-mode)
  229. (save-excursion
  230. (goto-char (point-max))
  231. (re-search-backward
  232. message-signature-separator nil t)))))
  233. (or (and (re-search-forward
  234. (org-re
  235. (concat "^[ \t]*$" "\\|"
  236. org-outline-regexp-bol
  237. "\\|"
  238. "^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]"))
  239. bound 'move)
  240. (progn (skip-chars-forward " \t\n") (point-at-bol)))
  241. (point))))
  242. (org-trim (buffer-substring (match-end 0) (point)))))))))
  243. (defun org-footnote-get-next-reference (&optional label backward limit)
  244. "Return complete reference of the next footnote.
  245. If LABEL is provided, get the next reference of that footnote. If
  246. BACKWARD is non-nil, find previous reference instead. LIMIT is
  247. the buffer position bounding the search.
  248. Return value is a list like those provided by `org-footnote-at-reference-p'.
  249. If no footnote is found, return nil."
  250. (save-excursion
  251. (let* ((label-fmt (if label (format "\\[%s[]:]" label) org-footnote-re)))
  252. (catch 'exit
  253. (while t
  254. (unless (funcall (if backward #'re-search-backward #'re-search-forward)
  255. label-fmt limit t)
  256. (throw 'exit nil))
  257. (unless backward (backward-char))
  258. (let ((ref (org-footnote-at-reference-p)))
  259. (when ref (throw 'exit ref))))))))
  260. (defun org-footnote-next-reference-or-definition (limit)
  261. "Move point to next footnote reference or definition.
  262. LIMIT is the buffer position bounding the search.
  263. Return value is a list like those provided by
  264. `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
  265. If no footnote is found, return nil."
  266. (let* (ref)
  267. (catch 'exit
  268. (while t
  269. (unless (re-search-forward org-footnote-re limit t)
  270. (throw 'exit nil))
  271. ;; Beware: with [1]-like footnotes point will be just after
  272. ;; the closing square bracket.
  273. (backward-char)
  274. (cond
  275. ((setq ref (org-footnote-at-reference-p))
  276. (throw 'exit ref))
  277. ;; Definition: also grab the last square bracket, only
  278. ;; matched in `org-footnote-re' for [1]-like footnotes.
  279. ((save-match-data (org-footnote-at-definition-p))
  280. (let ((end (match-end 0)))
  281. (throw 'exit
  282. (list nil (match-beginning 0)
  283. (if (eq (char-before end) 93) end (1+ end)))))))))))
  284. (defun org-footnote-get-definition (label)
  285. "Return label, boundaries and definition of the footnote LABEL."
  286. (let* ((label (regexp-quote (org-footnote-normalize-label label)))
  287. (re (format "^\\[%s\\]\\|.\\[%s:" label label))
  288. pos)
  289. (save-excursion
  290. (when (or (re-search-forward re nil t)
  291. (and (goto-char (point-min))
  292. (re-search-forward re nil t))
  293. (and (progn (widen) t)
  294. (goto-char (point-min))
  295. (re-search-forward re nil t)))
  296. (let ((refp (org-footnote-at-reference-p)))
  297. (cond
  298. ((and (nth 3 refp) refp))
  299. ((org-footnote-at-definition-p))))))))
  300. (defun org-footnote-goto-definition (label)
  301. "Move point to the definition of the footnote LABEL."
  302. (interactive "sLabel: ")
  303. (org-mark-ring-push)
  304. (let ((def (org-footnote-get-definition label)))
  305. (if (not def)
  306. (error "Cannot find definition of footnote %s" label)
  307. (goto-char (nth 1 def))
  308. (looking-at (format "\\[%s\\]\\|\\[%s:" label label))
  309. (goto-char (match-end 0))
  310. (org-show-context 'link-search)
  311. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
  312. (defun org-footnote-goto-previous-reference (label)
  313. "Find the first closest (to point) reference of footnote with label LABEL."
  314. (interactive "sLabel: ")
  315. (org-mark-ring-push)
  316. (let* ((label (org-footnote-normalize-label label)) ref)
  317. (save-excursion
  318. (setq ref (or (org-footnote-get-next-reference label t)
  319. (org-footnote-get-next-reference label)
  320. (save-restriction
  321. (widen)
  322. (or
  323. (org-footnote-get-next-reference label t)
  324. (org-footnote-get-next-reference label))))))
  325. (if (not ref)
  326. (error "Cannot find reference of footnote %s" label)
  327. (goto-char (nth 1 ref))
  328. (org-show-context 'link-search))))
  329. (defun org-footnote-normalize-label (label)
  330. "Return LABEL as an appropriate string."
  331. (cond
  332. ((numberp label) (number-to-string label))
  333. ((equal "" label) nil)
  334. ((not (string-match "^[0-9]+$\\|^fn:" label))
  335. (concat "fn:" label))
  336. (t label)))
  337. (defun org-footnote-all-labels (&optional with-defs)
  338. "Return list with all defined foot labels used in the buffer.
  339. If WITH-DEFS is non-nil, also associate the definition to each
  340. label. The function will then return an alist whose key is label
  341. and value definition."
  342. (let* (rtn
  343. (push-to-rtn
  344. (function
  345. ;; Depending on WITH-DEFS, store label or (label . def) of
  346. ;; footnote reference/definition given as argument in RTN.
  347. (lambda (el)
  348. (let ((lbl (car el)))
  349. (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
  350. (save-excursion
  351. (save-restriction
  352. (widen)
  353. ;; Find all labels found in definitions.
  354. (goto-char (point-min))
  355. (let (def)
  356. (while (re-search-forward org-footnote-definition-re nil t)
  357. (when (setq def (org-footnote-at-definition-p))
  358. (funcall push-to-rtn def))))
  359. ;; Find all labels found in references.
  360. (goto-char (point-min))
  361. (let (ref)
  362. (while (setq ref (org-footnote-get-next-reference))
  363. (goto-char (nth 2 ref))
  364. (and (car ref) ; ignore anonymous footnotes
  365. (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
  366. (funcall push-to-rtn ref))))))
  367. rtn))
  368. (defun org-footnote-unique-label (&optional current)
  369. "Return a new unique footnote label.
  370. The returns the firsts fn:N labels that is currently not used."
  371. (unless current (setq current (org-footnote-all-labels)))
  372. (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
  373. (cnt 1))
  374. (while (member (format fmt cnt) current)
  375. (incf cnt))
  376. (format fmt cnt)))
  377. (defvar org-footnote-label-history nil
  378. "History of footnote labels entered in current buffer.")
  379. (make-variable-buffer-local 'org-footnote-label-history)
  380. (defun org-footnote-new ()
  381. "Insert a new footnote.
  382. This command prompts for a label. If this is a label referencing an
  383. existing label, only insert the label. If the footnote label is empty
  384. or new, let the user edit the definition of the footnote."
  385. (interactive)
  386. (unless (and (not (bolp)) (org-footnote-in-valid-context-p))
  387. (error "Cannot insert a footnote here"))
  388. (let* ((labels (and (not (equal org-footnote-auto-label 'random))
  389. (org-footnote-all-labels)))
  390. (propose (org-footnote-unique-label labels))
  391. (label
  392. (org-footnote-normalize-label
  393. (cond
  394. ((member org-footnote-auto-label '(t plain))
  395. propose)
  396. ((equal org-footnote-auto-label 'random)
  397. (require 'org-id)
  398. (substring (org-id-uuid) 0 8))
  399. (t
  400. (completing-read
  401. "Label (leave empty for anonymous): "
  402. (mapcar 'list labels) nil nil
  403. (if (eq org-footnote-auto-label 'confirm) propose nil)
  404. 'org-footnote-label-history))))))
  405. (cond
  406. ((not label)
  407. (insert "[fn:: ]")
  408. (backward-char 1))
  409. ((member label labels)
  410. (insert "[" label "]")
  411. (message "New reference to existing note"))
  412. (org-footnote-define-inline
  413. (insert "[" label ": ]")
  414. (backward-char 1)
  415. (org-footnote-auto-adjust-maybe))
  416. (t
  417. (insert "[" label "]")
  418. (org-footnote-create-definition label)
  419. (org-footnote-auto-adjust-maybe)))))
  420. (defun org-footnote-create-definition (label)
  421. "Start the definition of a footnote with label LABEL."
  422. (interactive "sLabel: ")
  423. (let ((label (org-footnote-normalize-label label)))
  424. (cond
  425. ((org-mode-p)
  426. ;; No section, put footnote into the current outline node Try to
  427. ;; find or make the special node
  428. (when org-footnote-section
  429. (goto-char (point-min))
  430. (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
  431. (unless (or (re-search-forward re nil t)
  432. (and (progn (widen) t)
  433. (re-search-forward re nil t)))
  434. (goto-char (point-max))
  435. (insert "\n\n* " org-footnote-section "\n"))))
  436. ;; Now go to the end of this entry and insert there.
  437. (org-footnote-goto-local-insertion-point)
  438. (org-show-context 'link-search))
  439. (t
  440. ;; In a non-Org file. Search for footnote tag, or create it if
  441. ;; necessary (at the end of buffer, or before a signature if in
  442. ;; Message mode). Set point after any definition already there.
  443. (let ((tag (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$"))
  444. (max (save-excursion
  445. (if (and (derived-mode-p 'message-mode)
  446. (re-search-forward
  447. message-signature-separator nil t))
  448. (copy-marker (point-at-bol) t)
  449. (copy-marker (point-max) t)))))
  450. (goto-char max)
  451. (unless (re-search-backward tag nil t)
  452. (skip-chars-backward " \t\r\n")
  453. (delete-region (point) max)
  454. (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n"))
  455. ;; Skip existing footnotes.
  456. (while (re-search-forward org-footnote-definition-re max t))
  457. (let ((def (org-footnote-at-definition-p)))
  458. (when def (goto-char (nth 2 def))))
  459. (set-marker max nil))))
  460. ;; Insert footnote label, position point and notify user.
  461. (unless (bolp) (insert "\n"))
  462. (insert "\n[" label "] \n")
  463. (backward-char)
  464. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
  465. ;;;###autoload
  466. (defun org-footnote-action (&optional special)
  467. "Do the right thing for footnotes.
  468. When at a footnote reference, jump to the definition.
  469. When at a definition, jump to the references if they exist, offer
  470. to create them otherwise.
  471. When neither at definition or reference, create a new footnote,
  472. interactively.
  473. With prefix arg SPECIAL, offer additional commands in a menu."
  474. (interactive "P")
  475. (let (tmp c)
  476. (cond
  477. (special
  478. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
  479. (setq c (read-char-exclusive))
  480. (cond
  481. ((eq c ?s) (org-footnote-normalize 'sort))
  482. ((eq c ?r) (org-footnote-renumber-fn:N))
  483. ((eq c ?S)
  484. (org-footnote-renumber-fn:N)
  485. (org-footnote-normalize 'sort))
  486. ((eq c ?n) (org-footnote-normalize))
  487. ((eq c ?d) (org-footnote-delete))
  488. (t (error "No such footnote command %c" c))))
  489. ((setq tmp (org-footnote-at-reference-p))
  490. (cond
  491. ;; Anonymous footnote: move point at the beginning of its
  492. ;; definition.
  493. ((not (car tmp))
  494. (goto-char (nth 1 tmp))
  495. (forward-char 5))
  496. ;; A definition exists: move to it.
  497. ((ignore-errors (org-footnote-goto-definition (car tmp))))
  498. ;; No definition exists: offer to create it.
  499. ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
  500. (org-footnote-create-definition (car tmp)))))
  501. ((setq tmp (org-footnote-at-definition-p))
  502. (org-footnote-goto-previous-reference (car tmp)))
  503. (t (org-footnote-new)))))
  504. (defvar org-footnote-insert-pos-for-preprocessor 'point-max
  505. "See `org-footnote-normalize'.")
  506. (defvar org-export-footnotes-seen nil) ; silence byte-compiler
  507. (defvar org-export-footnotes-data nil) ; silence byte-compiler
  508. ;;;###autoload
  509. (defun org-footnote-normalize (&optional sort-only export-props)
  510. "Collect the footnotes in various formats and normalize them.
  511. This finds the different sorts of footnotes allowed in Org, and
  512. normalizes them to the usual [N] format that is understood by the
  513. Org-mode exporters.
  514. When SORT-ONLY is set, only sort the footnote definitions into the
  515. referenced sequence.
  516. If Org is amidst an export process, EXPORT-PROPS will hold the
  517. export properties of the buffer.
  518. When EXPORT-PROPS is non-nil, the default action is to insert
  519. normalized footnotes towards the end of the pre-processing buffer.
  520. Some exporters like docbook, odt, etc. expect that footnote
  521. definitions be available before any references to them. Such
  522. exporters can let bind `org-footnote-insert-pos-for-preprocessor' to
  523. symbol 'point-min to achieve the desired behaviour.
  524. Additional note on `org-footnote-insert-pos-for-preprocessor':
  525. 1. This variable has not effect when FOR-PREPROCESSOR is nil.
  526. 2. This variable (potentially) obviates the need for extra scan
  527. of pre-processor buffer as witnessed in
  528. `org-export-docbook-get-footnotes'."
  529. ;; This is based on Paul's function, but rewritten.
  530. ;;
  531. ;; Re-create `org-with-limited-levels', but not limited to Org
  532. ;; buffers.
  533. (let* ((limit-level
  534. (and (boundp 'org-inlinetask-min-level)
  535. org-inlinetask-min-level
  536. (1- org-inlinetask-min-level)))
  537. (nstars (and limit-level
  538. (if org-odd-levels-only
  539. (and limit-level (1- (* limit-level 2)))
  540. limit-level)))
  541. (org-outline-regexp
  542. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  543. ;; Determine the highest marker used so far.
  544. (ref-table (when export-props org-export-footnotes-seen))
  545. (count (if (and export-props ref-table)
  546. (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
  547. 0))
  548. ins-point ref)
  549. (save-excursion
  550. ;; 1. Find every footnote reference, extract the definition, and
  551. ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
  552. ;; normalize references.
  553. (goto-char (point-min))
  554. (while (setq ref (org-footnote-get-next-reference))
  555. (let* ((lbl (car ref))
  556. ;; When footnote isn't anonymous, check if it's label
  557. ;; (REF) is already stored in REF-TABLE. In that case,
  558. ;; extract number used to identify it (MARKER). If
  559. ;; footnote is unknown, increment the global counter
  560. ;; (COUNT) to create an unused identifier.
  561. (a (and lbl (assoc lbl ref-table)))
  562. (marker (or (nth 1 a) (incf count)))
  563. ;; Is the reference inline or pointing to an inline
  564. ;; footnote?
  565. (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
  566. ;; Replace footnote reference with [MARKER]. Maybe fill
  567. ;; paragraph once done. If SORT-ONLY is non-nil, only move
  568. ;; to the end of reference found to avoid matching it twice.
  569. ;; If EXPORT-PROPS isn't nil, also add `org-footnote'
  570. ;; property to it, so it can be easily recognized by
  571. ;; exporters.
  572. (if sort-only
  573. (goto-char (nth 2 ref))
  574. (delete-region (nth 1 ref) (nth 2 ref))
  575. (goto-char (nth 1 ref))
  576. (let ((new-ref (format "[%d]" marker)))
  577. (when export-props (org-add-props new-ref '(org-footnote t)))
  578. (insert new-ref))
  579. (and inlinep
  580. org-footnote-fill-after-inline-note-extraction
  581. (org-fill-paragraph)))
  582. ;; Add label (REF), identifier (MARKER) and definition (DEF)
  583. ;; to REF-TABLE if data was unknown.
  584. (unless a
  585. (let ((def (or (nth 3 ref) ; inline
  586. (and export-props
  587. (cdr (assoc lbl org-export-footnotes-data)))
  588. (nth 3 (org-footnote-get-definition lbl)))))
  589. (push (list lbl marker
  590. ;; When exporting, each definition goes
  591. ;; through `org-export-preprocess-string' so
  592. ;; it is ready to insert in the
  593. ;; backend-specific buffer.
  594. (if export-props
  595. (let ((parameters
  596. (org-combine-plists
  597. export-props
  598. '(:todo-keywords t :tags t :priority t))))
  599. (org-export-preprocess-string def parameters))
  600. def)
  601. inlinep) ref-table)))
  602. ;; Remove definition of non-inlined footnotes.
  603. (unless inlinep (org-footnote-delete-definitions lbl))))
  604. ;; 2. Find and remove the footnote section, if any. Also
  605. ;; determine where footnotes shall be inserted (INS-POINT).
  606. (goto-char (point-min))
  607. (cond
  608. ((org-mode-p)
  609. (if (and org-footnote-section
  610. (re-search-forward
  611. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  612. "[ \t]*$")
  613. nil t))
  614. (progn
  615. (setq ins-point (match-beginning 0))
  616. (delete-region (match-beginning 0) (org-end-of-subtree t)))
  617. (setq ins-point (point-max))))
  618. (t
  619. (when (re-search-forward
  620. (concat "^"
  621. (regexp-quote org-footnote-tag-for-non-org-mode-files)
  622. "[ \t]*$")
  623. nil t)
  624. (replace-match ""))
  625. ;; In message-mode, ensure footnotes are inserted before the
  626. ;; signature.
  627. (let ((pt-max
  628. (or (and (derived-mode-p 'message-mode)
  629. (save-excursion
  630. (goto-char (point-max))
  631. (re-search-backward
  632. message-signature-separator nil t)
  633. (1- (point))))
  634. (point-max))))
  635. (goto-char pt-max)
  636. (skip-chars-backward " \t\n\r")
  637. (forward-line)
  638. (delete-region (point) pt-max))
  639. (setq ins-point (point))))
  640. ;; 3. Clean-up REF-TABLE.
  641. (setq ref-table
  642. (delq nil
  643. (mapcar
  644. (lambda (x)
  645. (cond
  646. ;; When only sorting, ignore inline footnotes.
  647. ((and sort-only (nth 3 x)) nil)
  648. ;; No definition available: provide one.
  649. ((not (nth 2 x))
  650. (append (butlast x 2)
  651. (list (format "DEFINITION NOT FOUND: %s" (car x))
  652. (nth 3 x))))
  653. (t x)))
  654. ref-table)))
  655. (setq ref-table (nreverse ref-table))
  656. ;; 4. Insert the footnotes again in the buffer, at the
  657. ;; appropriate spot.
  658. (goto-char (or
  659. (and export-props
  660. (eq org-footnote-insert-pos-for-preprocessor 'point-min)
  661. (point-min))
  662. ins-point
  663. (point-max)))
  664. (cond
  665. ;; No footnote: exit.
  666. ((not ref-table))
  667. ;; Cases when footnotes should be inserted in one place.
  668. ((or (not (org-mode-p))
  669. org-footnote-section
  670. (not sort-only))
  671. ;; Insert again the section title.
  672. (cond
  673. ((not (org-mode-p))
  674. (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n"))
  675. ((and org-footnote-section (not export-props))
  676. (or (bolp) (insert "\n"))
  677. (insert "* " org-footnote-section "\n")))
  678. ;; Insert the footnotes.
  679. (insert "\n"
  680. (mapconcat (lambda (x) (format "[%s] %s"
  681. (nth (if sort-only 0 1) x) (nth 2 x)))
  682. ref-table "\n\n")
  683. "\n\n")
  684. ;; When exporting, add newly inserted markers along with their
  685. ;; associated definition to `org-export-footnotes-seen'.
  686. (when export-props
  687. (setq org-export-footnotes-seen ref-table)))
  688. ;; Else, insert each definition at the end of the section
  689. ;; containing their first reference. Happens only in Org files
  690. ;; with no special footnote section, and only when doing
  691. ;; sorting.
  692. (t (mapc 'org-insert-footnote-reference-near-definition
  693. ref-table))))))
  694. (defun org-insert-footnote-reference-near-definition (entry)
  695. "Find first reference of footnote ENTRY and insert the definition there.
  696. ENTRY is (fn-label num-mark definition)."
  697. (when (car entry)
  698. (goto-char (point-min))
  699. (let ((ref (org-footnote-get-next-reference (car entry))))
  700. (when ref
  701. (goto-char (nth 2 ref))
  702. (org-footnote-goto-local-insertion-point)
  703. (insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
  704. (defun org-footnote-goto-local-insertion-point ()
  705. "Find insertion point for footnote, just before next outline heading."
  706. (org-with-limited-levels (outline-next-heading))
  707. (or (bolp) (newline))
  708. (beginning-of-line 0)
  709. (while (and (not (bobp)) (= (char-after) ?#))
  710. (beginning-of-line 0))
  711. (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
  712. (end-of-line 1)
  713. (skip-chars-backward "\n\r\t ")
  714. (forward-line))
  715. (defun org-footnote-delete-references (label)
  716. "Delete every reference to footnote LABEL.
  717. Return the number of footnotes removed."
  718. (save-excursion
  719. (goto-char (point-min))
  720. (let (ref (nref 0))
  721. (while (setq ref (org-footnote-get-next-reference label))
  722. (goto-char (nth 1 ref))
  723. (delete-region (nth 1 ref) (nth 2 ref))
  724. (incf nref))
  725. nref)))
  726. (defun org-footnote-delete-definitions (label)
  727. "Delete every definition of the footnote LABEL.
  728. Return the number of footnotes removed."
  729. (save-excursion
  730. (goto-char (point-min))
  731. (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
  732. (ndef 0))
  733. (while (re-search-forward def-re nil t)
  734. (let ((full-def (org-footnote-at-definition-p)))
  735. (delete-region (nth 1 full-def) (nth 2 full-def)))
  736. (incf ndef))
  737. ndef)))
  738. (defun org-footnote-delete (&optional label)
  739. "Delete the footnote at point.
  740. This will remove the definition (even multiple definitions if they exist)
  741. and all references of a footnote label.
  742. If LABEL is non-nil, delete that footnote instead."
  743. (catch 'done
  744. (let* ((nref 0) (ndef 0) x
  745. ;; 1. Determine LABEL of footnote at point.
  746. (label (cond
  747. ;; LABEL is provided as argument.
  748. (label)
  749. ;; Footnote reference at point. If the footnote is
  750. ;; anonymous, delete it and exit instead.
  751. ((setq x (org-footnote-at-reference-p))
  752. (or (car x)
  753. (progn
  754. (delete-region (nth 1 x) (nth 2 x))
  755. (message "Anonymous footnote removed")
  756. (throw 'done t))))
  757. ;; Footnote definition at point.
  758. ((setq x (org-footnote-at-definition-p))
  759. (car x))
  760. (t (error "Don't know which footnote to remove")))))
  761. ;; 2. Now that LABEL is non-nil, find every reference and every
  762. ;; definition, and delete them.
  763. (setq nref (org-footnote-delete-references label)
  764. ndef (org-footnote-delete-definitions label))
  765. ;; 3. Verify consistency of footnotes and notify user.
  766. (org-footnote-auto-adjust-maybe)
  767. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  768. ndef nref label))))
  769. (defun org-footnote-renumber-fn:N ()
  770. "Renumber the simple footnotes like fn:17 into a sequence in the document."
  771. (interactive)
  772. (let (map i (n 0))
  773. (save-excursion
  774. (save-restriction
  775. (widen)
  776. (goto-char (point-min))
  777. (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
  778. (setq i (string-to-number (match-string 1)))
  779. (when (and (string-match "\\S-" (buffer-substring
  780. (point-at-bol) (match-beginning 0)))
  781. (not (assq i map)))
  782. (push (cons i (number-to-string (incf n))) map)))
  783. (goto-char (point-min))
  784. (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
  785. (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
  786. (defun org-footnote-auto-adjust-maybe ()
  787. "Renumber and/or sort footnotes according to user settings."
  788. (when (memq org-footnote-auto-adjust '(t renumber))
  789. (org-footnote-renumber-fn:N))
  790. (when (memq org-footnote-auto-adjust '(t sort))
  791. (let ((label (car (org-footnote-at-definition-p))))
  792. (org-footnote-normalize 'sort)
  793. (when label
  794. (goto-char (point-min))
  795. (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
  796. nil t)
  797. (progn (insert " ")
  798. (just-one-space)))))))
  799. (provide 'org-footnote)
  800. ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
  801. ;;; org-footnote.el ends here