org-footnote.el 34 KB

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