org-footnote.el 31 KB

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