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