org-footnote.el 32 KB

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