org-footnote.el 36 KB

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