org-footnote.el 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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.28trans
  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 | [r]enumber fn:N | 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 ?r)
  280. (org-footnote-renumber-fn:N))
  281. ((equal c ?n)
  282. (org-footnote-normalize))
  283. ((equal c ?d)
  284. (org-footnote-delete))
  285. (t (error "No such footnote command %c" c))))
  286. ((setq tmp (org-footnote-at-reference-p))
  287. (if (nth 1 tmp)
  288. (org-footnote-goto-definition (nth 1 tmp))
  289. (goto-char (match-beginning 4))))
  290. ((setq tmp (org-footnote-at-definition-p))
  291. (org-footnote-goto-next-reference (nth 1 tmp)))
  292. (t (org-footnote-new)))))
  293. ;;;###autoload
  294. (defun org-footnote-normalize (&optional sort-only for-preprocessor)
  295. "Collect the footnotes in various formats and normalize them.
  296. This find the different sorts of footnotes allowed in Org, and
  297. normalizes them to the usual [N] format that is understood by the
  298. Org-mode exporters.
  299. When SORT-ONLY is set, only sort the footnote definitions into the
  300. referenced sequence."
  301. ;; This is based on Paul's function, but rewritten.
  302. (let* ((limit-level
  303. (and (boundp 'org-inlinetask-min-level)
  304. org-inlinetask-min-level
  305. (1- org-inlinetask-min-level)))
  306. (nstars (and limit-level
  307. (if org-odd-levels-only
  308. (and limit-level (1- (* limit-level 2)))
  309. limit-level)))
  310. (outline-regexp
  311. (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
  312. (count 0)
  313. ref def idef ref-table beg beg1 marker a before ins-point)
  314. (save-excursion
  315. ;; Now find footnote references, and extract the definitions
  316. (goto-char (point-min))
  317. (while (re-search-forward org-footnote-re nil t)
  318. (org-if-unprotected
  319. (setq def (match-string 4)
  320. idef def
  321. ref (or (match-string 1) (match-string 2))
  322. before (char-to-string (char-after (match-beginning 0))))
  323. (if (equal ref "fn:") (setq ref nil))
  324. (if (and ref (setq a (assoc ref ref-table)))
  325. (progn
  326. (setq marker (nth 1 a))
  327. (unless (nth 2 a) (setf (caddr a) def)))
  328. (setq marker (number-to-string (incf count))))
  329. (save-match-data
  330. (if def
  331. (setq def (org-trim def))
  332. (save-excursion
  333. (goto-char (point-min))
  334. (if (not (re-search-forward (concat "^\\[" (regexp-quote ref)
  335. "\\]") nil t))
  336. (setq def nil)
  337. (setq beg (match-beginning 0))
  338. (setq beg1 (match-end 0))
  339. (re-search-forward
  340. (org-re "^[ \t]*$\\|^\\*+ \\|^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
  341. nil 'move)
  342. (setq def (buffer-substring beg1 (or (match-beginning 0)
  343. (point-max))))
  344. (goto-char beg)
  345. (skip-chars-backward " \t\n\t")
  346. (delete-region (1+ (point)) (match-beginning 0))))))
  347. (unless sort-only
  348. (replace-match (concat before "[" marker "]"))
  349. (and idef
  350. org-footnote-fill-after-inline-note-extraction
  351. (fill-paragraph)))
  352. (if (not a) (push (list ref marker def (if idef t nil)) ref-table))))
  353. ;; First find and remove the footnote section
  354. (goto-char (point-min))
  355. (cond
  356. ((org-mode-p)
  357. (if (and org-footnote-section
  358. (re-search-forward
  359. (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
  360. "[ \t]*$")
  361. nil t))
  362. (if (or for-preprocessor (not org-footnote-section))
  363. (replace-match "")
  364. (org-back-to-heading t)
  365. (forward-line 1)
  366. (setq ins-point (point))
  367. (delete-region (point) (org-end-of-subtree t)))
  368. (goto-char (point-max))
  369. (unless for-preprocessor
  370. (when org-footnote-section
  371. (or (bolp) (insert "\n"))
  372. (insert "* " org-footnote-section "\n")
  373. (setq ins-point (point))))))
  374. (t
  375. (if (re-search-forward
  376. (concat "^"
  377. (regexp-quote org-footnote-tag-for-non-org-mode-files)
  378. "[ \t]*$")
  379. nil t)
  380. (replace-match ""))
  381. (goto-char (point-max))
  382. (skip-chars-backward " \t\n\r")
  383. (delete-region (point) (point-max))
  384. (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n")
  385. (setq ins-point (point))))
  386. ;; Insert the footnotes again
  387. (goto-char (or ins-point (point-max)))
  388. (setq ref-table (reverse ref-table))
  389. (when sort-only
  390. ;; remove anonymous and inline footnotes from the list
  391. (setq ref-table
  392. (delq nil (mapcar
  393. (lambda (x) (and (car x)
  394. (not (equal (car x) "fn:"))
  395. (not (nth 3 x))
  396. x))
  397. ref-table))))
  398. ;; Make sure each footnote has a description, or an error message.
  399. (setq ref-table
  400. (mapcar
  401. (lambda (x)
  402. (if (not (nth 2 x))
  403. (setcar (cddr x)
  404. (format "FOOTNOTE DEFINITION NOT FOUND: %s" (car x)))
  405. (setcar (cddr x) (org-trim (nth 2 x))))
  406. x)
  407. ref-table))
  408. (if (or (not (org-mode-p)) ; not an Org file
  409. org-footnote-section ; we do not use a footnote section
  410. (not sort-only) ; this is normalization
  411. for-preprocessor) ; the is the preprocessor
  412. ;; Insert the footnotes together in one place
  413. (progn
  414. (setq def
  415. (mapconcat
  416. (lambda (x)
  417. (format "[%s] %s" (nth (if sort-only 0 1) x)
  418. (org-trim (nth 2 x))))
  419. ref-table "\n\n"))
  420. (if ref-table (insert "\n" def "\n\n")))
  421. ;; Insert each footnote near the first reference
  422. ;; Happens only in Org files with no special footnote section,
  423. ;; and only when doing sorting
  424. (mapc 'org-insert-footnote-reference-near-definition
  425. ref-table)))))
  426. (defun org-insert-footnote-reference-near-definition (entry)
  427. "Find first reference of footnote ENTRY and insert the definition there.
  428. ENTRY is (fn-label num-mark definition)."
  429. (when (car entry)
  430. (goto-char (point-min))
  431. (when (re-search-forward (format ".\\[%s[]:]" (regexp-quote (car entry)))
  432. nil t)
  433. (org-footnote-goto-local-insertion-point)
  434. (insert (format "\n\n[%s] %s" (car entry) (nth 2 entry))))))
  435. (defun org-footnote-goto-local-insertion-point ()
  436. "Find insertion point for footnote, just before next outline heading."
  437. (outline-next-heading)
  438. (or (bolp) (newline))
  439. (beginning-of-line 0)
  440. (while (and (not (bobp)) (= (char-after) ?#))
  441. (beginning-of-line 0))
  442. (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
  443. (end-of-line 1)
  444. (skip-chars-backward "\n\r\t "))
  445. (defun org-footnote-delete (&optional label)
  446. "Delete the footnote at point.
  447. This will remove the definition (even multiple definitions if they exist)
  448. and all references of a footnote label."
  449. (catch 'done
  450. (let (x label l beg def-re (nref 0) (ndef 0))
  451. (unless label
  452. (when (setq x (org-footnote-at-reference-p))
  453. (setq label (nth 1 x))
  454. (when (or (not label) (equal "fn:" label))
  455. (delete-region (1+ (match-beginning 0)) (match-end 0))
  456. (message "Anonymous footnote removed")
  457. (throw 'done t)))
  458. (when (and (not label) (setq x (org-footnote-at-definition-p)))
  459. (setq label (nth 1 x)))
  460. (unless label (error "Don't know which footnote to remove")))
  461. (save-excursion
  462. (save-restriction
  463. (goto-char (point-min))
  464. (while (re-search-forward org-footnote-re nil t)
  465. (setq l (or (match-string 1) (match-string 2)))
  466. (when (equal l label)
  467. (delete-region (1+ (match-beginning 0)) (match-end 0))
  468. (incf nref)))
  469. (goto-char (point-min))
  470. (setq def-re (concat "^\\[" (regexp-quote label) "\\]"))
  471. (while (re-search-forward def-re nil t)
  472. (setq beg (match-beginning 0))
  473. (if (re-search-forward "^\\[\\|^[ \t]*$\\|^\\*+ " nil t)
  474. (goto-char (match-beginning 0))
  475. (goto-char (point-max)))
  476. (delete-region beg (point))
  477. (incf ndef))))
  478. (message "%d definition(s) of and %d reference(s) of footnote %s removed"
  479. ndef nref label))))
  480. (defun org-footnote-renumber-fn:N ()
  481. "Renumber the simple footnotes like fn:17 into a sequence in the document."
  482. (interactive)
  483. (let (map i (n 0))
  484. (save-excursion
  485. (save-restriction
  486. (widen)
  487. (goto-char (point-min))
  488. (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
  489. (setq i (string-to-number (match-string 1)))
  490. (when (and (string-match "\\S-" (buffer-substring
  491. (point-at-bol) (match-beginning 0)))
  492. (not (assq i map)))
  493. (push (cons i (number-to-string (incf n))) map)))
  494. (goto-char (point-min))
  495. (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
  496. (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
  497. (provide 'org-footnote)
  498. ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
  499. ;;; org-footnote.el ends here