org-footnote.el 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. ;;; org-footnote.el --- Footnote support in Org and elsewhere
  2. ;;
  3. ;; Copyright (C) 2009 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. ;; Version: 6.28
  9. ;;
  10. ;; This file is part of GNU Emacs.
  11. ;;
  12. ;; GNU Emacs is free software: you can redistribute it and/or modify
  13. ;; it under the terms of the GNU General Public License as published by
  14. ;; the Free Software Foundation, either version 3 of the License, or
  15. ;; (at your option) any later version.
  16. ;; GNU Emacs is distributed in the hope that it will be useful,
  17. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. ;; GNU General Public License for more details.
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  22. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
  23. ;;
  24. ;;; Commentary:
  25. ;; This file contains the code dealing with footnotes in Org-mode.
  26. ;; The code can also be used in arbitrary text modes to provide
  27. ;; footnotes. Compared to Steven L Baur's footnote.el it provides
  28. ;; better support for resuming editing. It is less configurable than
  29. ;; Steve's code, though.
  30. ;;; Code:
  31. (eval-when-compile
  32. (require 'cl))
  33. (require 'org-macs)
  34. (require 'org-compat)
  35. (declare-function org-in-regexp "org" (re &optional nlines visually))
  36. (declare-function org-mark-ring-push "org" (&optional pos buffer))
  37. (declare-function outline-next-heading "outline")
  38. (declare-function org-trim "org" (s))
  39. (declare-function org-show-context "org" (&optional key))
  40. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  41. (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
  42. (defvar org-odd-levels-only) ;; defined in org.el
  43. (defconst org-footnote-re
  44. (concat "[^][\n]" ; to make sure it is not at the beginning of a line
  45. "\\["
  46. "\\(?:"
  47. "\\([0-9]+\\)"
  48. "\\|"
  49. (org-re "\\(fn:\\([-_[:word:]]+?\\)?\\)\\(?::\\([^\]]*?\\)\\)?")
  50. "\\)"
  51. "\\]")
  52. "Regular expression for matching footnotes.")
  53. (defconst org-footnote-definition-re
  54. (org-re "^\\(\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]\\)")
  55. "Regular expression matching the definition of a footnote.")
  56. (defcustom org-footnote-section "Footnotes"
  57. "Outline heading containing footnote definitions before export.
  58. This can be nil, to place footnotes locally at the end of the current
  59. outline node. If can also be the name of a special outline heading
  60. under which footnotes should be put.
  61. This variable defines the place where Org puts the definition
  62. automatically, i.e. when creating the footnote, and when sorting the notes.
  63. However, by hand you may place definitions *anywhere*.
  64. If this is a string, during export, all subtrees starting with this
  65. heading will be removed after extracting footnote definitions."
  66. :group 'org-footnotes
  67. :type '(choice
  68. (string :tag "Collect fotnotes under heading")
  69. (const :tag "Define footnotes locally" nil)))
  70. (defcustom org-footnote-tag-for-non-org-mode-files "Footnotes:"
  71. "Tag marking the beginning of footnote section.
  72. The Org-mode footnote engine can be used in arbitrary text files as well
  73. as in Org-mode. Outside Org-mode, new footnotes are always placed at
  74. the end of the file. When you normalize the notes, any line containing
  75. only this tag will be removed, a new one will be inserted at the end
  76. of the file, followed by the collected and normalized footnotes."
  77. :group 'org-footnotes
  78. :type 'string)
  79. (defcustom org-footnote-define-inline nil
  80. "Non-nil means, define footnotes inline, at reference location.
  81. When nil, footnotes will be defined in a special section near
  82. the end of the document. When t, the [fn:label:definition] notation
  83. will be used to define the footnote at the reference position."
  84. :group 'org-footnote
  85. :type 'boolean)
  86. (defcustom org-footnote-auto-label t
  87. "Non-nil means, define automatically new labels for footnotes.
  88. Possible values are:
  89. nil prompt the user for each label
  90. t create unique labels of the form [fn:1], [fn:2], ...
  91. confirm like t, but let the user edit the created value. In particular,
  92. the label can be removed from the minibuffer, to create
  93. an anonymous footnote.
  94. plain Automatically create plain number labels like [1]"
  95. :group 'org-footnote
  96. :type '(choice
  97. (const :tag "Frompt for label" nil)
  98. (const :tag "Create automatic [fn:N]" t)
  99. (const :tag "Offer automatic [fn:N] for editing" confirm)
  100. (const :tag "Create automatic [N]" plain)))
  101. (defcustom org-footnote-fill-after-inline-note-extraction nil
  102. "Non-nil means, fill paragraphs after extracting footnotes.
  103. When extracting inline footnotes, the lengths of lines can change a lot.
  104. When this option is set, paragraphs from which an inline footnote has been
  105. extracted will be filled again."
  106. :group 'org-footnote
  107. :type 'boolean)
  108. (defun org-footnote-at-reference-p ()
  109. "Is the cursor at a footnote reference?
  110. If yes, return the beginning position, the label, and the definition, if local."
  111. (when (org-in-regexp org-footnote-re 15)
  112. (list (match-beginning 0)
  113. (or (match-string 1)
  114. (if (equal (match-string 2) "fn:") nil (match-string 2)))
  115. (match-string 4))))
  116. (defun org-footnote-at-definition-p ()
  117. "Is the cursor at a footnote definition.
  118. This matches only pure definitions like [1] or [fn:name] at the beginning
  119. of a line. It does not a references like [fn:name:definition], where the
  120. footnote text is included and defined locally.
  121. The return value will be nil if not at a footnote definition, and a list
  122. with start and label of the footnote if there is a definition at point."
  123. (save-excursion
  124. (end-of-line 1)
  125. (let ((lim (save-excursion (re-search-backward "^\\*+ \\|^[ \t]*$" nil t))))
  126. (when (re-search-backward org-footnote-definition-re lim t)
  127. (list (match-beginning 0) (match-string 2))))))
  128. (defun org-footnote-goto-definition (label)
  129. "Find the definition of the footnote with label LABEL."
  130. (interactive "sLabel: ")
  131. (org-mark-ring-push)
  132. (setq label (org-footnote-normalize-label label))
  133. (let ((re (format "^\\[%s\\]\\|.\\[%s:" label label))
  134. pos)
  135. (save-excursion
  136. (setq pos (or (re-search-forward re nil t)
  137. (and (goto-char (point-min))
  138. (re-search-forward re nil t))
  139. (and (progn (widen) t)
  140. (goto-char (point-min))
  141. (re-search-forward re nil t)))))
  142. (if (not pos)
  143. (error "Cannot find definition of footnote %s" label)
  144. (goto-char pos)
  145. (org-show-context 'link-search)
  146. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
  147. (defun org-footnote-goto-next-reference (label)
  148. "Find the definition of the footnote with label LABEL."
  149. (interactive "sLabel: ")
  150. (org-mark-ring-push)
  151. (setq label (org-footnote-normalize-label label))
  152. (let ((re (format ".\\[%s[]:]" label))
  153. (p0 (point)) pos)
  154. (save-excursion
  155. (setq pos (or (re-search-forward re nil t)
  156. (and (goto-char (point-min))
  157. (re-search-forward re nil t))
  158. (and (progn (widen) t)
  159. (goto-char p0)
  160. (re-search-forward re nil t))
  161. (and (goto-char (point-min))
  162. (re-search-forward re nil t)))))
  163. (if pos
  164. (progn
  165. (goto-char pos)
  166. (org-show-context 'link-search))
  167. (error "Cannot find reference of footnote %s" label))))
  168. (defun org-footnote-normalize-label (label)
  169. (if (numberp label) (setq label (number-to-string label)))
  170. (if (not (string-match "^[0-9]+$\\|^$\\|^fn:" label))
  171. (setq label (concat "fn:" label)))
  172. label)
  173. (defun org-footnote-all-labels ()
  174. "Return list with all defined foot labels used in the buffer."
  175. (let (rtn l)
  176. (save-excursion
  177. (save-restriction
  178. (widen)
  179. (goto-char (point-min))
  180. (while (re-search-forward org-footnote-definition-re nil t)
  181. (setq l (org-match-string-no-properties 2))
  182. (and l (add-to-list 'rtn l)))
  183. (goto-char (point-min))
  184. (while (re-search-forward org-footnote-re nil t)
  185. (setq l (or (org-match-string-no-properties 1)
  186. (org-match-string-no-properties 2)))
  187. (and l (not (equal l "fn:")) (add-to-list 'rtn l)))))
  188. rtn))
  189. (defun org-footnote-unique-label (&optional current)
  190. "Return a new unique footnote label.
  191. The returns the firsts fn:N labels that is currently not used."
  192. (unless current (setq current (org-footnote-all-labels)))
  193. (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
  194. (cnt 1))
  195. (while (member (format fmt cnt) current)
  196. (incf cnt))
  197. (format fmt cnt)))
  198. (defvar org-footnote-label-history nil
  199. "History of footnote labels entered in current buffer.")
  200. (make-variable-buffer-local 'org-footnote-label-history)
  201. (defun org-footnote-new ()
  202. "Insert a new footnote.
  203. This command prompts for a label. If this is a label referencing an
  204. existing label, only insert the label. If the footnote label is empty
  205. or new, let the user edit the definition of the footnote."
  206. (interactive)
  207. (let* ((labels (org-footnote-all-labels))
  208. (propose (org-footnote-unique-label labels))
  209. (label
  210. (if (member org-footnote-auto-label '(t plain))
  211. propose
  212. (completing-read
  213. "Label (leave empty for anonymous): "
  214. (mapcar 'list labels) nil nil
  215. (if (eq org-footnote-auto-label 'confirm) propose nil)
  216. 'org-footnote-label-history))))
  217. (setq label (org-footnote-normalize-label label))
  218. (cond
  219. ((equal label "")
  220. (insert "[fn:: ]")
  221. (backward-char 1))
  222. ((member label labels)
  223. (insert "[" label "]")
  224. (message "New reference to existing note"))
  225. (org-footnote-define-inline
  226. (insert "[" label ": ]")
  227. (backward-char 1))
  228. (t
  229. (insert "[" label "]")
  230. (org-footnote-create-definition label)))))
  231. (defun org-footnote-create-definition (label)
  232. "Start the definition of a footnote with label LABEL."
  233. (interactive "sLabel: ")
  234. (setq label (org-footnote-normalize-label label))
  235. (let (re)
  236. (cond
  237. ((org-mode-p)
  238. (if (not org-footnote-section)
  239. ;; No section, put footnote into the current outline node
  240. nil
  241. ;; Try to find or make the special node
  242. (setq re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$"))
  243. (unless (or (re-search-forward re nil t)
  244. (and (progn (widen) t)
  245. (re-search-forward re nil t)))
  246. (goto-char (point-max))
  247. (insert "\n\n* " org-footnote-section "\n")))
  248. ;; Now go to the end of this entry and insert there.
  249. (org-footnote-goto-local-insertion-point))
  250. (t
  251. (setq re (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$"))
  252. (unless (re-search-forward re nil t)
  253. (goto-char (point-max))
  254. (skip-chars-backward " \t\r\n")
  255. (insert "\n\n")
  256. (delete-region (point) (point-max))
  257. (insert org-footnote-tag-for-non-org-mode-files "\n"))
  258. (goto-char (point-max))
  259. (skip-chars-backward " \t\r\n")))
  260. (insert "\n\n")
  261. (insert "[" label "] ")
  262. (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
  263. ;;;###autoload
  264. (defun org-footnote-action (&optional special)
  265. "Do the right thing for footnotes.
  266. When at a footnote reference, jump to the definition. When at a definition,
  267. jump to the refernces. When neither at definition or reference,
  268. create a new footnote, interactively.
  269. With prefix arg SPECIAL, offer additional commands in a menu."
  270. (interactive "P")
  271. (let (tmp c)
  272. (cond
  273. (special
  274. (message "Footnotes: [s]ort | convert to [n]umeric | [d]elete")
  275. (setq c (read-char-exclusive))
  276. (cond
  277. ((equal c ?s)
  278. (org-footnote-normalize 'sort))
  279. ((equal c ?n)
  280. (org-footnote-normalize))
  281. ((equal c ?d)
  282. (org-footnote-delete))
  283. (t (error "No such footnote command %c" c))))
  284. ((setq tmp (org-footnote-at-reference-p))
  285. (if (nth 1 tmp)
  286. (org-footnote-goto-definition (nth 1 tmp))
  287. (goto-char (match-beginning 4))))
  288. ((setq tmp (org-footnote-at-definition-p))
  289. (org-footnote-goto-next-reference (nth 1 tmp)))
  290. (t (org-footnote-new)))))
  291. ;;;###autoload
  292. (defun org-footnote-normalize (&optional sort-only for-preprocessor)
  293. "Collect the footnotes in various formats and normalize them.
  294. This find the different sorts of footnotes allowed in Org, and
  295. normalizes them to the usual [N] format that is understood by the
  296. Org-mode exporters.
  297. When SORT-ONLY is set, only sort the footnote definitions into the
  298. referenced sequence."
  299. ;; This is based on Paul's function, but rewritten.
  300. (let* ((limit-level
  301. (and (boundp 'org-inlinetask-min-level)
  302. org-inlinetask-min-level
  303. (1- org-inlinetask-min-level)))
  304. (nstars (and limit-level
  305. (if org-odd-levels-only
  306. (and limit-level (1- (* limit-level 2)))
  307. limit-level)))
  308. (outline-regexp
  309. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  310. (count 0)
  311. ref def idef ref-table beg beg1 marker a before ins-point)
  312. (save-excursion
  313. ;; Now find footnote references, and extract the definitions
  314. (goto-char (point-min))
  315. (while (re-search-forward org-footnote-re nil t)
  316. (org-if-unprotected
  317. (setq def (match-string 4)
  318. idef def
  319. ref (or (match-string 1) (match-string 2))
  320. before (char-to-string (char-after (match-beginning 0))))
  321. (if (equal ref "fn:") (setq ref nil))
  322. (if (and ref (setq a (assoc ref ref-table)))
  323. (progn
  324. (setq marker (nth 1 a))
  325. (unless (nth 2 a) (setf (caddr a) def)))
  326. (setq marker (number-to-string (incf count))))
  327. (save-match-data
  328. (if def
  329. (setq def (org-trim def))
  330. (save-excursion
  331. (goto-char (point-min))
  332. (if (not (re-search-forward (concat "^\\[" (regexp-quote ref)
  333. "\\]") nil t))
  334. (setq def nil)
  335. (setq beg (match-beginning 0))
  336. (setq beg1 (match-end 0))
  337. (re-search-forward
  338. (org-re "^[ \t]*$\\|^\\*+ \\|^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
  339. nil 'move)
  340. (setq def (buffer-substring beg1 (or (match-beginning 0)
  341. (point-max))))
  342. (goto-char beg)
  343. (skip-chars-backward " \t\n\t")
  344. (delete-region (1+ (point)) (match-beginning 0))))))
  345. (unless sort-only
  346. (replace-match (concat before "[" marker "]"))
  347. (and idef
  348. org-footnote-fill-after-inline-note-extraction
  349. (fill-paragraph)))
  350. (if (not a) (push (list ref marker def (if idef t nil)) ref-table))))
  351. ;; First find and remove the footnote section
  352. (goto-char (point-min))
  353. (cond
  354. ((org-mode-p)
  355. (if (and org-footnote-section
  356. (re-search-forward
  357. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  358. "[ \t]*$")
  359. nil t))
  360. (if (or for-preprocessor (not org-footnote-section))
  361. (replace-match "")
  362. (org-back-to-heading t)
  363. (forward-line 1)
  364. (setq ins-point (point))
  365. (delete-region (point) (org-end-of-subtree t)))
  366. (goto-char (point-max))
  367. (unless for-preprocessor
  368. (when org-footnote-section
  369. (or (bolp) (insert "\n"))
  370. (insert "* " org-footnote-section "\n")
  371. (setq ins-point (point))))))
  372. (t
  373. (if (re-search-forward
  374. (concat "^"
  375. (regexp-quote org-footnote-tag-for-non-org-mode-files)
  376. "[ \t]*$")
  377. nil t)
  378. (replace-match ""))
  379. (goto-char (point-max))
  380. (skip-chars-backward " \t\n\r")
  381. (delete-region (point) (point-max))
  382. (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n")
  383. (setq ins-point (point))))
  384. ;; Insert the footnotes again
  385. (goto-char (or ins-point (point-max)))
  386. (setq ref-table (reverse ref-table))
  387. (when sort-only
  388. ;; remove anonymous and inline footnotes from the list
  389. (setq ref-table
  390. (delq nil (mapcar
  391. (lambda (x) (and (car x)
  392. (not (equal (car x) "fn:"))
  393. (not (nth 3 x))
  394. x))
  395. ref-table))))
  396. ;; Make sure each footnote has a description, or an error message.
  397. (setq ref-table
  398. (mapcar
  399. (lambda (x)
  400. (if (not (nth 2 x))
  401. (setcar (cddr x)
  402. (format "FOOTNOTE DEFINITION NOT FOUND: %s" (car x)))
  403. (setcar (cddr x) (org-trim (nth 2 x))))
  404. x)
  405. ref-table))
  406. (if (or (not (org-mode-p)) ; not an Org file
  407. org-footnote-section ; we do not use a footnote section
  408. (not sort-only) ; this is normalization
  409. for-preprocessor) ; the is the preprocessor
  410. ;; Insert the footnotes together in one place
  411. (progn
  412. (setq def
  413. (mapconcat
  414. (lambda (x)
  415. (format "[%s] %s" (nth (if sort-only 0 1) x)
  416. (org-trim (nth 2 x))))
  417. ref-table "\n\n"))
  418. (if ref-table (insert "\n" def "\n\n")))
  419. ;; Insert each footnote near the first reference
  420. ;; Happens only in Org files with no special footnote section,
  421. ;; and only when doing sorting
  422. (mapc 'org-insert-footnote-reference-near-definition
  423. ref-table)))))
  424. (defun org-insert-footnote-reference-near-definition (entry)
  425. "Find first reference of footnote ENTRY and insert the definition there.
  426. ENTRY is (fn-label num-mark definition)."
  427. (when (car entry)
  428. (goto-char (point-min))
  429. (when (re-search-forward (format ".\\[%s[]:]" (regexp-quote (car entry)))
  430. nil t)
  431. (org-footnote-goto-local-insertion-point)
  432. (insert (format "\n\n[%s] %s" (car entry) (nth 2 entry))))))
  433. (defun org-footnote-goto-local-insertion-point ()
  434. "Find insertion point for footnote, just before next outline heading."
  435. (outline-next-heading)
  436. (or (bolp) (newline))
  437. (beginning-of-line 0)
  438. (while (and (not (bobp)) (= (char-after) ?#))
  439. (beginning-of-line 0))
  440. (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
  441. (end-of-line 1)
  442. (skip-chars-backward "\n\r\t "))
  443. (defun org-footnote-delete (&optional label)
  444. "Delete the footnote at point.
  445. This will remove the definition (even multiple definitions if they exist)
  446. and all references of a footnote label."
  447. (catch 'done
  448. (let (x label l beg def-re (nref 0) (ndef 0))
  449. (unless label
  450. (when (setq x (org-footnote-at-reference-p))
  451. (setq label (nth 1 x))
  452. (when (or (not label) (equal "fn:" label))
  453. (delete-region (1+ (match-beginning 0)) (match-end 0))
  454. (message "Anonymous footnote removed")
  455. (throw 'done t)))
  456. (when (and (not label) (setq x (org-footnote-at-definition-p)))
  457. (setq label (nth 1 x)))
  458. (unless label (error "Don't know which footnote to remove")))
  459. (save-excursion
  460. (save-restriction
  461. (goto-char (point-min))
  462. (while (re-search-forward org-footnote-re nil t)
  463. (setq l (or (match-string 1) (match-string 2)))
  464. (when (equal l label)
  465. (delete-region (1+ (match-beginning 0)) (match-end 0))
  466. (incf nref)))
  467. (goto-char (point-min))
  468. (setq def-re (concat "^\\[" (regexp-quote label) "\\]"))
  469. (while (re-search-forward def-re nil t)
  470. (setq beg (match-beginning 0))
  471. (if (re-search-forward "^\\[\\|^[ \t]*$\\|^\\*+ " nil t)
  472. (goto-char (match-beginning 0))
  473. (goto-char (point-max)))
  474. (delete-region beg (point))
  475. (incf ndef))))
  476. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  477. ndef nref label))))
  478. (provide 'org-footnote)
  479. ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
  480. ;;; org-footnote.el ends here