org-footnote.el 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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-id" ())
  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 function returns the first \"fn:N\" or \"N\" label that is
  373. currently not used."
  374. (unless current (setq current (org-footnote-all-labels)))
  375. (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
  376. (cnt 1))
  377. (while (member (format fmt cnt) current)
  378. (incf cnt))
  379. (format fmt cnt)))
  380. (defun org-footnote-new ()
  381. "Insert a new footnote.
  382. This command prompts for a label. If this is a label referencing an
  383. existing label, only insert the label. If the footnote label is empty
  384. or new, let the user edit the definition of the footnote."
  385. (interactive)
  386. (unless (org-footnote-in-valid-context-p)
  387. (error "Cannot insert a footnote here"))
  388. (let* ((lbls (and (not (equal org-footnote-auto-label 'random))
  389. (org-footnote-all-labels)))
  390. (propose (org-footnote-unique-label lbls))
  391. (label
  392. (org-footnote-normalize-label
  393. (cond
  394. ((member org-footnote-auto-label '(t plain))
  395. propose)
  396. ((equal org-footnote-auto-label 'random)
  397. (require 'org-id)
  398. (substring (org-id-uuid) 0 8))
  399. (t
  400. (org-icompleting-read
  401. "Label (leave empty for anonymous): "
  402. (mapcar 'list lbls) nil nil
  403. (if (eq org-footnote-auto-label 'confirm) propose nil)))))))
  404. (cond
  405. ((and label (bolp) (not org-footnote-define-inline))
  406. (error "Cannot create a non-inlined footnote at left margin"))
  407. ((not label)
  408. (insert "[fn:: ]")
  409. (backward-char 1))
  410. ((member label lbls)
  411. (insert "[" label "]")
  412. (message "New reference to existing note"))
  413. (org-footnote-define-inline
  414. (insert "[" label ": ]")
  415. (backward-char 1)
  416. (org-footnote-auto-adjust-maybe))
  417. (t
  418. (insert "[" label "]")
  419. (org-footnote-create-definition label)
  420. (org-footnote-auto-adjust-maybe)))))
  421. (defun org-footnote-create-definition (label)
  422. "Start the definition of a footnote with label LABEL."
  423. (interactive "sLabel: ")
  424. (let ((label (org-footnote-normalize-label label)))
  425. (cond
  426. ((org-mode-p)
  427. ;; No section, put footnote into the current outline node Try to
  428. ;; find or make the special node
  429. (when org-footnote-section
  430. (goto-char (point-min))
  431. (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
  432. (unless (or (re-search-forward re nil t)
  433. (and (progn (widen) t)
  434. (re-search-forward re nil t)))
  435. (goto-char (point-max))
  436. (insert "\n\n* " org-footnote-section "\n"))))
  437. ;; Now go to the end of this entry and insert there.
  438. (org-footnote-goto-local-insertion-point)
  439. (org-show-context 'link-search))
  440. (t
  441. ;; In a non-Org file. Search for footnote tag, or create it if
  442. ;; necessary (at the end of buffer, or before a signature if in
  443. ;; Message mode). Set point after any definition already there.
  444. (let ((tag (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$"))
  445. (max (save-excursion
  446. (if (and (derived-mode-p 'message-mode)
  447. (re-search-forward
  448. message-signature-separator nil t))
  449. (copy-marker (point-at-bol) t)
  450. (copy-marker (point-max) t)))))
  451. (goto-char max)
  452. (unless (re-search-backward tag nil t)
  453. (skip-chars-backward " \t\r\n")
  454. (delete-region (point) max)
  455. (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n"))
  456. ;; Skip existing footnotes.
  457. (while (re-search-forward org-footnote-definition-re max t))
  458. (let ((def (org-footnote-at-definition-p)))
  459. (when def (goto-char (nth 2 def))))
  460. (set-marker max nil))))
  461. ;; Insert footnote label, position point and notify user.
  462. (unless (bolp) (insert "\n"))
  463. (insert "\n[" label "] \n")
  464. (backward-char)
  465. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
  466. ;;;###autoload
  467. (defun org-footnote-action (&optional special)
  468. "Do the right thing for footnotes.
  469. When at a footnote reference, jump to the definition.
  470. When at a definition, jump to the references if they exist, offer
  471. to create them otherwise.
  472. When neither at definition or reference, create a new footnote,
  473. interactively.
  474. With prefix arg SPECIAL, offer additional commands in a menu."
  475. (interactive "P")
  476. (let (tmp c)
  477. (cond
  478. (special
  479. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
  480. (setq c (read-char-exclusive))
  481. (cond
  482. ((eq c ?s) (org-footnote-normalize 'sort))
  483. ((eq c ?r) (org-footnote-renumber-fn:N))
  484. ((eq c ?S)
  485. (org-footnote-renumber-fn:N)
  486. (org-footnote-normalize 'sort))
  487. ((eq c ?n) (org-footnote-normalize))
  488. ((eq c ?d) (org-footnote-delete))
  489. (t (error "No such footnote command %c" c))))
  490. ((setq tmp (org-footnote-at-reference-p))
  491. (cond
  492. ;; Anonymous footnote: move point at the beginning of its
  493. ;; definition.
  494. ((not (car tmp))
  495. (goto-char (nth 1 tmp))
  496. (forward-char 5))
  497. ;; A definition exists: move to it.
  498. ((ignore-errors (org-footnote-goto-definition (car tmp))))
  499. ;; No definition exists: offer to create it.
  500. ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
  501. (org-footnote-create-definition (car tmp)))))
  502. ((setq tmp (org-footnote-at-definition-p))
  503. (org-footnote-goto-previous-reference (car tmp)))
  504. (t (org-footnote-new)))))
  505. (defvar org-footnote-insert-pos-for-preprocessor 'point-max
  506. "See `org-footnote-normalize'.")
  507. (defvar org-export-footnotes-seen nil) ; silence byte-compiler
  508. (defvar org-export-footnotes-data nil) ; silence byte-compiler
  509. ;;;###autoload
  510. (defun org-footnote-normalize (&optional sort-only export-props)
  511. "Collect the footnotes in various formats and normalize them.
  512. This finds the different sorts of footnotes allowed in Org, and
  513. normalizes them to the usual [N] format that is understood by the
  514. Org-mode exporters.
  515. When SORT-ONLY is set, only sort the footnote definitions into the
  516. referenced sequence.
  517. If Org is amidst an export process, EXPORT-PROPS will hold the
  518. export properties of the buffer.
  519. When EXPORT-PROPS is non-nil, the default action is to insert
  520. normalized footnotes towards the end of the pre-processing buffer.
  521. Some exporters like docbook, odt, etc. expect that footnote
  522. definitions be available before any references to them. Such
  523. exporters can let bind `org-footnote-insert-pos-for-preprocessor' to
  524. symbol 'point-min to achieve the desired behaviour.
  525. Additional note on `org-footnote-insert-pos-for-preprocessor':
  526. 1. This variable has not effect when FOR-PREPROCESSOR is nil.
  527. 2. This variable (potentially) obviates the need for extra scan
  528. of pre-processor buffer as witnessed in
  529. `org-export-docbook-get-footnotes'."
  530. ;; This is based on Paul's function, but rewritten.
  531. ;;
  532. ;; Re-create `org-with-limited-levels', but not limited to Org
  533. ;; buffers.
  534. (let* ((limit-level
  535. (and (boundp 'org-inlinetask-min-level)
  536. org-inlinetask-min-level
  537. (1- org-inlinetask-min-level)))
  538. (nstars (and limit-level
  539. (if org-odd-levels-only
  540. (and limit-level (1- (* limit-level 2)))
  541. limit-level)))
  542. (org-outline-regexp
  543. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  544. ;; Determine the highest marker used so far.
  545. (ref-table (when export-props org-export-footnotes-seen))
  546. (count (if (and export-props ref-table)
  547. (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
  548. 0))
  549. ins-point ref)
  550. (save-excursion
  551. ;; 1. Find every footnote reference, extract the definition, and
  552. ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
  553. ;; normalize references.
  554. (goto-char (point-min))
  555. (while (setq ref (org-footnote-get-next-reference))
  556. (let* ((lbl (car ref))
  557. ;; When footnote isn't anonymous, check if it's label
  558. ;; (REF) is already stored in REF-TABLE. In that case,
  559. ;; extract number used to identify it (MARKER). If
  560. ;; footnote is unknown, increment the global counter
  561. ;; (COUNT) to create an unused identifier.
  562. (a (and lbl (assoc lbl ref-table)))
  563. (marker (or (nth 1 a) (incf count)))
  564. ;; Is the reference inline or pointing to an inline
  565. ;; footnote?
  566. (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
  567. ;; Replace footnote reference with [MARKER]. Maybe fill
  568. ;; paragraph once done. If SORT-ONLY is non-nil, only move
  569. ;; to the end of reference found to avoid matching it twice.
  570. ;; If EXPORT-PROPS isn't nil, also add `org-footnote'
  571. ;; property to it, so it can be easily recognized by
  572. ;; exporters.
  573. (if sort-only
  574. (goto-char (nth 2 ref))
  575. (delete-region (nth 1 ref) (nth 2 ref))
  576. (goto-char (nth 1 ref))
  577. (let ((new-ref (format "[%d]" marker)))
  578. (when export-props (org-add-props new-ref '(org-footnote t)))
  579. (insert new-ref))
  580. (and inlinep
  581. org-footnote-fill-after-inline-note-extraction
  582. (org-fill-paragraph)))
  583. ;; Add label (REF), identifier (MARKER) and definition (DEF)
  584. ;; to REF-TABLE if data was unknown.
  585. (unless a
  586. (let ((def (or (nth 3 ref) ; inline
  587. (and export-props
  588. (cdr (assoc lbl org-export-footnotes-data)))
  589. (nth 3 (org-footnote-get-definition lbl)))))
  590. (push (list lbl marker
  591. ;; When exporting, each definition goes
  592. ;; through `org-export-preprocess-string' so
  593. ;; it is ready to insert in the
  594. ;; backend-specific buffer.
  595. (if export-props
  596. (let ((parameters
  597. (org-combine-plists
  598. export-props
  599. '(:todo-keywords t :tags t :priority t))))
  600. (org-export-preprocess-string def parameters))
  601. def)
  602. inlinep) ref-table)))
  603. ;; Remove definition of non-inlined footnotes.
  604. (unless inlinep (org-footnote-delete-definitions lbl))))
  605. ;; 2. Find and remove the footnote section, if any. Also
  606. ;; determine where footnotes shall be inserted (INS-POINT).
  607. (goto-char (point-min))
  608. (cond
  609. ((org-mode-p)
  610. (if (and org-footnote-section
  611. (re-search-forward
  612. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  613. "[ \t]*$")
  614. nil t))
  615. (progn
  616. (setq ins-point (match-beginning 0))
  617. (delete-region (match-beginning 0) (org-end-of-subtree t)))
  618. (setq ins-point (point-max))))
  619. (t
  620. (when (re-search-forward
  621. (concat "^"
  622. (regexp-quote org-footnote-tag-for-non-org-mode-files)
  623. "[ \t]*$")
  624. nil t)
  625. (replace-match ""))
  626. ;; In message-mode, ensure footnotes are inserted before the
  627. ;; signature.
  628. (let ((pt-max
  629. (or (and (derived-mode-p 'message-mode)
  630. (save-excursion
  631. (goto-char (point-max))
  632. (re-search-backward
  633. message-signature-separator nil t)
  634. (1- (point))))
  635. (point-max))))
  636. (goto-char pt-max)
  637. (skip-chars-backward " \t\n\r")
  638. (forward-line)
  639. (delete-region (point) pt-max))
  640. (setq ins-point (point))))
  641. ;; 3. Clean-up REF-TABLE.
  642. (setq ref-table
  643. (delq nil
  644. (mapcar
  645. (lambda (x)
  646. (cond
  647. ;; When only sorting, ignore inline footnotes.
  648. ((and sort-only (nth 3 x)) nil)
  649. ;; No definition available: provide one.
  650. ((not (nth 2 x))
  651. (append (butlast x 2)
  652. (list (format "DEFINITION NOT FOUND: %s" (car x))
  653. (nth 3 x))))
  654. (t x)))
  655. ref-table)))
  656. (setq ref-table (nreverse ref-table))
  657. ;; 4. Insert the footnotes again in the buffer, at the
  658. ;; appropriate spot.
  659. (goto-char (or
  660. (and export-props
  661. (eq org-footnote-insert-pos-for-preprocessor 'point-min)
  662. (point-min))
  663. ins-point
  664. (point-max)))
  665. (cond
  666. ;; No footnote: exit.
  667. ((not ref-table))
  668. ;; Cases when footnotes should be inserted in one place.
  669. ((or (not (org-mode-p))
  670. org-footnote-section
  671. (not sort-only))
  672. ;; Insert again the section title.
  673. (cond
  674. ((not (org-mode-p))
  675. (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n"))
  676. ((and org-footnote-section (not export-props))
  677. (or (bolp) (insert "\n"))
  678. (insert "* " org-footnote-section "\n")))
  679. ;; Insert the footnotes.
  680. (insert "\n"
  681. (mapconcat (lambda (x) (format "[%s] %s"
  682. (nth (if sort-only 0 1) x) (nth 2 x)))
  683. ref-table "\n\n")
  684. "\n\n")
  685. ;; When exporting, add newly inserted markers along with their
  686. ;; associated definition to `org-export-footnotes-seen'.
  687. (when export-props
  688. (setq org-export-footnotes-seen ref-table)))
  689. ;; Else, insert each definition at the end of the section
  690. ;; containing their first reference. Happens only in Org files
  691. ;; with no special footnote section, and only when doing
  692. ;; sorting.
  693. (t (mapc 'org-insert-footnote-reference-near-definition
  694. ref-table))))))
  695. (defun org-insert-footnote-reference-near-definition (entry)
  696. "Find first reference of footnote ENTRY and insert the definition there.
  697. ENTRY is (fn-label num-mark definition)."
  698. (when (car entry)
  699. (goto-char (point-min))
  700. (let ((ref (org-footnote-get-next-reference (car entry))))
  701. (when ref
  702. (goto-char (nth 2 ref))
  703. (org-footnote-goto-local-insertion-point)
  704. (insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
  705. (defun org-footnote-goto-local-insertion-point ()
  706. "Find insertion point for footnote, just before next outline heading."
  707. (org-with-limited-levels (outline-next-heading))
  708. (or (bolp) (newline))
  709. (beginning-of-line 0)
  710. (while (and (not (bobp)) (= (char-after) ?#))
  711. (beginning-of-line 0))
  712. (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
  713. (end-of-line 1)
  714. (skip-chars-backward "\n\r\t ")
  715. (forward-line))
  716. (defun org-footnote-delete-references (label)
  717. "Delete every reference to footnote LABEL.
  718. Return the number of footnotes removed."
  719. (save-excursion
  720. (goto-char (point-min))
  721. (let (ref (nref 0))
  722. (while (setq ref (org-footnote-get-next-reference label))
  723. (goto-char (nth 1 ref))
  724. (delete-region (nth 1 ref) (nth 2 ref))
  725. (incf nref))
  726. nref)))
  727. (defun org-footnote-delete-definitions (label)
  728. "Delete every definition of the footnote LABEL.
  729. Return the number of footnotes removed."
  730. (save-excursion
  731. (goto-char (point-min))
  732. (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
  733. (ndef 0))
  734. (while (re-search-forward def-re nil t)
  735. (let ((full-def (org-footnote-at-definition-p)))
  736. (delete-region (nth 1 full-def) (nth 2 full-def)))
  737. (incf ndef))
  738. ndef)))
  739. (defun org-footnote-delete (&optional label)
  740. "Delete the footnote at point.
  741. This will remove the definition (even multiple definitions if they exist)
  742. and all references of a footnote label.
  743. If LABEL is non-nil, delete that footnote instead."
  744. (catch 'done
  745. (let* ((nref 0) (ndef 0) x
  746. ;; 1. Determine LABEL of footnote at point.
  747. (label (cond
  748. ;; LABEL is provided as argument.
  749. (label)
  750. ;; Footnote reference at point. If the footnote is
  751. ;; anonymous, delete it and exit instead.
  752. ((setq x (org-footnote-at-reference-p))
  753. (or (car x)
  754. (progn
  755. (delete-region (nth 1 x) (nth 2 x))
  756. (message "Anonymous footnote removed")
  757. (throw 'done t))))
  758. ;; Footnote definition at point.
  759. ((setq x (org-footnote-at-definition-p))
  760. (car x))
  761. (t (error "Don't know which footnote to remove")))))
  762. ;; 2. Now that LABEL is non-nil, find every reference and every
  763. ;; definition, and delete them.
  764. (setq nref (org-footnote-delete-references label)
  765. ndef (org-footnote-delete-definitions label))
  766. ;; 3. Verify consistency of footnotes and notify user.
  767. (org-footnote-auto-adjust-maybe)
  768. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  769. ndef nref label))))
  770. (defun org-footnote-renumber-fn:N ()
  771. "Renumber the simple footnotes like fn:17 into a sequence in the document."
  772. (interactive)
  773. (let (map i (n 0))
  774. (save-excursion
  775. (save-restriction
  776. (widen)
  777. (goto-char (point-min))
  778. (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
  779. (setq i (string-to-number (match-string 1)))
  780. (when (and (string-match "\\S-" (buffer-substring
  781. (point-at-bol) (match-beginning 0)))
  782. (not (assq i map)))
  783. (push (cons i (number-to-string (incf n))) map)))
  784. (goto-char (point-min))
  785. (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
  786. (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
  787. (defun org-footnote-auto-adjust-maybe ()
  788. "Renumber and/or sort footnotes according to user settings."
  789. (when (memq org-footnote-auto-adjust '(t renumber))
  790. (org-footnote-renumber-fn:N))
  791. (when (memq org-footnote-auto-adjust '(t sort))
  792. (let ((label (car (org-footnote-at-definition-p))))
  793. (org-footnote-normalize 'sort)
  794. (when label
  795. (goto-char (point-min))
  796. (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
  797. nil t)
  798. (progn (insert " ")
  799. (just-one-space)))))))
  800. (provide 'org-footnote)
  801. ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
  802. ;;; org-footnote.el ends here