Release 6.30d
[org-mode.git] / lisp / org-footnote.el
blob389cf9b923397100652e684faa166b6839b5d9c7
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.30d
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 (defvar org-odd-levels-only) ;; defined in org.el
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.")
62 (defconst org-footnote-definition-re
63 (org-re "^\\(\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]\\)")
64 "Regular expression matching the definition of a footnote.")
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)))
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)
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)
99 (defcustom org-footnote-auto-label t
100 "Non-nil means, define automatically new labels for footnotes.
101 Possible values are:
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)))
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'.
123 The main values of this variable can be set with in-buffer options:
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)))
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)
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))))
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))))))
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'."))))
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))))
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)
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))
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)))
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)
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))
271 (insert "[" label "]")
272 (org-footnote-create-definition label)
273 (org-footnote-auto-adjust-maybe)))))
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
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))
295 (setq re (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$"))
296 (unless (re-search-forward re nil t)
297 (goto-char (point-max))
298 (skip-chars-backward " \t\r\n")
299 (insert "\n\n")
300 (delete-region (point) (point-max))
301 (insert org-footnote-tag-for-non-org-mode-files "\n"))
302 (goto-char (point-max))
303 (skip-chars-backward " \t\r\n")))
304 (insert "\n\n")
305 (insert "[" label "] ")
306 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
308 ;;;###autoload
309 (defun org-footnote-action (&optional special)
310 "Do the right thing for footnotes.
311 When at a footnote reference, jump to the definition. When at a definition,
312 jump to the refernces. When neither at definition or reference,
313 create a new footnote, interactively.
314 With prefix arg SPECIAL, offer additional commands in a menu."
315 (interactive "P")
316 (let (tmp c)
317 (cond
318 (special
319 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
320 (setq c (read-char-exclusive))
321 (cond
322 ((equal c ?s)
323 (org-footnote-normalize 'sort))
324 ((equal c ?r)
325 (org-footnote-renumber-fn:N))
326 ((equal c ?S)
327 (org-footnote-renumber-fn:N)
328 (org-footnote-normalize 'sort))
329 ((equal c ?n)
330 (org-footnote-normalize))
331 ((equal c ?d)
332 (org-footnote-delete))
333 (t (error "No such footnote command %c" c))))
334 ((setq tmp (org-footnote-at-reference-p))
335 (if (nth 1 tmp)
336 (org-footnote-goto-definition (nth 1 tmp))
337 (goto-char (match-beginning 4))))
338 ((setq tmp (org-footnote-at-definition-p))
339 (org-footnote-goto-next-reference (nth 1 tmp)))
340 (t (org-footnote-new)))))
342 ;;;###autoload
343 (defun org-footnote-normalize (&optional sort-only for-preprocessor)
344 "Collect the footnotes in various formats and normalize them.
345 This finds the different sorts of footnotes allowed in Org, and
346 normalizes them to the usual [N] format that is understood by the
347 Org-mode exporters.
348 When SORT-ONLY is set, only sort the footnote definitions into the
349 referenced sequence."
350 ;; This is based on Paul's function, but rewritten.
351 (let* ((limit-level
352 (and (boundp 'org-inlinetask-min-level)
353 org-inlinetask-min-level
354 (1- org-inlinetask-min-level)))
355 (nstars (and limit-level
356 (if org-odd-levels-only
357 (and limit-level (1- (* limit-level 2)))
358 limit-level)))
359 (outline-regexp
360 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
361 (count 0)
362 ref def idef ref-table beg beg1 marker a before ins-point)
363 (save-excursion
364 ;; Now find footnote references, and extract the definitions
365 (goto-char (point-min))
366 (while (re-search-forward org-footnote-re nil t)
367 (unless (org-in-commented-line)
368 (org-if-unprotected
369 (setq def (match-string 4)
370 idef def
371 ref (or (match-string 1) (match-string 2))
372 before (char-to-string (char-after (match-beginning 0))))
373 (if (equal ref "fn:") (setq ref nil))
374 (if (and ref (setq a (assoc ref ref-table)))
375 (progn
376 (setq marker (nth 1 a))
377 (unless (nth 2 a) (setf (caddr a) def)))
378 (setq marker (number-to-string (incf count))))
379 (save-match-data
380 (if def
381 (setq def (org-trim def))
382 (save-excursion
383 (goto-char (point-min))
384 (if (not (re-search-forward (concat "^\\[" (regexp-quote ref)
385 "\\]") nil t))
386 (setq def nil)
387 (setq beg (match-beginning 0))
388 (setq beg1 (match-end 0))
389 (re-search-forward
390 (org-re "^[ \t]*$\\|^\\*+ \\|^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
391 nil 'move)
392 (setq def (buffer-substring beg1 (or (match-beginning 0)
393 (point-max))))
394 (goto-char beg)
395 (skip-chars-backward " \t\n\t")
396 (delete-region (1+ (point)) (match-beginning 0))))))
397 (unless sort-only
398 (replace-match (concat before "[" marker "]"))
399 (and idef
400 org-footnote-fill-after-inline-note-extraction
401 (fill-paragraph)))
402 (if (not a) (push (list ref marker def (if idef t nil))
403 ref-table)))))
405 ;; First find and remove the footnote section
406 (goto-char (point-min))
407 (cond
408 ((org-mode-p)
409 (if (and org-footnote-section
410 (re-search-forward
411 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
412 "[ \t]*$")
413 nil t))
414 (if (or for-preprocessor (not org-footnote-section))
415 (replace-match "")
416 (org-back-to-heading t)
417 (forward-line 1)
418 (setq ins-point (point))
419 (delete-region (point) (org-end-of-subtree t)))
420 (goto-char (point-max))
421 (unless for-preprocessor
422 (when org-footnote-section
423 (or (bolp) (insert "\n"))
424 (insert "* " org-footnote-section "\n")
425 (setq ins-point (point))))))
427 (if (re-search-forward
428 (concat "^"
429 (regexp-quote org-footnote-tag-for-non-org-mode-files)
430 "[ \t]*$")
431 nil t)
432 (replace-match ""))
433 (goto-char (point-max))
434 (skip-chars-backward " \t\n\r")
435 (delete-region (point) (point-max))
436 (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n")
437 (setq ins-point (point))))
439 ;; Insert the footnotes again
440 (goto-char (or ins-point (point-max)))
441 (setq ref-table (reverse ref-table))
442 (when sort-only
443 ;; remove anonymous and inline footnotes from the list
444 (setq ref-table
445 (delq nil (mapcar
446 (lambda (x) (and (car x)
447 (not (equal (car x) "fn:"))
448 (not (nth 3 x))
450 ref-table))))
451 ;; Make sure each footnote has a description, or an error message.
452 (setq ref-table
453 (mapcar
454 (lambda (x)
455 (if (not (nth 2 x))
456 (setcar (cddr x)
457 (format "FOOTNOTE DEFINITION NOT FOUND: %s" (car x)))
458 (setcar (cddr x) (org-trim (nth 2 x))))
460 ref-table))
462 (if (or (not (org-mode-p)) ; not an Org file
463 org-footnote-section ; we do not use a footnote section
464 (not sort-only) ; this is normalization
465 for-preprocessor) ; the is the preprocessor
466 ;; Insert the footnotes together in one place
467 (progn
468 (setq def
469 (mapconcat
470 (lambda (x)
471 (format "[%s] %s" (nth (if sort-only 0 1) x)
472 (org-trim (nth 2 x))))
473 ref-table "\n\n"))
474 (if ref-table (insert "\n" def "\n\n")))
475 ;; Insert each footnote near the first reference
476 ;; Happens only in Org files with no special footnote section,
477 ;; and only when doing sorting
478 (mapc 'org-insert-footnote-reference-near-definition
479 ref-table)))))
481 (defun org-insert-footnote-reference-near-definition (entry)
482 "Find first reference of footnote ENTRY and insert the definition there.
483 ENTRY is (fn-label num-mark definition)."
484 (when (car entry)
485 (goto-char (point-min))
486 (when (re-search-forward (format ".\\[%s[]:]" (regexp-quote (car entry)))
487 nil t)
488 (org-footnote-goto-local-insertion-point)
489 (insert (format "\n\n[%s] %s" (car entry) (nth 2 entry))))))
491 (defun org-footnote-goto-local-insertion-point ()
492 "Find insertion point for footnote, just before next outline heading."
493 (org-with-limited-levels (outline-next-heading))
494 (or (bolp) (newline))
495 (beginning-of-line 0)
496 (while (and (not (bobp)) (= (char-after) ?#))
497 (beginning-of-line 0))
498 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
499 (end-of-line 1)
500 (skip-chars-backward "\n\r\t "))
502 (defun org-footnote-delete (&optional label)
503 "Delete the footnote at point.
504 This will remove the definition (even multiple definitions if they exist)
505 and all references of a footnote label."
506 (catch 'done
507 (let (x label l beg def-re (nref 0) (ndef 0))
508 (unless label
509 (when (setq x (org-footnote-at-reference-p))
510 (setq label (nth 1 x))
511 (when (or (not label) (equal "fn:" label))
512 (delete-region (1+ (match-beginning 0)) (match-end 0))
513 (message "Anonymous footnote removed")
514 (throw 'done t)))
515 (when (and (not label) (setq x (org-footnote-at-definition-p)))
516 (setq label (nth 1 x)))
517 (unless label (error "Don't know which footnote to remove")))
518 (save-excursion
519 (save-restriction
520 (goto-char (point-min))
521 (while (re-search-forward org-footnote-re nil t)
522 (setq l (or (match-string 1) (match-string 2)))
523 (when (equal l label)
524 (delete-region (1+ (match-beginning 0)) (match-end 0))
525 (incf nref)))
526 (goto-char (point-min))
527 (setq def-re (concat "^\\[" (regexp-quote label) "\\]"))
528 (while (re-search-forward def-re nil t)
529 (setq beg (match-beginning 0))
530 (if (re-search-forward "^\\[\\|^[ \t]*$\\|^\\*+ " nil t)
531 (goto-char (match-beginning 0))
532 (goto-char (point-max)))
533 (delete-region beg (point))
534 (incf ndef))))
535 (org-footnote-auto-adjust-maybe)
536 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
537 ndef nref label))))
539 (defun org-footnote-renumber-fn:N ()
540 "Renumber the simple footnotes like fn:17 into a sequence in the document."
541 (interactive)
542 (let (map i (n 0))
543 (save-excursion
544 (save-restriction
545 (widen)
546 (goto-char (point-min))
547 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
548 (setq i (string-to-number (match-string 1)))
549 (when (and (string-match "\\S-" (buffer-substring
550 (point-at-bol) (match-beginning 0)))
551 (not (assq i map)))
552 (push (cons i (number-to-string (incf n))) map)))
553 (goto-char (point-min))
554 (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
555 (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
557 (defun org-footnote-auto-adjust-maybe ()
558 "Renumber and/or sort footnotes according to user settings."
559 (when (memq org-footnote-auto-adjust '(t renumber))
560 (org-footnote-renumber-fn:N))
561 (when (memq org-footnote-auto-adjust '(t sort))
562 (let ((label (nth 1 (org-footnote-at-definition-p))))
563 (org-footnote-normalize 'sort)
564 (when label
565 (goto-char (point-min))
566 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
567 nil t)
568 (progn (insert " ")
569 (just-one-space)))))))
571 (provide 'org-footnote)
573 ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
575 ;;; org-footnote.el ends here