org-footnote.el 35 KB

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