org-footnote.el 33 KB

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