org-footnote.el 34 KB

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