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