org-footnote.el 34 KB

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