org-footnote.el 30 KB

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