org-footnote.el 29 KB

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