org-footnote.el 32 KB

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