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