1 ;;; org-footnote.el --- Footnote support in Org and elsewhere
3 ;; Copyright (C) 2009-2011 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;; This file contains the code dealing with footnotes in Org-mode.
28 ;; The code can also be used in arbitrary text modes to provide
29 ;; footnotes. Compared to Steven L Baur's footnote.el it provides
30 ;; better support for resuming editing. It is less configurable than
31 ;; Steve's code, though.
40 (declare-function message-point-in-header-p
"message" ())
41 (declare-function org-back-over-empty-lines
"org" ())
42 (declare-function org-back-to-heading
"org" (&optional invisible-ok
))
43 (declare-function org-combine-plists
"org" (&rest plists
))
44 (declare-function org-end-of-subtree
"org" (&optional invisible-ok to-heading
))
45 (declare-function org-export-preprocess-string
"org-exp"
46 (string &rest parameters
))
47 (declare-function org-fill-paragraph
"org" (&optional justify
))
48 (declare-function org-icompleting-read
"org" (&rest args
))
49 (declare-function org-id-uuid
"org-id" ())
50 (declare-function org-in-block-p
"org" (names))
51 (declare-function org-in-commented-line
"org" ())
52 (declare-function org-in-indented-comment-line
"org" ())
53 (declare-function org-in-regexp
"org" (re &optional nlines visually
))
54 (declare-function org-in-verbatim-emphasis
"org" ())
55 (declare-function org-inside-LaTeX-fragment-p
"org" ())
56 (declare-function org-inside-latex-macro-p
"org" ())
57 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
58 (declare-function org-show-context
"org" (&optional key
))
59 (declare-function org-trim
"org" (s))
60 (declare-function outline-next-heading
"outline")
62 (defvar org-outline-regexp-bol
) ; defined in org.el
63 (defvar org-odd-levels-only
) ; defined in org.el
64 (defvar org-bracket-link-regexp
) ; defined in org.el
65 (defvar message-cite-prefix-regexp
) ; defined in message.el
66 (defvar message-signature-separator
) ; defined in message.el
68 (defconst org-footnote-re
69 ;; Only [1]-like footnotes are closed in this regexp, as footnotes
70 ;; from other types might contain square brackets (i.e. links) in
73 ;; `org-re' is used for regexp compatibility with XEmacs.
75 ;; Match inline footnotes.
76 (org-re "fn:\\([-_[:word:]]+\\)?:\\|")
77 ;; Match other footnotes.
78 "\\(?:\\([0-9]+\\)\\]\\)\\|"
79 (org-re "\\(fn:[-_[:word:]]+\\)")
81 "Regular expression for matching footnotes.")
83 (defconst org-footnote-definition-re
84 (org-re "^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
85 "Regular expression matching the definition of a footnote.")
87 (defvar org-footnote-forbidden-blocks
'("example" "verse" "src" "ascii" "beamer"
88 "docbook" "html" "latex" "odt")
89 "Names of blocks where footnotes are not allowed.")
91 (defgroup org-footnote nil
92 "Footnotes in Org-mode."
96 (defcustom org-footnote-section
"Footnotes"
97 "Outline heading containing footnote definitions before export.
98 This can be nil, to place footnotes locally at the end of the current
99 outline node. If can also be the name of a special outline heading
100 under which footnotes should be put.
101 This variable defines the place where Org puts the definition
102 automatically, i.e. when creating the footnote, and when sorting the notes.
103 However, by hand you may place definitions *anywhere*.
104 If this is a string, during export, all subtrees starting with this
105 heading will be removed after extracting footnote definitions."
108 (string :tag
"Collect footnotes under heading")
109 (const :tag
"Define footnotes locally" nil
)))
111 (defcustom org-footnote-tag-for-non-org-mode-files
"Footnotes:"
112 "Tag marking the beginning of footnote section.
113 The Org footnote engine can be used in arbitrary text files as well
114 as in Org-mode. Outside Org mode, new footnotes are always placed at
115 the end of the file. When you normalize the notes, any line containing
116 only this tag will be removed, a new one will be inserted at the end
117 of the file, followed by the collected and normalized footnotes.
119 If you don't want any tag in such buffers, set this variable to nil."
122 (string :tag
"Collect footnotes under tag")
123 (const :tag
"Don't use a tag" nil
)))
125 (defcustom org-footnote-define-inline nil
126 "Non-nil means define footnotes inline, at reference location.
127 When nil, footnotes will be defined in a special section near
128 the end of the document. When t, the [fn:label:definition] notation
129 will be used to define the footnote at the reference position."
133 (defcustom org-footnote-auto-label t
134 "Non-nil means define automatically new labels for footnotes.
137 nil prompt the user for each label
138 t create unique labels of the form [fn:1], [fn:2], ...
139 confirm like t, but let the user edit the created value. In particular,
140 the label can be removed from the minibuffer, to create
141 an anonymous footnote.
142 random Automatically generate a unique, random label.
143 plain Automatically create plain number labels like [1]"
146 (const :tag
"Prompt for label" nil
)
147 (const :tag
"Create automatic [fn:N]" t
)
148 (const :tag
"Offer automatic [fn:N] for editing" confirm
)
149 (const :tag
"Create a random label" random
)
150 (const :tag
"Create automatic [N]" plain
)))
152 (defcustom org-footnote-auto-adjust nil
153 "Non-nil means automatically adjust footnotes after insert/delete.
154 When this is t, after each insertion or deletion of a footnote,
155 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
156 If you want to have just sorting or just renumbering, set this variable
157 to `sort' or `renumber'.
159 The main values of this variable can be set with in-buffer options:
162 #+STARTUP: nofnadjust"
165 (const :tag
"Renumber" renumber
)
166 (const :tag
"Sort" sort
)
167 (const :tag
"Renumber and Sort" t
)))
169 (defcustom org-footnote-fill-after-inline-note-extraction nil
170 "Non-nil means fill paragraphs after extracting footnotes.
171 When extracting inline footnotes, the lengths of lines can change a lot.
172 When this option is set, paragraphs from which an inline footnote has been
173 extracted will be filled again."
177 (defun org-footnote-in-valid-context-p ()
178 "Is point in a context where footnotes are allowed?"
180 (not (or (org-in-commented-line)
181 (org-in-indented-comment-line)
182 (org-inside-LaTeX-fragment-p)
183 ;; Avoid protected environments (LaTeX export)
184 (get-text-property (point) 'org-protected
)
185 ;; Avoid literal example.
186 (org-in-verbatim-emphasis)
189 (looking-at "[ \t]*:[ \t]+"))
190 ;; Avoid cited text and headers in message-mode.
191 (and (derived-mode-p 'message-mode
)
194 (looking-at message-cite-prefix-regexp
))
195 (message-point-in-header-p)))
196 ;; Avoid forbidden blocks.
197 (org-in-block-p org-footnote-forbidden-blocks
)))))
199 (defun org-footnote-at-reference-p ()
200 "Is the cursor at a footnote reference?
202 If so, return a list containing its label, beginning and ending
203 positions, and the definition, when inlined."
204 (when (and (org-footnote-in-valid-context-p)
205 (or (looking-at org-footnote-re
)
206 (org-in-regexp org-footnote-re
)
207 (save-excursion (re-search-backward org-footnote-re nil t
)))
208 ;; Only inline footnotes can start at bol.
209 (or (eq (char-before (match-end 0)) 58)
210 (/= (match-beginning 0) (point-at-bol))))
211 (let* ((beg (match-beginning 0))
212 (label (or (org-match-string-no-properties 2)
213 (org-match-string-no-properties 3)
214 ;; Anonymous footnotes don't have labels
215 (and (match-string 1)
216 (concat "fn:" (org-match-string-no-properties 1)))))
217 ;; Inline footnotes don't end at (match-end 0) as
218 ;; `org-footnote-re' stops just after the second colon.
219 ;; Find the real ending with `scan-sexps', so Org doesn't
220 ;; get fooled by unrelated closing square brackets.
221 (end (ignore-errors (scan-sexps beg
1))))
222 ;; Point is really at a reference if it's located before true
223 ;; ending of the footnote.
224 (when (and end
(< (point) end
)
225 ;; Verify match isn't a part of a link.
230 (org-in-regexp org-bracket-link-regexp
))))
231 (and linkp
(< (point) (cdr linkp
))))))
232 ;; Verify point doesn't belong to a LaTeX macro.
233 ;; Beware though, when two footnotes are side by
234 ;; side, once the first one is changed into LaTeX,
235 ;; the second one might then be considered as an
236 ;; optional argument of the command. Thus, check
237 ;; the `org-protected' property of that command.
238 (or (not (org-inside-latex-macro-p))
239 (get-text-property (1- beg
) 'org-protected
)))
241 ;; Definition: ensure this is an inline footnote first.
242 (and (or (not label
) (match-string 1))
243 (org-trim (buffer-substring (match-end 0) (1- end
)))))))))
245 (defun org-footnote-at-definition-p ()
246 "Is the cursor at a footnote definition?
248 This matches only pure definitions like [1] or [fn:name] at the beginning
249 of a line. It does not match references like [fn:name:definition], where the
250 footnote text is included and defined locally.
252 The return value will be nil if not at a footnote definition, and a list with
253 label, start, end and definition of the footnote otherwise."
254 (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
257 (let ((lim (save-excursion (re-search-backward
258 (concat org-outline-regexp-bol
259 "\\|^[ \t]*$") nil t
))))
260 (when (re-search-backward org-footnote-definition-re lim t
)
262 (list (org-match-string-no-properties 1)
265 ;; In a message, limit search to signature.
266 (let ((bound (and (derived-mode-p 'message-mode
)
268 (goto-char (point-max))
270 message-signature-separator nil t
)))))
271 (or (and (re-search-forward
272 (concat org-outline-regexp-bol
"\\|"
273 org-footnote-definition-re
"\\|"
276 (progn (skip-chars-forward " \t\n") (point-at-bol)))
278 (org-trim (buffer-substring (match-end 0) (point)))))))))
280 (defun org-footnote-get-next-reference (&optional label backward limit
)
281 "Return complete reference of the next footnote.
283 If LABEL is provided, get the next reference of that footnote. If
284 BACKWARD is non-nil, find previous reference instead. LIMIT is
285 the buffer position bounding the search.
287 Return value is a list like those provided by `org-footnote-at-reference-p'.
288 If no footnote is found, return nil."
290 (let* ((label-fmt (if label
(format "\\[%s[]:]" label
) org-footnote-re
)))
293 (unless (funcall (if backward
#'re-search-backward
#'re-search-forward
)
296 (unless backward
(backward-char))
297 (let ((ref (org-footnote-at-reference-p)))
298 (when ref
(throw 'exit ref
))))))))
300 (defun org-footnote-next-reference-or-definition (limit)
301 "Move point to next footnote reference or definition.
303 LIMIT is the buffer position bounding the search.
305 Return value is a list like those provided by
306 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
307 If no footnote is found, return nil."
308 (let* (ref (origin (point)))
311 (unless (re-search-forward org-footnote-re limit t
)
314 ;; Beware: with [1]-like footnotes point will be just after
315 ;; the closing square bracket.
318 ((setq ref
(org-footnote-at-reference-p))
320 ;; Definition: also grab the last square bracket, only
321 ;; matched in `org-footnote-re' for [1]-like footnotes.
322 ((save-match-data (org-footnote-at-definition-p))
323 (let ((end (match-end 0)))
325 (list nil
(match-beginning 0)
326 (if (eq (char-before end
) 93) end
(1+ end
)))))))))))
328 (defun org-footnote-get-definition (label)
329 "Return label, boundaries and definition of the footnote LABEL."
330 (let* ((label (regexp-quote (org-footnote-normalize-label label
)))
331 (re (format "^\\[%s\\]\\|.\\[%s:" label label
))
335 (when (or (re-search-forward re nil t
)
336 (and (goto-char (point-min))
337 (re-search-forward re nil t
))
338 (and (progn (widen) t
)
339 (goto-char (point-min))
340 (re-search-forward re nil t
)))
341 (let ((refp (org-footnote-at-reference-p)))
343 ((and (nth 3 refp
) refp
))
344 ((org-footnote-at-definition-p)))))))))
346 (defun org-footnote-goto-definition (label)
347 "Move point to the definition of the footnote LABEL.
348 Return a non-nil value when a definition has been found."
349 (interactive "sLabel: ")
351 (let ((def (org-footnote-get-definition label
)))
353 (error "Cannot find definition of footnote %s" label
)
354 (goto-char (nth 1 def
))
355 (looking-at (format "\\[%s\\]\\|\\[%s:" label label
))
356 (goto-char (match-end 0))
357 (org-show-context 'link-search
)
358 (when (eq major-mode
'org-mode
)
359 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))
362 (defun org-footnote-goto-previous-reference (label)
363 "Find the first closest (to point) reference of footnote with label LABEL."
364 (interactive "sLabel: ")
366 (let* ((label (org-footnote-normalize-label label
)) ref
)
368 (setq ref
(or (org-footnote-get-next-reference label t
)
369 (org-footnote-get-next-reference label
)
373 (org-footnote-get-next-reference label t
)
374 (org-footnote-get-next-reference label
))))))
376 (error "Cannot find reference of footnote %s" label
)
377 (goto-char (nth 1 ref
))
378 (org-show-context 'link-search
))))
380 (defun org-footnote-normalize-label (label)
381 "Return LABEL as an appropriate string."
383 ((numberp label
) (number-to-string label
))
384 ((equal "" label
) nil
)
385 ((not (string-match "^[0-9]+$\\|^fn:" label
))
386 (concat "fn:" label
))
389 (defun org-footnote-all-labels (&optional with-defs
)
390 "Return list with all defined foot labels used in the buffer.
392 If WITH-DEFS is non-nil, also associate the definition to each
393 label. The function will then return an alist whose key is label
394 and value definition."
398 ;; Depending on WITH-DEFS, store label or (label . def) of
399 ;; footnote reference/definition given as argument in RTN.
401 (let ((lbl (car el
)))
402 (push (if with-defs
(cons lbl
(nth 3 el
)) lbl
) rtn
))))))
406 ;; Find all labels found in definitions.
407 (goto-char (point-min))
409 (while (re-search-forward org-footnote-definition-re nil t
)
410 (when (setq def
(org-footnote-at-definition-p))
411 (funcall push-to-rtn def
))))
412 ;; Find all labels found in references.
413 (goto-char (point-min))
415 (while (setq ref
(org-footnote-get-next-reference))
416 (goto-char (nth 2 ref
))
417 (and (car ref
) ; ignore anonymous footnotes
418 (not (funcall (if with-defs
#'assoc
#'member
) (car ref
) rtn
))
419 (funcall push-to-rtn ref
))))))
422 (defun org-footnote-unique-label (&optional current
)
423 "Return a new unique footnote label.
425 The function returns the first \"fn:N\" or \"N\" label that is
428 Optional argument CURRENT is the list of labels active in the
430 (unless current
(setq current
(org-footnote-all-labels)))
431 (let ((fmt (if (eq org-footnote-auto-label
'plain
) "%d" "fn:%d"))
433 (while (member (format fmt cnt
) current
)
437 (defun org-footnote-new ()
438 "Insert a new footnote.
439 This command prompts for a label. If this is a label referencing an
440 existing label, only insert the label. If the footnote label is empty
441 or new, let the user edit the definition of the footnote."
443 (unless (org-footnote-in-valid-context-p)
444 (error "Cannot insert a footnote here"))
445 (let* ((lbls (and (not (equal org-footnote-auto-label
'random
))
446 (org-footnote-all-labels)))
447 (propose (org-footnote-unique-label lbls
))
449 (org-footnote-normalize-label
451 ((member org-footnote-auto-label
'(t plain
))
453 ((equal org-footnote-auto-label
'random
)
455 (substring (org-id-uuid) 0 8))
457 (org-icompleting-read
458 "Label (leave empty for anonymous): "
459 (mapcar 'list lbls
) nil nil
460 (if (eq org-footnote-auto-label
'confirm
) propose nil
)))))))
462 ((and label
(bolp) (not org-footnote-define-inline
))
463 (error "Cannot create a non-inlined footnote at left margin"))
468 (insert "[" label
"]")
469 (message "New reference to existing note"))
470 (org-footnote-define-inline
471 (insert "[" label
": ]")
473 (org-footnote-auto-adjust-maybe))
475 (insert "[" label
"]")
476 (org-footnote-create-definition label
)
477 (org-footnote-auto-adjust-maybe)))))
479 (defvar org-blank-before-new-entry nil
) ; silence byte-compiler
480 (defun org-footnote-create-definition (label)
481 "Start the definition of a footnote with label LABEL."
482 (interactive "sLabel: ")
483 (let ((label (org-footnote-normalize-label label
)))
486 ((eq major-mode
'org-mode
)
487 ;; If `org-footnote-section' is defined, find it, or create it
488 ;; at the end of the buffer.
489 (when org-footnote-section
490 (goto-char (point-min))
491 (let ((re (concat "^\\*+[ \t]+" org-footnote-section
"[ \t]*$")))
492 (unless (or (re-search-forward re nil t
)
493 (and (progn (widen) t
)
494 (re-search-forward re nil t
)))
495 (goto-char (point-max))
496 (skip-chars-backward " \t\r\n")
497 (unless (bolp) (newline))
498 ;; Insert new section. Separate it from the previous one
499 ;; with a blank line, unless `org-blank-before-new-entry'
500 ;; explicitly says no.
501 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
502 (zerop (save-excursion (org-back-over-empty-lines))))
504 (insert "* " org-footnote-section
"\n"))))
505 ;; Move to the end of this entry (which may be
506 ;; `org-footnote-section' or the current one).
507 (org-footnote-goto-local-insertion-point)
508 (org-show-context 'link-search
))
510 ;; In a non-Org file. Search for footnote tag, or create it if
511 ;; specified (at the end of buffer, or before signature if in
512 ;; Message mode). Set point after any definition already there.
513 (let ((tag (and org-footnote-tag-for-non-org-mode-files
514 (concat "^" (regexp-quote
515 org-footnote-tag-for-non-org-mode-files
)
517 (max (if (and (derived-mode-p 'message-mode
)
518 (goto-char (point-max))
520 message-signature-separator nil t
))
522 ;; Ensure one blank line separates last
523 ;; footnote from signature.
527 (point-max-marker))))
528 (set-marker-insertion-type max t
)
530 ;; Check if the footnote tag is defined but missing. In this
531 ;; case, insert it, before any footnote or one blank line
532 ;; after any previous text.
533 (when (and tag
(not (re-search-backward tag nil t
)))
534 (skip-chars-backward " \t\r\n")
535 (while (re-search-backward org-footnote-definition-re nil t
))
536 (unless (bolp) (newline 2))
537 (insert org-footnote-tag-for-non-org-mode-files
"\n\n"))
538 ;; Remove superfluous white space and clear marker.
540 (skip-chars-backward " \t\r\n")
541 (delete-region (point) max
)
542 (unless (bolp) (newline))
543 (set-marker max nil
))))
544 ;; Insert footnote label.
545 (insert "\n[" label
"] ")
546 ;; Only notify user about next possible action when in an Org
547 ;; buffer, as the bindings may have different meanings otherwise.
548 (when (eq major-mode
'org-mode
)
550 "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
553 (defun org-footnote-action (&optional special
)
554 "Do the right thing for footnotes.
556 When at a footnote reference, jump to the definition.
558 When at a definition, jump to the references if they exist, offer
559 to create them otherwise.
561 When neither at definition or reference, create a new footnote,
564 With prefix arg SPECIAL, offer additional commands in a menu."
569 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
570 (setq c
(read-char-exclusive))
572 ((eq c ?s
) (org-footnote-normalize 'sort
))
573 ((eq c ?r
) (org-footnote-renumber-fn:N
))
575 (org-footnote-renumber-fn:N
)
576 (org-footnote-normalize 'sort
))
577 ((eq c ?n
) (org-footnote-normalize))
578 ((eq c ?d
) (org-footnote-delete))
579 (t (error "No such footnote command %c" c
))))
580 ((setq tmp
(org-footnote-at-reference-p))
582 ;; Anonymous footnote: move point at the beginning of its
585 (goto-char (nth 1 tmp
))
587 ;; A definition exists: move to it.
588 ((ignore-errors (org-footnote-goto-definition (car tmp
))))
589 ;; No definition exists: offer to create it.
590 ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp
)))
591 (org-footnote-create-definition (car tmp
)))))
592 ((setq tmp
(org-footnote-at-definition-p))
593 (org-footnote-goto-previous-reference (car tmp
)))
594 (t (org-footnote-new)))))
596 (defvar org-footnote-insert-pos-for-preprocessor
'point-max
597 "See `org-footnote-normalize'.")
599 (defvar org-export-footnotes-seen nil
) ; silence byte-compiler
600 (defvar org-export-footnotes-data nil
) ; silence byte-compiler
603 (defun org-footnote-normalize (&optional sort-only export-props
)
604 "Collect the footnotes in various formats and normalize them.
606 This finds the different sorts of footnotes allowed in Org, and
607 normalizes them to the usual [N] format that is understood by the
610 When SORT-ONLY is set, only sort the footnote definitions into the
613 If Org is amidst an export process, EXPORT-PROPS will hold the
614 export properties of the buffer.
616 When EXPORT-PROPS is non-nil, the default action is to insert
617 normalized footnotes towards the end of the pre-processing
618 buffer. Some exporters (docbook, odt...) expect footnote
619 definitions to be available before any references to them. Such
620 exporters can let bind `org-footnote-insert-pos-for-preprocessor'
621 to symbol `point-min' to achieve the desired behaviour.
623 Additional note on `org-footnote-insert-pos-for-preprocessor':
624 1. This variable has not effect when FOR-PREPROCESSOR is nil.
625 2. This variable (potentially) obviates the need for extra scan
626 of pre-processor buffer as witnessed in
627 `org-export-docbook-get-footnotes'."
628 ;; This is based on Paul's function, but rewritten.
630 ;; Re-create `org-with-limited-levels', but not limited to Org
633 (and (boundp 'org-inlinetask-min-level
)
634 org-inlinetask-min-level
635 (1- org-inlinetask-min-level
)))
636 (nstars (and limit-level
637 (if org-odd-levels-only
638 (and limit-level
(1- (* limit-level
2)))
641 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ ")))
642 ;; Determine the highest marker used so far.
643 (ref-table (when export-props org-export-footnotes-seen
))
644 (count (if (and export-props ref-table
)
645 (apply 'max
(mapcar (lambda (e) (nth 1 e
)) ref-table
))
649 ;; 1. Find every footnote reference, extract the definition, and
650 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
651 ;; normalize references.
652 (goto-char (point-min))
653 (while (setq ref
(org-footnote-get-next-reference))
654 (let* ((lbl (car ref
))
655 ;; When footnote isn't anonymous, check if it's label
656 ;; (REF) is already stored in REF-TABLE. In that case,
657 ;; extract number used to identify it (MARKER). If
658 ;; footnote is unknown, increment the global counter
659 ;; (COUNT) to create an unused identifier.
660 (a (and lbl
(assoc lbl ref-table
)))
661 (marker (or (nth 1 a
) (incf count
)))
662 ;; Is the reference inline or pointing to an inline
664 (inlinep (or (stringp (nth 3 ref
)) (nth 3 a
))))
665 ;; Replace footnote reference with [MARKER]. Maybe fill
666 ;; paragraph once done. If SORT-ONLY is non-nil, only move
667 ;; to the end of reference found to avoid matching it twice.
668 ;; If EXPORT-PROPS isn't nil, also add `org-footnote'
669 ;; property to it, so it can be easily recognized by
672 (goto-char (nth 2 ref
))
673 (delete-region (nth 1 ref
) (nth 2 ref
))
674 (goto-char (nth 1 ref
))
675 (let ((new-ref (format "[%d]" marker
)))
676 (when export-props
(org-add-props new-ref
'(org-footnote t
)))
679 org-footnote-fill-after-inline-note-extraction
680 (org-fill-paragraph)))
681 ;; Add label (REF), identifier (MARKER), definition (DEF)
682 ;; and type (INLINEP) to REF-TABLE if data was unknown.
684 (let ((def (or (nth 3 ref
) ; inline
686 (cdr (assoc lbl org-export-footnotes-data
)))
687 (nth 3 (org-footnote-get-definition lbl
)))))
688 (push (list lbl marker
689 ;; When exporting, each definition goes
690 ;; through `org-export-preprocess-string' so
691 ;; it is ready to insert in the
692 ;; backend-specific buffer.
693 (if (and export-props def
)
697 '(:todo-keywords t
:tags t
:priority t
))))
698 (org-export-preprocess-string def parameters
))
700 inlinep
) ref-table
)))))
701 ;; 2. Find and remove the footnote section, if any. Also
702 ;; determine where footnotes shall be inserted (INS-POINT).
703 (goto-char (point-min))
705 ((and org-footnote-section
706 (eq major-mode
'org-mode
)
708 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section
)
711 (delete-region (match-beginning 0) (org-end-of-subtree t
)))
712 ((eq major-mode
'org-mode
)
713 (goto-char (point-max))
714 (unless (bolp) (newline)))
716 ;; Remove any left-over tag in the buffer, if one is set up.
717 (when org-footnote-tag-for-non-org-mode-files
718 (let ((tag (concat "^" (regexp-quote
719 org-footnote-tag-for-non-org-mode-files
)
721 (while (re-search-forward tag nil t
)
723 (delete-region (point) (progn (forward-line) (point))))))
724 ;; In Message mode, ensure footnotes are inserted before the
726 (if (and (derived-mode-p 'message-mode
)
727 (goto-char (point-max))
728 (re-search-backward message-signature-separator nil t
))
730 (goto-char (point-max)))))
731 ;; During export, `org-footnote-insert-pos-for-preprocessor' has
732 ;; precedence over previously found position.
735 (if (and export-props
736 (eq org-footnote-insert-pos-for-preprocessor
'point-min
))
739 ;; 3. Clean-up REF-TABLE.
745 ;; When only sorting, ignore inline footnotes.
746 ((and sort-only
(nth 3 x
)) nil
)
747 ;; No definition available: provide one.
749 (append (butlast x
2)
750 (list (format "DEFINITION NOT FOUND: %s" (car x
))
754 (setq ref-table
(nreverse ref-table
))
755 ;; 4. Remove left-over definitions in the buffer.
756 (mapc (lambda (x) (unless (nth 3 x
)
757 (org-footnote-delete-definitions (car x
))))
759 ;; 5. Insert the footnotes again in the buffer, at the
761 (goto-char ins-point
)
763 ;; No footnote: exit.
765 ;; Cases when footnotes should be inserted in one place.
766 ((or (not (eq major-mode
'org-mode
))
769 ;; Insert again the section title, if any. Ensure that title,
770 ;; or the subsequent footnotes, will be separated by a blank
771 ;; lines from the rest of the document. In an Org buffer,
772 ;; separate section with a blank line, unless explicitly
773 ;; stated in `org-blank-before-new-entry'.
775 ((not (eq major-mode
'org-mode
))
776 (skip-chars-backward " \t\n\r")
777 (delete-region (point) ins-point
)
778 (unless (bolp) (newline))
779 ;; Keep one blank line between footnotes and signature.
780 (when (and (derived-mode-p 'message-mode
)
782 (re-search-forward message-signature-separator nil t
)))
784 (when org-footnote-tag-for-non-org-mode-files
785 (insert "\n" org-footnote-tag-for-non-org-mode-files
"\n")))
786 ((and org-footnote-section
(not export-props
))
787 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
788 (zerop (save-excursion (org-back-over-empty-lines))))
790 (insert "* " org-footnote-section
"\n")))
791 (set-marker ins-point nil
)
792 ;; Insert the footnotes, separated by a blank line.
793 (insert (mapconcat (lambda (x) (format "\n[%s] %s"
794 (nth (if sort-only
0 1) x
) (nth 2 x
)))
796 (unless (eobp) (insert "\n"))
797 ;; When exporting, add newly inserted markers along with their
798 ;; associated definition to `org-export-footnotes-seen'.
800 (setq org-export-footnotes-seen ref-table
)))
801 ;; Else, insert each definition at the end of the section
802 ;; containing their first reference. Happens only in Org files
803 ;; with no special footnote section, and only when doing
805 (t (mapc 'org-insert-footnote-reference-near-definition
808 (defun org-insert-footnote-reference-near-definition (entry)
809 "Find first reference of footnote ENTRY and insert the definition there.
810 ENTRY is (fn-label num-mark definition)."
812 (goto-char (point-min))
813 (let ((ref (org-footnote-get-next-reference (car entry
))))
815 (goto-char (nth 2 ref
))
816 (org-footnote-goto-local-insertion-point)
817 (insert (format "\n[%s] %s\n" (car entry
) (nth 2 entry
)))))))
819 (defun org-footnote-goto-local-insertion-point ()
820 "Find insertion point for footnote, just before next outline heading."
821 (org-with-limited-levels (outline-next-heading))
822 (or (bolp) (newline))
823 (beginning-of-line 0)
824 (while (and (not (bobp)) (= (char-after) ?
#))
825 (beginning-of-line 0))
826 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
828 (skip-chars-backward "\n\r\t ")
831 (defun org-footnote-delete-references (label)
832 "Delete every reference to footnote LABEL.
833 Return the number of footnotes removed."
835 (goto-char (point-min))
837 (while (setq ref
(org-footnote-get-next-reference label
))
838 (goto-char (nth 1 ref
))
839 (delete-region (nth 1 ref
) (nth 2 ref
))
843 (defun org-footnote-delete-definitions (label)
844 "Delete every definition of the footnote LABEL.
845 Return the number of footnotes removed."
847 (goto-char (point-min))
848 (let ((def-re (concat "^\\[" (regexp-quote label
) "\\]"))
850 (while (re-search-forward def-re nil t
)
851 (let ((full-def (org-footnote-at-definition-p)))
852 (delete-region (nth 1 full-def
) (nth 2 full-def
)))
856 (defun org-footnote-delete (&optional label
)
857 "Delete the footnote at point.
858 This will remove the definition (even multiple definitions if they exist)
859 and all references of a footnote label.
861 If LABEL is non-nil, delete that footnote instead."
863 (let* ((nref 0) (ndef 0) x
864 ;; 1. Determine LABEL of footnote at point.
866 ;; LABEL is provided as argument.
868 ;; Footnote reference at point. If the footnote is
869 ;; anonymous, delete it and exit instead.
870 ((setq x
(org-footnote-at-reference-p))
873 (delete-region (nth 1 x
) (nth 2 x
))
874 (message "Anonymous footnote removed")
876 ;; Footnote definition at point.
877 ((setq x
(org-footnote-at-definition-p))
879 (t (error "Don't know which footnote to remove")))))
880 ;; 2. Now that LABEL is non-nil, find every reference and every
881 ;; definition, and delete them.
882 (setq nref
(org-footnote-delete-references label
)
883 ndef
(org-footnote-delete-definitions label
))
884 ;; 3. Verify consistency of footnotes and notify user.
885 (org-footnote-auto-adjust-maybe)
886 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
889 (defun org-footnote-renumber-fn:N
()
890 "Renumber the simple footnotes like fn:17 into a sequence in the document."
893 (org-with-wide-buffer
894 (goto-char (point-min))
895 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t
)
897 (goto-char (match-beginning 0))
898 ;; Ensure match is a footnote reference or definition.
899 (when (save-match-data (if (bolp)
900 (org-footnote-at-definition-p)
901 (org-footnote-at-reference-p)))
902 (let ((new-val (or (cdr (assoc (match-string 1) map
))
903 (number-to-string (incf n
)))))
904 (unless (assoc (match-string 1) map
)
905 (push (cons (match-string 1) new-val
) map
))
906 (replace-match new-val nil nil nil
1))))))))
908 (defun org-footnote-auto-adjust-maybe ()
909 "Renumber and/or sort footnotes according to user settings."
910 (when (memq org-footnote-auto-adjust
'(t renumber
))
911 (org-footnote-renumber-fn:N
))
912 (when (memq org-footnote-auto-adjust
'(t sort
))
913 (let ((label (car (org-footnote-at-definition-p))))
914 (org-footnote-normalize 'sort
)
916 (goto-char (point-min))
917 (and (re-search-forward (concat "^\\[" (regexp-quote label
) "\\]")
920 (just-one-space)))))))
922 (provide 'org-footnote
)
924 ;;; org-footnote.el ends here