org-footnote.el 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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" "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. (not (org-inside-latex-macro-p)))
  207. (list label beg end
  208. ;; Definition: ensure this is an inline footnote first.
  209. (and (or (not label) (match-string 1))
  210. (org-trim (buffer-substring-no-properties
  211. (match-end 0) (1- end)))))))))
  212. (defun org-footnote-at-definition-p ()
  213. "Is point within a footnote definition?
  214. This matches only pure definitions like [1] or [fn:name] at the
  215. beginning of a line. It does not match references like
  216. \[fn:name:definition], where the footnote text is included and
  217. defined locally.
  218. The return value will be nil if not at a footnote definition, and
  219. a list with label, start, end and definition of the footnote
  220. otherwise."
  221. (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
  222. (save-excursion
  223. (end-of-line)
  224. ;; Footnotes definitions are separated by new headlines or blank
  225. ;; lines.
  226. (let ((lim (save-excursion (re-search-backward
  227. (concat org-outline-regexp-bol
  228. "\\|^[ \t]*$") nil t))))
  229. (when (re-search-backward org-footnote-definition-re lim t)
  230. (let ((label (org-match-string-no-properties 1))
  231. (beg (match-beginning 0))
  232. (beg-def (match-end 0))
  233. ;; In message-mode, do not search after signature.
  234. (end (let ((bound (and (derived-mode-p 'message-mode)
  235. (save-excursion
  236. (goto-char (point-max))
  237. (re-search-backward
  238. message-signature-separator nil t)))))
  239. (if (progn
  240. (end-of-line)
  241. (re-search-forward
  242. (concat org-outline-regexp-bol "\\|"
  243. org-footnote-definition-re "\\|"
  244. "^[ \t]*$") bound 'move))
  245. (match-beginning 0)
  246. (point)))))
  247. (list label beg end
  248. (org-trim (buffer-substring-no-properties beg-def end)))))))))
  249. (defun org-footnote-get-next-reference (&optional label backward limit)
  250. "Return complete reference of the next footnote.
  251. If LABEL is provided, get the next reference of that footnote. If
  252. BACKWARD is non-nil, find previous reference instead. LIMIT is
  253. the buffer position bounding the search.
  254. Return value is a list like those provided by `org-footnote-at-reference-p'.
  255. If no footnote is found, return nil."
  256. (save-excursion
  257. (let* ((label-fmt (if label (format "\\[%s[]:]" label) org-footnote-re)))
  258. (catch 'exit
  259. (while t
  260. (unless (funcall (if backward #'re-search-backward #'re-search-forward)
  261. label-fmt limit t)
  262. (throw 'exit nil))
  263. (unless backward (backward-char))
  264. (let ((ref (org-footnote-at-reference-p)))
  265. (when ref (throw 'exit ref))))))))
  266. (defun org-footnote-next-reference-or-definition (limit)
  267. "Move point to next footnote reference or definition.
  268. LIMIT is the buffer position bounding the search.
  269. Return value is a list like those provided by
  270. `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
  271. If no footnote is found, return nil."
  272. (let* (ref (origin (point)))
  273. (catch 'exit
  274. (while t
  275. (unless (re-search-forward org-footnote-re limit t)
  276. (goto-char origin)
  277. (throw 'exit nil))
  278. ;; Beware: with [1]-like footnotes point will be just after
  279. ;; the closing square bracket.
  280. (backward-char)
  281. (cond
  282. ((setq ref (org-footnote-at-reference-p))
  283. (throw 'exit ref))
  284. ;; Definition: also grab the last square bracket, only
  285. ;; matched in `org-footnote-re' for [1]-like footnotes.
  286. ((save-match-data (org-footnote-at-definition-p))
  287. (let ((end (match-end 0)))
  288. (throw 'exit
  289. (list nil (match-beginning 0)
  290. (if (eq (char-before end) 93) end (1+ end)))))))))))
  291. (defun org-footnote-get-definition (label)
  292. "Return label, boundaries and definition of the footnote LABEL."
  293. (let* ((label (regexp-quote (org-footnote-normalize-label label)))
  294. (re (format "^\\[%s\\]\\|.\\[%s:" label label))
  295. pos)
  296. (save-excursion
  297. (save-restriction
  298. (when (or (re-search-forward re nil t)
  299. (and (goto-char (point-min))
  300. (re-search-forward re nil t))
  301. (and (progn (widen) t)
  302. (goto-char (point-min))
  303. (re-search-forward re nil t)))
  304. (let ((refp (org-footnote-at-reference-p)))
  305. (cond
  306. ((and (nth 3 refp) refp))
  307. ((org-footnote-at-definition-p)))))))))
  308. (defun org-footnote-goto-definition (label)
  309. "Move point to the definition of the footnote LABEL.
  310. Return a non-nil value when a definition has been found."
  311. (interactive "sLabel: ")
  312. (org-mark-ring-push)
  313. (let ((def (org-footnote-get-definition label)))
  314. (if (not def)
  315. (error "Cannot find definition of footnote %s" label)
  316. (goto-char (nth 1 def))
  317. (looking-at (format "\\[%s\\]\\|\\[%s:" label label))
  318. (goto-char (match-end 0))
  319. (org-show-context 'link-search)
  320. (when (derived-mode-p 'org-mode)
  321. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))
  322. t)))
  323. (defun org-footnote-goto-previous-reference (label)
  324. "Find the first closest (to point) reference of footnote with label LABEL."
  325. (interactive "sLabel: ")
  326. (org-mark-ring-push)
  327. (let* ((label (org-footnote-normalize-label label)) ref)
  328. (save-excursion
  329. (setq ref (or (org-footnote-get-next-reference label t)
  330. (org-footnote-get-next-reference label)
  331. (save-restriction
  332. (widen)
  333. (or
  334. (org-footnote-get-next-reference label t)
  335. (org-footnote-get-next-reference label))))))
  336. (if (not ref)
  337. (error "Cannot find reference of footnote %s" label)
  338. (goto-char (nth 1 ref))
  339. (org-show-context 'link-search))))
  340. (defun org-footnote-normalize-label (label)
  341. "Return LABEL as an appropriate string."
  342. (cond
  343. ((numberp label) (number-to-string label))
  344. ((equal "" label) nil)
  345. ((not (string-match "^[0-9]+$\\|^fn:" label))
  346. (concat "fn:" label))
  347. (t label)))
  348. (defun org-footnote-all-labels (&optional with-defs)
  349. "Return list with all defined foot labels used in the buffer.
  350. If WITH-DEFS is non-nil, also associate the definition to each
  351. label. The function will then return an alist whose key is label
  352. and value definition."
  353. (let* (rtn
  354. (push-to-rtn
  355. (function
  356. ;; Depending on WITH-DEFS, store label or (label . def) of
  357. ;; footnote reference/definition given as argument in RTN.
  358. (lambda (el)
  359. (let ((lbl (car el)))
  360. (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
  361. (save-excursion
  362. (save-restriction
  363. (widen)
  364. ;; Find all labels found in definitions.
  365. (goto-char (point-min))
  366. (let (def)
  367. (while (re-search-forward org-footnote-definition-re nil t)
  368. (when (setq def (org-footnote-at-definition-p))
  369. (funcall push-to-rtn def))))
  370. ;; Find all labels found in references.
  371. (goto-char (point-min))
  372. (let (ref)
  373. (while (setq ref (org-footnote-get-next-reference))
  374. (goto-char (nth 2 ref))
  375. (and (car ref) ; ignore anonymous footnotes
  376. (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
  377. (funcall push-to-rtn ref))))))
  378. rtn))
  379. (defun org-footnote-unique-label (&optional current)
  380. "Return a new unique footnote label.
  381. The function returns the first \"fn:N\" or \"N\" label that is
  382. currently not used.
  383. Optional argument CURRENT is the list of labels active in the
  384. buffer."
  385. (unless current (setq current (org-footnote-all-labels)))
  386. (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
  387. (cnt 1))
  388. (while (member (format fmt cnt) current)
  389. (incf cnt))
  390. (format fmt cnt)))
  391. (defun org-footnote-new ()
  392. "Insert a new footnote.
  393. This command prompts for a label. If this is a label referencing an
  394. existing label, only insert the label. If the footnote label is empty
  395. or new, let the user edit the definition of the footnote."
  396. (interactive)
  397. (unless (org-footnote-in-valid-context-p)
  398. (error "Cannot insert a footnote here"))
  399. (let* ((lbls (and (not (equal org-footnote-auto-label 'random))
  400. (org-footnote-all-labels)))
  401. (propose (and (not (equal org-footnote-auto-label 'random))
  402. (org-footnote-unique-label lbls)))
  403. (label
  404. (org-footnote-normalize-label
  405. (cond
  406. ((member org-footnote-auto-label '(t plain))
  407. propose)
  408. ((equal org-footnote-auto-label 'random)
  409. (require 'org-id)
  410. (substring (org-id-uuid) 0 8))
  411. (t
  412. (org-icompleting-read
  413. "Label (leave empty for anonymous): "
  414. (mapcar 'list lbls) nil nil
  415. (if (eq org-footnote-auto-label 'confirm) propose nil)))))))
  416. (cond
  417. ((bolp) (error "Cannot create a footnote reference at left margin"))
  418. ((not label)
  419. (insert "[fn:: ]")
  420. (backward-char 1))
  421. ((member label lbls)
  422. (insert "[" label "]")
  423. (message "New reference to existing note"))
  424. (org-footnote-define-inline
  425. (insert "[" label ": ]")
  426. (backward-char 1)
  427. (org-footnote-auto-adjust-maybe))
  428. (t
  429. (insert "[" label "]")
  430. (org-footnote-create-definition label)
  431. (org-footnote-auto-adjust-maybe)))))
  432. (defvar org-blank-before-new-entry) ; silence byte-compiler
  433. (defun org-footnote-create-definition (label)
  434. "Start the definition of a footnote with label LABEL."
  435. (interactive "sLabel: ")
  436. (let ((label (org-footnote-normalize-label label))
  437. electric-indent-mode) ;; Prevent wrong indentation
  438. (cond
  439. ;; In an Org file.
  440. ((derived-mode-p 'org-mode)
  441. ;; If `org-footnote-section' is defined, find it, or create it
  442. ;; at the end of the buffer.
  443. (when org-footnote-section
  444. (goto-char (point-min))
  445. (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
  446. (unless (or (re-search-forward re nil t)
  447. (and (progn (widen) t)
  448. (re-search-forward re nil t)))
  449. (goto-char (point-max))
  450. (skip-chars-backward " \t\r\n")
  451. (unless (bolp) (newline))
  452. ;; Insert new section. Separate it from the previous one
  453. ;; with a blank line, unless `org-blank-before-new-entry'
  454. ;; explicitly says no.
  455. (when (and (cdr (assq 'heading org-blank-before-new-entry))
  456. (zerop (save-excursion (org-back-over-empty-lines))))
  457. (insert "\n"))
  458. (insert "* " org-footnote-section "\n"))))
  459. ;; Move to the end of this entry (which may be
  460. ;; `org-footnote-section' or the current one).
  461. (org-footnote-goto-local-insertion-point)
  462. (org-show-context 'link-search))
  463. (t
  464. ;; In a non-Org file. Search for footnote tag, or create it if
  465. ;; specified (at the end of buffer, or before signature if in
  466. ;; Message mode). Set point after any definition already there.
  467. (let ((tag (and org-footnote-tag-for-non-org-mode-files
  468. (concat "^" (regexp-quote
  469. org-footnote-tag-for-non-org-mode-files)
  470. "[ \t]*$")))
  471. (max (if (and (derived-mode-p 'message-mode)
  472. (goto-char (point-max))
  473. (re-search-backward
  474. message-signature-separator nil t))
  475. (progn
  476. ;; Ensure one blank line separates last
  477. ;; footnote from signature.
  478. (beginning-of-line)
  479. (open-line 2)
  480. (point-marker))
  481. (point-max-marker))))
  482. (set-marker-insertion-type max t)
  483. (goto-char max)
  484. ;; Check if the footnote tag is defined but missing. In this
  485. ;; case, insert it, before any footnote or one blank line
  486. ;; after any previous text.
  487. (when (and tag (not (re-search-backward tag nil t)))
  488. (skip-chars-backward " \t\r\n")
  489. (while (re-search-backward org-footnote-definition-re nil t))
  490. (unless (bolp) (newline 2))
  491. (insert org-footnote-tag-for-non-org-mode-files "\n\n"))
  492. ;; Remove superfluous white space and clear marker.
  493. (goto-char max)
  494. (skip-chars-backward " \t\r\n")
  495. (delete-region (point) max)
  496. (unless (bolp) (newline))
  497. (set-marker max nil))))
  498. ;; Insert footnote label.
  499. (when (zerop (org-back-over-empty-lines)) (newline))
  500. (insert "[" label "] \n")
  501. (backward-char)
  502. ;; Only notify user about next possible action when in an Org
  503. ;; buffer, as the bindings may have different meanings otherwise.
  504. (when (derived-mode-p 'org-mode)
  505. (message
  506. "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
  507. ;;;###autoload
  508. (defun org-footnote-action (&optional special)
  509. "Do the right thing for footnotes.
  510. When at a footnote reference, jump to the definition.
  511. When at a definition, jump to the references if they exist, offer
  512. to create them otherwise.
  513. When neither at definition or reference, create a new footnote,
  514. interactively.
  515. With prefix arg SPECIAL, offer additional commands in a menu."
  516. (interactive "P")
  517. (let (tmp c)
  518. (cond
  519. (special
  520. (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
  521. (setq c (read-char-exclusive))
  522. (cond
  523. ((eq c ?s) (org-footnote-normalize 'sort))
  524. ((eq c ?r) (org-footnote-renumber-fn:N))
  525. ((eq c ?S)
  526. (org-footnote-renumber-fn:N)
  527. (org-footnote-normalize 'sort))
  528. ((eq c ?n) (org-footnote-normalize))
  529. ((eq c ?d) (org-footnote-delete))
  530. (t (error "No such footnote command %c" c))))
  531. ((setq tmp (org-footnote-at-reference-p))
  532. (cond
  533. ;; Anonymous footnote: move point at the beginning of its
  534. ;; definition.
  535. ((not (car tmp))
  536. (goto-char (nth 1 tmp))
  537. (forward-char 5))
  538. ;; A definition exists: move to it.
  539. ((ignore-errors (org-footnote-goto-definition (car tmp))))
  540. ;; No definition exists: offer to create it.
  541. ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
  542. (org-footnote-create-definition (car tmp)))))
  543. ((setq tmp (org-footnote-at-definition-p))
  544. (org-footnote-goto-previous-reference (car tmp)))
  545. (t (org-footnote-new)))))
  546. ;;;###autoload
  547. (defun org-footnote-normalize (&optional sort-only)
  548. "Collect the footnotes in various formats and normalize them.
  549. This finds the different sorts of footnotes allowed in Org, and
  550. normalizes them to the usual [N] format.
  551. When SORT-ONLY is set, only sort the footnote definitions into the
  552. referenced sequence."
  553. ;; This is based on Paul's function, but rewritten.
  554. ;;
  555. ;; Re-create `org-with-limited-levels', but not limited to Org
  556. ;; buffers.
  557. (let* ((limit-level
  558. (and (boundp 'org-inlinetask-min-level)
  559. org-inlinetask-min-level
  560. (1- org-inlinetask-min-level)))
  561. (nstars (and limit-level
  562. (if org-odd-levels-only (1- (* limit-level 2))
  563. limit-level)))
  564. (org-outline-regexp
  565. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  566. (count 0)
  567. ins-point ref ref-table)
  568. (save-excursion
  569. ;; 1. Find every footnote reference, extract the definition, and
  570. ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
  571. ;; normalize references.
  572. (goto-char (point-min))
  573. (while (setq ref (org-footnote-get-next-reference))
  574. (let* ((lbl (car ref))
  575. (pos (nth 1 ref))
  576. ;; When footnote isn't anonymous, check if it's label
  577. ;; (REF) is already stored in REF-TABLE. In that case,
  578. ;; extract number used to identify it (MARKER). If
  579. ;; footnote is unknown, increment the global counter
  580. ;; (COUNT) to create an unused identifier.
  581. (a (and lbl (assoc lbl ref-table)))
  582. (marker (or (nth 1 a) (incf count)))
  583. ;; Is the reference inline or pointing to an inline
  584. ;; footnote?
  585. (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
  586. ;; Replace footnote reference with [MARKER]. Maybe fill
  587. ;; paragraph once done. If SORT-ONLY is non-nil, only move
  588. ;; to the end of reference found to avoid matching it twice.
  589. (if sort-only (goto-char (nth 2 ref))
  590. (delete-region (nth 1 ref) (nth 2 ref))
  591. (goto-char (nth 1 ref))
  592. (insert (format "[%d]" marker))
  593. (and inlinep
  594. org-footnote-fill-after-inline-note-extraction
  595. (org-fill-paragraph)))
  596. ;; Add label (REF), identifier (MARKER), definition (DEF)
  597. ;; type (INLINEP) and position (POS) to REF-TABLE if data
  598. ;; was unknown.
  599. (unless a
  600. (let ((def (or (nth 3 ref) ; Inline definition.
  601. (nth 3 (org-footnote-get-definition lbl)))))
  602. (push (list lbl marker def
  603. ;; Reference beginning position is a marker
  604. ;; to preserve it during further buffer
  605. ;; modifications.
  606. inlinep (copy-marker pos)) ref-table)))))
  607. ;; 2. Find and remove the footnote section, if any. Also
  608. ;; determine where footnotes shall be inserted (INS-POINT).
  609. (cond
  610. ((and org-footnote-section (derived-mode-p 'org-mode))
  611. (goto-char (point-min))
  612. (if (re-search-forward
  613. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  614. "[ \t]*$") nil t)
  615. (delete-region (match-beginning 0) (org-end-of-subtree t t)))
  616. ;; A new footnote section is inserted by default at the end of
  617. ;; the buffer.
  618. (goto-char (point-max))
  619. (skip-chars-backward " \r\t\n")
  620. (forward-line)
  621. (unless (bolp) (newline)))
  622. ;; No footnote section set: Footnotes will be added at the end
  623. ;; of the section containing their first reference.
  624. ((derived-mode-p 'org-mode))
  625. (t
  626. ;; Remove any left-over tag in the buffer, if one is set up.
  627. (when org-footnote-tag-for-non-org-mode-files
  628. (let ((tag (concat "^" (regexp-quote
  629. org-footnote-tag-for-non-org-mode-files)
  630. "[ \t]*$")))
  631. (goto-char (point-min))
  632. (while (re-search-forward tag nil t)
  633. (replace-match "")
  634. (delete-region (point) (progn (forward-line) (point))))))
  635. ;; In Message mode, ensure footnotes are inserted before the
  636. ;; signature.
  637. (if (and (derived-mode-p 'message-mode)
  638. (goto-char (point-max))
  639. (re-search-backward message-signature-separator nil t))
  640. (beginning-of-line)
  641. (goto-char (point-max)))))
  642. (setq ins-point (point-marker))
  643. ;; 3. Clean-up REF-TABLE.
  644. (setq ref-table
  645. (delq nil
  646. (mapcar
  647. (lambda (x)
  648. (cond
  649. ;; When only sorting, ignore inline footnotes.
  650. ;; Also clear position marker.
  651. ((and sort-only (nth 3 x))
  652. (set-marker (nth 4 x) nil) nil)
  653. ;; No definition available: provide one.
  654. ((not (nth 2 x))
  655. (append
  656. (list (car x) (nth 1 x)
  657. (format "DEFINITION NOT FOUND: %s" (car x)))
  658. (nthcdr 3 x)))
  659. (t x)))
  660. ref-table)))
  661. (setq ref-table (nreverse ref-table))
  662. ;; 4. Remove left-over definitions in the buffer.
  663. (mapc (lambda (x)
  664. (unless (nth 3 x) (org-footnote-delete-definitions (car x))))
  665. ref-table)
  666. ;; 5. Insert the footnotes again in the buffer, at the
  667. ;; appropriate spot.
  668. (goto-char ins-point)
  669. (cond
  670. ;; No footnote: exit.
  671. ((not ref-table))
  672. ;; Cases when footnotes should be inserted in one place.
  673. ((or (not (derived-mode-p 'org-mode)) org-footnote-section)
  674. ;; Insert again the section title, if any. Ensure that title,
  675. ;; or the subsequent footnotes, will be separated by a blank
  676. ;; lines from the rest of the document. In an Org buffer,
  677. ;; separate section with a blank line, unless explicitly
  678. ;; stated in `org-blank-before-new-entry'.
  679. (if (not (derived-mode-p 'org-mode))
  680. (progn (skip-chars-backward " \t\n\r")
  681. (delete-region (point) ins-point)
  682. (unless (bolp) (newline))
  683. (when org-footnote-tag-for-non-org-mode-files
  684. (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
  685. (when (and (cdr (assq 'heading org-blank-before-new-entry))
  686. (zerop (save-excursion (org-back-over-empty-lines))))
  687. (insert "\n"))
  688. (insert "* " org-footnote-section "\n"))
  689. (set-marker ins-point nil)
  690. ;; Insert the footnotes, separated by a blank line.
  691. (insert
  692. (mapconcat
  693. (lambda (x)
  694. ;; Clean markers.
  695. (set-marker (nth 4 x) nil)
  696. (format "\n[%s] %s" (nth (if sort-only 0 1) x) (nth 2 x)))
  697. ref-table "\n"))
  698. (unless (eobp) (insert "\n\n")))
  699. ;; Each footnote definition has to be inserted at the end of
  700. ;; the section where its first reference belongs.
  701. (t
  702. (mapc
  703. (lambda (x)
  704. (let ((pos (nth 4 x)))
  705. (goto-char pos)
  706. ;; Clean marker.
  707. (set-marker pos nil))
  708. (org-footnote-goto-local-insertion-point)
  709. (insert (format "\n[%s] %s\n"
  710. (if sort-only (car x) (nth 1 x))
  711. (nth 2 x))))
  712. ref-table))))))
  713. (defun org-footnote-goto-local-insertion-point ()
  714. "Find insertion point for footnote, just before next outline heading."
  715. (org-with-limited-levels (outline-next-heading))
  716. (or (bolp) (newline))
  717. (beginning-of-line 0)
  718. (while (and (not (bobp)) (= (char-after) ?#))
  719. (beginning-of-line 0))
  720. (if (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:")) (beginning-of-line 2))
  721. (end-of-line 1)
  722. (skip-chars-backward "\n\r\t ")
  723. (forward-line))
  724. (defun org-footnote-delete-references (label)
  725. "Delete every reference to footnote LABEL.
  726. Return the number of footnotes removed."
  727. (save-excursion
  728. (goto-char (point-min))
  729. (let (ref (nref 0))
  730. (while (setq ref (org-footnote-get-next-reference label))
  731. (goto-char (nth 1 ref))
  732. (delete-region (nth 1 ref) (nth 2 ref))
  733. (incf nref))
  734. nref)))
  735. (defun org-footnote-delete-definitions (label)
  736. "Delete every definition of the footnote LABEL.
  737. Return the number of footnotes removed."
  738. (save-excursion
  739. (goto-char (point-min))
  740. (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
  741. (ndef 0))
  742. (while (re-search-forward def-re nil t)
  743. (let ((full-def (org-footnote-at-definition-p)))
  744. (when full-def
  745. ;; Remove the footnote, and all blank lines before it.
  746. (goto-char (nth 1 full-def))
  747. (skip-chars-backward " \r\t\n")
  748. (unless (bolp) (forward-line))
  749. (delete-region (point) (nth 2 full-def))
  750. (incf ndef))))
  751. ndef)))
  752. (defun org-footnote-delete (&optional label)
  753. "Delete the footnote at point.
  754. This will remove the definition (even multiple definitions if they exist)
  755. and all references of a footnote label.
  756. If LABEL is non-nil, delete that footnote instead."
  757. (catch 'done
  758. (let* ((nref 0) (ndef 0) x
  759. ;; 1. Determine LABEL of footnote at point.
  760. (label (cond
  761. ;; LABEL is provided as argument.
  762. (label)
  763. ;; Footnote reference at point. If the footnote is
  764. ;; anonymous, delete it and exit instead.
  765. ((setq x (org-footnote-at-reference-p))
  766. (or (car x)
  767. (progn
  768. (delete-region (nth 1 x) (nth 2 x))
  769. (message "Anonymous footnote removed")
  770. (throw 'done t))))
  771. ;; Footnote definition at point.
  772. ((setq x (org-footnote-at-definition-p))
  773. (car x))
  774. (t (error "Don't know which footnote to remove")))))
  775. ;; 2. Now that LABEL is non-nil, find every reference and every
  776. ;; definition, and delete them.
  777. (setq nref (org-footnote-delete-references label)
  778. ndef (org-footnote-delete-definitions label))
  779. ;; 3. Verify consistency of footnotes and notify user.
  780. (org-footnote-auto-adjust-maybe)
  781. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  782. ndef nref label))))
  783. (defun org-footnote-renumber-fn:N ()
  784. "Renumber the simple footnotes like fn:17 into a sequence in the document."
  785. (interactive)
  786. (let (map (n 0))
  787. (org-with-wide-buffer
  788. (goto-char (point-min))
  789. (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
  790. (save-excursion
  791. (goto-char (match-beginning 0))
  792. ;; Ensure match is a footnote reference or definition.
  793. (when (save-match-data (if (bolp)
  794. (org-footnote-at-definition-p)
  795. (org-footnote-at-reference-p)))
  796. (let ((new-val (or (cdr (assoc (match-string 1) map))
  797. (number-to-string (incf n)))))
  798. (unless (assoc (match-string 1) map)
  799. (push (cons (match-string 1) new-val) map))
  800. (replace-match new-val nil nil nil 1))))))))
  801. (defun org-footnote-auto-adjust-maybe ()
  802. "Renumber and/or sort footnotes according to user settings."
  803. (when (memq org-footnote-auto-adjust '(t renumber))
  804. (org-footnote-renumber-fn:N))
  805. (when (memq org-footnote-auto-adjust '(t sort))
  806. (let ((label (car (org-footnote-at-definition-p))))
  807. (org-footnote-normalize 'sort)
  808. (when label
  809. (goto-char (point-min))
  810. (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
  811. nil t)
  812. (progn (insert " ")
  813. (just-one-space)))))))
  814. (provide 'org-footnote)
  815. ;; Local variables:
  816. ;; generated-autoload-file: "org-loaddefs.el"
  817. ;; End:
  818. ;;; org-footnote.el ends here