org-footnote.el 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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.6
  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. (let ((re (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$")))
  441. (unless (re-search-forward re nil t)
  442. (let ((max (if (and (derived-mode-p 'message-mode)
  443. (re-search-forward message-signature-separator nil t))
  444. (progn (beginning-of-line) (point))
  445. (goto-char (point-max)))))
  446. (skip-chars-backward " \t\r\n")
  447. (delete-region (point) max)
  448. (insert "\n\n")
  449. (insert org-footnote-tag-for-non-org-mode-files "\n"))))
  450. ;; Skip existing footnotes
  451. (while (re-search-forward "^[[:space:]]*\\[[^]]+\\] " nil t)
  452. (forward-line))))
  453. (insert "\n[" label "] \n")
  454. (goto-char (1- (point)))
  455. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
  456. ;;;###autoload
  457. (defun org-footnote-action (&optional special)
  458. "Do the right thing for footnotes.
  459. When at a footnote reference, jump to the definition.
  460. When at a definition, jump to the references if they exist, offer
  461. to create them otherwise.
  462. When neither at definition or reference, create a new footnote,
  463. interactively.
  464. With prefix arg SPECIAL, offer additional commands in a menu."
  465. (interactive "P")
  466. (let (tmp c)
  467. (cond
  468. (special
  469. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
  470. (setq c (read-char-exclusive))
  471. (cond
  472. ((eq c ?s) (org-footnote-normalize 'sort))
  473. ((eq c ?r) (org-footnote-renumber-fn:N))
  474. ((eq c ?S)
  475. (org-footnote-renumber-fn:N)
  476. (org-footnote-normalize 'sort))
  477. ((eq c ?n) (org-footnote-normalize))
  478. ((eq c ?d) (org-footnote-delete))
  479. (t (error "No such footnote command %c" c))))
  480. ((setq tmp (org-footnote-at-reference-p))
  481. (cond
  482. ;; Anonymous footnote: move point at the beginning of its
  483. ;; definition.
  484. ((not (car tmp))
  485. (goto-char (nth 1 tmp))
  486. (forward-char 5))
  487. ;; A definition exists: move to it.
  488. ((ignore-errors (org-footnote-goto-definition (car tmp))))
  489. ;; No definition exists: offer to create it.
  490. ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
  491. (org-footnote-create-definition (car tmp)))))
  492. ((setq tmp (org-footnote-at-definition-p))
  493. (org-footnote-goto-previous-reference (car tmp)))
  494. (t (org-footnote-new)))))
  495. (defvar org-footnote-insert-pos-for-preprocessor 'point-max
  496. "See `org-footnote-normalize'.")
  497. (defvar org-export-footnotes-seen nil) ; silence byte-compiler
  498. (defvar org-export-footnotes-data nil) ; silence byte-compiler
  499. ;;;###autoload
  500. (defun org-footnote-normalize (&optional sort-only export-props)
  501. "Collect the footnotes in various formats and normalize them.
  502. This finds the different sorts of footnotes allowed in Org, and
  503. normalizes them to the usual [N] format that is understood by the
  504. Org-mode exporters.
  505. When SORT-ONLY is set, only sort the footnote definitions into the
  506. referenced sequence.
  507. If Org is amidst an export process, EXPORT-PROPS will hold the
  508. export properties of the buffer.
  509. When EXPORT-PROPS is non-nil, the default action is to insert
  510. normalized footnotes towards the end of the pre-processing buffer.
  511. Some exporters like docbook, odt, etc. expect that footnote
  512. definitions be available before any references to them. Such
  513. exporters can let bind `org-footnote-insert-pos-for-preprocessor' to
  514. symbol 'point-min to achieve the desired behaviour.
  515. Additional note on `org-footnote-insert-pos-for-preprocessor':
  516. 1. This variable has not effect when FOR-PREPROCESSOR is nil.
  517. 2. This variable (potentially) obviates the need for extra scan
  518. of pre-processor buffer as witnessed in
  519. `org-export-docbook-get-footnotes'."
  520. ;; This is based on Paul's function, but rewritten.
  521. ;;
  522. ;; Re-create `org-with-limited-levels', but not limited to Org
  523. ;; buffers.
  524. (let* ((limit-level
  525. (and (boundp 'org-inlinetask-min-level)
  526. org-inlinetask-min-level
  527. (1- org-inlinetask-min-level)))
  528. (nstars (and limit-level
  529. (if org-odd-levels-only
  530. (and limit-level (1- (* limit-level 2)))
  531. limit-level)))
  532. (org-outline-regexp
  533. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  534. ;; Determine the highest marker used so far.
  535. (ref-table (when export-props org-export-footnotes-seen))
  536. (count (if (and export-props ref-table)
  537. (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
  538. 0))
  539. ins-point ref)
  540. (save-excursion
  541. ;; 1. Find every footnote reference, extract the definition, and
  542. ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
  543. ;; normalize references.
  544. (goto-char (point-min))
  545. (while (setq ref (org-footnote-get-next-reference))
  546. (let* ((lbl (car ref))
  547. ;; When footnote isn't anonymous, check if it's label
  548. ;; (REF) is already stored in REF-TABLE. In that case,
  549. ;; extract number used to identify it (MARKER). If
  550. ;; footnote is unknown, increment the global counter
  551. ;; (COUNT) to create an unused identifier.
  552. (a (and lbl (assoc lbl ref-table)))
  553. (marker (or (nth 1 a) (incf count)))
  554. ;; Is the reference inline or pointing to an inline
  555. ;; footnote?
  556. (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
  557. ;; Replace footnote reference with [MARKER]. Maybe fill
  558. ;; paragraph once done. If SORT-ONLY is non-nil, only move
  559. ;; to the end of reference found to avoid matching it twice.
  560. ;; If EXPORT-PROPS isn't nil, also add `org-footnote'
  561. ;; property to it, so it can be easily recognized by
  562. ;; exporters.
  563. (if sort-only
  564. (goto-char (nth 2 ref))
  565. (delete-region (nth 1 ref) (nth 2 ref))
  566. (goto-char (nth 1 ref))
  567. (let ((new-ref (format "[%d]" marker)))
  568. (when export-props (org-add-props new-ref '(org-footnote t)))
  569. (insert new-ref))
  570. (and inlinep
  571. org-footnote-fill-after-inline-note-extraction
  572. (org-fill-paragraph)))
  573. ;; Add label (REF), identifier (MARKER) and definition (DEF)
  574. ;; to REF-TABLE if data was unknown.
  575. (unless a
  576. (let ((def (or (nth 3 ref) ; inline
  577. (and export-props
  578. (cdr (assoc lbl org-export-footnotes-data)))
  579. (nth 3 (org-footnote-get-definition lbl)))))
  580. (push (list lbl marker
  581. ;; When exporting, each definition goes
  582. ;; through `org-export-preprocess-string' so
  583. ;; it is ready to insert in the
  584. ;; backend-specific buffer.
  585. (if export-props
  586. (let ((parameters
  587. (org-combine-plists
  588. export-props
  589. '(:todo-keywords t :tags t :priority t))))
  590. (org-export-preprocess-string def parameters))
  591. def)
  592. inlinep) ref-table)))
  593. ;; Remove definition of non-inlined footnotes.
  594. (unless inlinep (org-footnote-delete-definitions lbl))))
  595. ;; 2. Find and remove the footnote section, if any. Also
  596. ;; determine where footnotes shall be inserted (INS-POINT).
  597. (goto-char (point-min))
  598. (cond
  599. ((org-mode-p)
  600. (if (and org-footnote-section
  601. (re-search-forward
  602. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  603. "[ \t]*$")
  604. nil t))
  605. (progn
  606. (setq ins-point (match-beginning 0))
  607. (delete-region (match-beginning 0) (org-end-of-subtree t)))
  608. (setq ins-point (point-max))))
  609. (t
  610. (when (re-search-forward
  611. (concat "^"
  612. (regexp-quote org-footnote-tag-for-non-org-mode-files)
  613. "[ \t]*$")
  614. nil t)
  615. (replace-match ""))
  616. ;; In message-mode, ensure footnotes are inserted before the
  617. ;; signature.
  618. (let ((pt-max
  619. (or (and (derived-mode-p 'message-mode)
  620. (save-excursion
  621. (goto-char (point-max))
  622. (re-search-backward
  623. message-signature-separator nil t)
  624. (1- (point))))
  625. (point-max))))
  626. (goto-char pt-max)
  627. (skip-chars-backward " \t\n\r")
  628. (forward-line)
  629. (delete-region (point) pt-max))
  630. (setq ins-point (point))))
  631. ;; 3. Clean-up REF-TABLE.
  632. (setq ref-table
  633. (delq nil
  634. (mapcar
  635. (lambda (x)
  636. (cond
  637. ;; When only sorting, ignore inline footnotes.
  638. ((and sort-only (nth 3 x)) nil)
  639. ;; No definition available: provide one.
  640. ((not (nth 2 x))
  641. (append (butlast x 2)
  642. (list (format "DEFINITION NOT FOUND: %s" (car x))
  643. (nth 3 x))))
  644. (t x)))
  645. ref-table)))
  646. (setq ref-table (nreverse ref-table))
  647. ;; 4. Insert the footnotes again in the buffer, at the
  648. ;; appropriate spot.
  649. (goto-char (or
  650. (and export-props
  651. (eq org-footnote-insert-pos-for-preprocessor 'point-min)
  652. (point-min))
  653. ins-point
  654. (point-max)))
  655. (cond
  656. ;; No footnote: exit.
  657. ((not ref-table))
  658. ;; Cases when footnotes should be inserted in one place.
  659. ((or (not (org-mode-p))
  660. org-footnote-section
  661. (not sort-only))
  662. ;; Insert again the section title.
  663. (cond
  664. ((not (org-mode-p))
  665. (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n"))
  666. ((and org-footnote-section (not export-props))
  667. (or (bolp) (insert "\n"))
  668. (insert "* " org-footnote-section "\n")))
  669. ;; Insert the footnotes.
  670. (insert "\n"
  671. (mapconcat (lambda (x) (format "[%s] %s"
  672. (nth (if sort-only 0 1) x) (nth 2 x)))
  673. ref-table "\n\n")
  674. "\n\n")
  675. ;; When exporting, add newly inserted markers along with their
  676. ;; associated definition to `org-export-footnotes-seen'.
  677. (when export-props
  678. (setq org-export-footnotes-seen ref-table)))
  679. ;; Else, insert each definition at the end of the section
  680. ;; containing their first reference. Happens only in Org files
  681. ;; with no special footnote section, and only when doing
  682. ;; sorting.
  683. (t (mapc 'org-insert-footnote-reference-near-definition
  684. ref-table))))))
  685. (defun org-insert-footnote-reference-near-definition (entry)
  686. "Find first reference of footnote ENTRY and insert the definition there.
  687. ENTRY is (fn-label num-mark definition)."
  688. (when (car entry)
  689. (goto-char (point-min))
  690. (let ((ref (org-footnote-get-next-reference (car entry))))
  691. (when ref
  692. (goto-char (nth 2 ref))
  693. (org-footnote-goto-local-insertion-point)
  694. (insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
  695. (defun org-footnote-goto-local-insertion-point ()
  696. "Find insertion point for footnote, just before next outline heading."
  697. (org-with-limited-levels (outline-next-heading))
  698. (or (bolp) (newline))
  699. (beginning-of-line 0)
  700. (while (and (not (bobp)) (= (char-after) ?#))
  701. (beginning-of-line 0))
  702. (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
  703. (end-of-line 1)
  704. (skip-chars-backward "\n\r\t ")
  705. (forward-line))
  706. (defun org-footnote-delete-references (label)
  707. "Delete every reference to footnote LABEL.
  708. Return the number of footnotes removed."
  709. (save-excursion
  710. (goto-char (point-min))
  711. (let (ref (nref 0))
  712. (while (setq ref (org-footnote-get-next-reference label))
  713. (goto-char (nth 1 ref))
  714. (delete-region (nth 1 ref) (nth 2 ref))
  715. (incf nref))
  716. nref)))
  717. (defun org-footnote-delete-definitions (label)
  718. "Delete every definition of the footnote LABEL.
  719. Return the number of footnotes removed."
  720. (save-excursion
  721. (goto-char (point-min))
  722. (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
  723. (ndef 0))
  724. (while (re-search-forward def-re nil t)
  725. (let ((full-def (org-footnote-at-definition-p)))
  726. (delete-region (nth 1 full-def) (nth 2 full-def)))
  727. (incf ndef))
  728. ndef)))
  729. (defun org-footnote-delete (&optional label)
  730. "Delete the footnote at point.
  731. This will remove the definition (even multiple definitions if they exist)
  732. and all references of a footnote label.
  733. If LABEL is non-nil, delete that footnote instead."
  734. (catch 'done
  735. (let* ((nref 0) (ndef 0) x
  736. ;; 1. Determine LABEL of footnote at point.
  737. (label (cond
  738. ;; LABEL is provided as argument.
  739. (label)
  740. ;; Footnote reference at point. If the footnote is
  741. ;; anonymous, delete it and exit instead.
  742. ((setq x (org-footnote-at-reference-p))
  743. (or (car x)
  744. (progn
  745. (delete-region (nth 1 x) (nth 2 x))
  746. (message "Anonymous footnote removed")
  747. (throw 'done t))))
  748. ;; Footnote definition at point.
  749. ((setq x (org-footnote-at-definition-p))
  750. (car x))
  751. (t (error "Don't know which footnote to remove")))))
  752. ;; 2. Now that LABEL is non-nil, find every reference and every
  753. ;; definition, and delete them.
  754. (setq nref (org-footnote-delete-references label)
  755. ndef (org-footnote-delete-definitions label))
  756. ;; 3. Verify consistency of footnotes and notify user.
  757. (org-footnote-auto-adjust-maybe)
  758. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  759. ndef nref label))))
  760. (defun org-footnote-renumber-fn:N ()
  761. "Renumber the simple footnotes like fn:17 into a sequence in the document."
  762. (interactive)
  763. (let (map i (n 0))
  764. (save-excursion
  765. (save-restriction
  766. (widen)
  767. (goto-char (point-min))
  768. (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
  769. (setq i (string-to-number (match-string 1)))
  770. (when (and (string-match "\\S-" (buffer-substring
  771. (point-at-bol) (match-beginning 0)))
  772. (not (assq i map)))
  773. (push (cons i (number-to-string (incf n))) map)))
  774. (goto-char (point-min))
  775. (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
  776. (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
  777. (defun org-footnote-auto-adjust-maybe ()
  778. "Renumber and/or sort footnotes according to user settings."
  779. (when (memq org-footnote-auto-adjust '(t renumber))
  780. (org-footnote-renumber-fn:N))
  781. (when (memq org-footnote-auto-adjust '(t sort))
  782. (let ((label (car (org-footnote-at-definition-p))))
  783. (org-footnote-normalize 'sort)
  784. (when label
  785. (goto-char (point-min))
  786. (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
  787. nil t)
  788. (progn (insert " ")
  789. (just-one-space)))))))
  790. (provide 'org-footnote)
  791. ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
  792. ;;; org-footnote.el ends here