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