1 ;;; org-footnote.el --- Footnote support in Org and elsewhere
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
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.
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
60 (org-re "\\(fn:\\([-_[:word:]]+?\\)?\\)\\(?::\\([^\]]*?\\)\\)?")
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."
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."
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."
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."
107 (defcustom org-footnote-auto-label t
108 "Non-nil means define automatically new labels for footnotes.
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 random Automatically generate a unique, random label.
117 plain Automatically create plain number labels like [1]"
120 (const :tag
"Prompt for label" nil
)
121 (const :tag
"Create automatic [fn:N]" t
)
122 (const :tag
"Offer automatic [fn:N] for editing" confirm
)
123 (const :tag
"Create a random label" random
)
124 (const :tag
"Create automatic [N]" plain
)))
126 (defcustom org-footnote-auto-adjust nil
127 "Non-nil means automatically adjust footnotes after insert/delete.
128 When this is t, after each insertion or deletion of a footnote,
129 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
130 If you want to have just sorting or just renumbering, set this variable
131 to `sort' or `renumber'.
133 The main values of this variable can be set with in-buffer options:
136 #+STARTUP: nofnadjust"
139 (const :tag
"Renumber" renumber
)
140 (const :tag
"Sort" sort
)
141 (const :tag
"Renumber and Sort" t
)))
143 (defcustom org-footnote-fill-after-inline-note-extraction nil
144 "Non-nil means fill paragraphs after extracting footnotes.
145 When extracting inline footnotes, the lengths of lines can change a lot.
146 When this option is set, paragraphs from which an inline footnote has been
147 extracted will be filled again."
151 (defun org-footnote-at-reference-p ()
152 "Is the cursor at a footnote reference?
153 If yes, return the beginning position, the label, and the definition, if local."
154 (when (org-in-regexp org-footnote-re
15)
155 (list (match-beginning 0)
157 (if (equal (match-string 2) "fn:") nil
(match-string 2)))
160 (defun org-footnote-at-definition-p ()
161 "Is the cursor at a footnote definition.
162 This matches only pure definitions like [1] or [fn:name] at the beginning
163 of a line. It does not match references like [fn:name:definition], where the
164 footnote text is included and defined locally.
165 The return value will be nil if not at a footnote definition, and a list
166 with start and label of the footnote if there is a definition at point."
169 (let ((lim (save-excursion (re-search-backward "^\\*+ \\|^[ \t]*$" nil t
))))
170 (when (re-search-backward org-footnote-definition-re lim t
)
171 (list (match-beginning 0) (match-string 2))))))
173 (defun org-footnote-goto-definition (label)
174 "Find the definition of the footnote with label LABEL."
175 (interactive "sLabel: ")
177 (setq label
(org-footnote-normalize-label label
))
178 (let ((re (format "^\\[%s\\]\\|.\\[%s:" label label
))
181 (setq pos
(or (re-search-forward re nil t
)
182 (and (goto-char (point-min))
183 (re-search-forward re nil t
))
184 (and (progn (widen) t
)
185 (goto-char (point-min))
186 (re-search-forward re nil t
)))))
188 (error "Cannot find definition of footnote %s" label
)
190 (org-show-context 'link-search
)
191 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
193 (defun org-footnote-goto-previous-reference (label)
194 "Find the first closest (to point) reference of footnote with label LABEL."
195 (interactive "sLabel: ")
197 (setq label
(org-footnote-normalize-label label
))
198 (let ((re (format ".\\[%s[]:]" label
))
201 (setq pos
(or (re-search-backward re nil t
)
202 (and (goto-char (point-max))
203 (re-search-backward re nil t
))
204 (and (progn (widen) t
)
206 (re-search-backward re nil t
))
207 (and (goto-char (point-max))
208 (re-search-forward re nil t
)))))
211 (goto-char (match-end 0))
212 (org-show-context 'link-search
))
213 (error "Cannot find reference of footnote %s" label
))))
215 (defun org-footnote-normalize-label (label)
216 (if (numberp label
) (setq label
(number-to-string label
)))
217 (if (not (string-match "^[0-9]+$\\|^$\\|^fn:" label
))
218 (setq label
(concat "fn:" label
)))
221 (defun org-footnote-all-labels ()
222 "Return list with all defined foot labels used in the buffer."
227 (goto-char (point-min))
228 (while (re-search-forward org-footnote-definition-re nil t
)
229 (setq l
(org-match-string-no-properties 2))
230 (and l
(add-to-list 'rtn l
)))
231 (goto-char (point-min))
232 (while (re-search-forward org-footnote-re nil t
)
233 (setq l
(or (org-match-string-no-properties 1)
234 (org-match-string-no-properties 2)))
235 (and l
(not (equal l
"fn:")) (add-to-list 'rtn l
)))))
238 (defun org-footnote-unique-label (&optional current
)
239 "Return a new unique footnote label.
240 The returns the firsts fn:N labels that is currently not used."
241 (unless current
(setq current
(org-footnote-all-labels)))
242 (let ((fmt (if (eq org-footnote-auto-label
'plain
) "%d" "fn:%d"))
244 (while (member (format fmt cnt
) current
)
248 (defvar org-footnote-label-history nil
249 "History of footnote labels entered in current buffer.")
250 (make-variable-buffer-local 'org-footnote-label-history
)
252 (defun org-footnote-new ()
253 "Insert a new footnote.
254 This command prompts for a label. If this is a label referencing an
255 existing label, only insert the label. If the footnote label is empty
256 or new, let the user edit the definition of the footnote."
258 (let* ((labels (and (not (equal org-footnote-auto-label
'random
))
259 (org-footnote-all-labels)))
260 (propose (org-footnote-unique-label labels
))
263 ((member org-footnote-auto-label
'(t plain
))
265 ((equal org-footnote-auto-label
'random
)
267 (substring (org-id-uuid) 0 8))
270 "Label (leave empty for anonymous): "
271 (mapcar 'list labels
) nil nil
272 (if (eq org-footnote-auto-label
'confirm
) propose nil
)
273 'org-footnote-label-history
)))))
274 (setq label
(org-footnote-normalize-label label
))
279 ((member label labels
)
280 (insert "[" label
"]")
281 (message "New reference to existing note"))
282 (org-footnote-define-inline
283 (insert "[" label
": ]")
285 (org-footnote-auto-adjust-maybe))
287 (insert "[" label
"]")
288 (org-footnote-create-definition label
)
289 (org-footnote-auto-adjust-maybe)))))
291 (defun org-footnote-create-definition (label)
292 "Start the definition of a footnote with label LABEL."
293 (interactive "sLabel: ")
294 (setq label
(org-footnote-normalize-label label
))
298 (if (not org-footnote-section
)
299 ;; No section, put footnote into the current outline node
301 ;; Try to find or make the special node
302 (goto-char (point-min))
303 (setq re
(concat "^\\*+[ \t]+" org-footnote-section
"[ \t]*$"))
304 (unless (or (re-search-forward re nil t
)
305 (and (progn (widen) t
)
306 (re-search-forward re nil t
)))
307 (goto-char (point-max))
308 (insert "\n\n* " org-footnote-section
"\n")))
309 ;; Now go to the end of this entry and insert there.
310 (org-footnote-goto-local-insertion-point)
311 (org-show-context 'link-search
))
313 (setq re
(concat "^" org-footnote-tag-for-non-org-mode-files
"[ \t]*$"))
314 (unless (re-search-forward re nil t
)
315 (let ((max (if (and (derived-mode-p 'message-mode
)
316 (re-search-forward message-signature-separator nil t
))
317 (progn (beginning-of-line) (point))
318 (goto-char (point-max)))))
319 (skip-chars-backward " \t\r\n")
320 (delete-region (point) max
)
322 (insert org-footnote-tag-for-non-org-mode-files
"\n")))
323 ;; Skip existing footnotes
324 (while (re-search-forward "^[[:space:]]*\\[[^]]+\\] " nil t
)
326 (insert "\n[" label
"] \n")
327 (goto-char (1- (point)))
328 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
331 (defun org-footnote-action (&optional special
)
332 "Do the right thing for footnotes.
333 When at a footnote reference, jump to the definition. When at a definition,
334 jump to the references. When neither at definition or reference,
335 create a new footnote, interactively.
336 With prefix arg SPECIAL, offer additional commands in a menu."
341 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
342 (setq c
(read-char-exclusive))
345 (org-footnote-normalize 'sort
))
347 (org-footnote-renumber-fn:N
))
349 (org-footnote-renumber-fn:N
)
350 (org-footnote-normalize 'sort
))
352 (org-footnote-normalize))
354 (org-footnote-delete))
355 (t (error "No such footnote command %c" c
))))
356 ((setq tmp
(org-footnote-at-reference-p))
358 (org-footnote-goto-definition (nth 1 tmp
))
359 (goto-char (match-beginning 4))))
360 ((setq tmp
(org-footnote-at-definition-p))
361 (org-footnote-goto-previous-reference (nth 1 tmp
)))
362 (t (org-footnote-new)))))
365 (defun org-footnote-normalize (&optional sort-only for-preprocessor
)
366 "Collect the footnotes in various formats and normalize them.
367 This finds the different sorts of footnotes allowed in Org, and
368 normalizes them to the usual [N] format that is understood by the
370 When SORT-ONLY is set, only sort the footnote definitions into the
371 referenced sequence."
372 ;; This is based on Paul's function, but rewritten.
374 (and (boundp 'org-inlinetask-min-level
)
375 org-inlinetask-min-level
376 (1- org-inlinetask-min-level
)))
377 (nstars (and limit-level
378 (if org-odd-levels-only
379 (and limit-level
(1- (* limit-level
2)))
382 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ ")))
384 ref def idef ref-table beg beg1 marker a before ins-point
)
386 ;; Now find footnote references, and extract the definitions
387 (goto-char (point-min))
388 (while (re-search-forward org-footnote-re nil t
)
389 (unless (or (org-in-commented-line) (org-in-verbatim-emphasis)
390 (org-inside-latex-macro-p))
392 (setq def
(match-string 4)
394 ref
(or (match-string 1) (match-string 2))
395 before
(char-to-string (char-after (match-beginning 0))))
396 (if (equal ref
"fn:") (setq ref nil
))
397 (if (and ref
(setq a
(assoc ref ref-table
)))
399 (setq marker
(nth 1 a
))
400 (unless (nth 2 a
) (setf (caddr a
) def
)))
401 (setq marker
(number-to-string (incf count
))))
404 (setq def
(org-trim def
))
406 (goto-char (point-min))
407 (if (not (re-search-forward (concat "^\\[" (regexp-quote ref
)
410 (setq beg
(match-beginning 0))
411 (setq beg1
(match-end 0))
413 (org-re "^[ \t]*$\\|^\\*+ \\|^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
415 (setq def
(buffer-substring beg1
(or (match-beginning 0)
418 (skip-chars-backward " \t\n\t")
419 (delete-region (1+ (point)) (match-beginning 0))))))
421 (replace-match (concat before
"[" marker
"]") t t
)
423 org-footnote-fill-after-inline-note-extraction
425 (if (not a
) (push (list ref marker def
(if idef t nil
))
428 ;; First find and remove the footnote section
429 (goto-char (point-min))
432 (if (and org-footnote-section
434 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section
)
437 (if (or for-preprocessor
(not org-footnote-section
))
439 (org-back-to-heading t
)
441 (setq ins-point
(point))
442 (delete-region (point) (org-end-of-subtree t
)))
443 (goto-char (point-max))
444 (unless for-preprocessor
445 (when org-footnote-section
446 (or (bolp) (insert "\n"))
447 (insert "* " org-footnote-section
"\n")
448 (setq ins-point
(point))))))
450 (if (re-search-forward
452 (regexp-quote org-footnote-tag-for-non-org-mode-files
)
456 (goto-char (point-max))
457 (skip-chars-backward " \t\n\r")
458 (delete-region (point) (point-max))
459 (insert "\n\n" org-footnote-tag-for-non-org-mode-files
"\n")
460 (setq ins-point
(point))))
462 ;; Insert the footnotes again
463 (goto-char (or ins-point
(point-max)))
464 (setq ref-table
(reverse ref-table
))
466 ;; remove anonymous and inline footnotes from the list
469 (lambda (x) (and (car x
)
470 (not (equal (car x
) "fn:"))
474 ;; Make sure each footnote has a description, or an error message.
480 (format "FOOTNOTE DEFINITION NOT FOUND: %s" (car x
)))
481 (setcar (cddr x
) (org-trim (nth 2 x
))))
485 (if (or (not (org-mode-p)) ; not an Org file
486 org-footnote-section
; we do not use a footnote section
487 (not sort-only
) ; this is normalization
488 for-preprocessor
) ; the is the preprocessor
489 ;; Insert the footnotes together in one place
494 (format "[%s] %s" (nth (if sort-only
0 1) x
)
495 (org-trim (nth 2 x
))))
497 (if ref-table
(insert "\n" def
"\n\n")))
498 ;; Insert each footnote near the first reference
499 ;; Happens only in Org files with no special footnote section,
500 ;; and only when doing sorting
501 (mapc 'org-insert-footnote-reference-near-definition
504 (defun org-insert-footnote-reference-near-definition (entry)
505 "Find first reference of footnote ENTRY and insert the definition there.
506 ENTRY is (fn-label num-mark definition)."
508 (goto-char (point-min))
509 (when (re-search-forward (format ".\\[%s[]:]" (regexp-quote (car entry
)))
511 (org-footnote-goto-local-insertion-point)
512 (insert (format "\n[%s] %s\n" (car entry
) (nth 2 entry
))))))
514 (defun org-footnote-goto-local-insertion-point ()
515 "Find insertion point for footnote, just before next outline heading."
516 (org-with-limited-levels (outline-next-heading))
517 (or (bolp) (newline))
518 (beginning-of-line 0)
519 (while (and (not (bobp)) (= (char-after) ?
#))
520 (beginning-of-line 0))
521 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
523 (skip-chars-backward "\n\r\t ")
526 (defun org-footnote-delete (&optional label
)
527 "Delete the footnote at point.
528 This will remove the definition (even multiple definitions if they exist)
529 and all references of a footnote label."
531 (let (x label l beg def-re
(nref 0) (ndef 0))
533 (when (setq x
(org-footnote-at-reference-p))
534 (setq label
(nth 1 x
))
535 (when (or (not label
) (equal "fn:" label
))
536 (delete-region (1+ (match-beginning 0)) (match-end 0))
537 (message "Anonymous footnote removed")
539 (when (and (not label
) (setq x
(org-footnote-at-definition-p)))
540 (setq label
(nth 1 x
)))
541 (unless label
(error "Don't know which footnote to remove")))
544 (goto-char (point-min))
545 (while (re-search-forward org-footnote-re nil t
)
546 (setq l
(or (match-string 1) (match-string 2)))
547 (when (equal l label
)
548 (delete-region (1+ (match-beginning 0)) (match-end 0))
550 (goto-char (point-min))
551 (setq def-re
(concat "^\\[" (regexp-quote label
) "\\]"))
552 (while (re-search-forward def-re nil t
)
553 (setq beg
(match-beginning 0))
554 (if (re-search-forward "^\\[\\|^[ \t]*$\\|^\\*+ " nil t
)
555 (goto-char (match-beginning 0))
556 (goto-char (point-max)))
557 (delete-region beg
(point))
559 (org-footnote-auto-adjust-maybe)
560 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
563 (defun org-footnote-renumber-fn:N
()
564 "Renumber the simple footnotes like fn:17 into a sequence in the document."
570 (goto-char (point-min))
571 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t
)
572 (setq i
(string-to-number (match-string 1)))
573 (when (and (string-match "\\S-" (buffer-substring
574 (point-at-bol) (match-beginning 0)))
576 (push (cons i
(number-to-string (incf n
))) map
)))
577 (goto-char (point-min))
578 (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t
)
579 (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map
)) "\\3")))))))
581 (defun org-footnote-auto-adjust-maybe ()
582 "Renumber and/or sort footnotes according to user settings."
583 (when (memq org-footnote-auto-adjust
'(t renumber
))
584 (org-footnote-renumber-fn:N
))
585 (when (memq org-footnote-auto-adjust
'(t sort
))
586 (let ((label (nth 1 (org-footnote-at-definition-p))))
587 (org-footnote-normalize 'sort
)
589 (goto-char (point-min))
590 (and (re-search-forward (concat "^\\[" (regexp-quote label
) "\\]")
593 (just-one-space)))))))
595 (provide 'org-footnote
)
597 ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
599 ;;; org-footnote.el ends here