org-footnote.el 33 KB

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