org-footnote.el 31 KB

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