org-footnote.el 35 KB

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