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-macro-p
"org" ())
56 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
57 (declare-function org-show-context
"org" (&optional key
))
58 (declare-function org-trim
"org" (s))
59 (declare-function outline-next-heading
"outline")
61 (defvar org-outline-regexp-bol
) ; defined in org.el
62 (defvar org-odd-levels-only
) ; defined in org.el
63 (defvar org-bracket-link-regexp
) ; defined in org.el
64 (defvar message-cite-prefix-regexp
) ; defined in message.el
65 (defvar message-signature-separator
) ; defined in message.el
67 (defconst org-footnote-re
68 ;; Only [1]-like footnotes are closed in this regexp, as footnotes
69 ;; from other types might contain square brackets (i.e. links) in
72 ;; `org-re' is used for regexp compatibility with XEmacs.
73 (org-re (concat "\\[\\(?:"
74 ;; Match inline footnotes.
75 "fn:\\([-_[:word:]]+\\)?:\\|"
76 ;; Match other footnotes.
77 "\\(?:\\([0-9]+\\)\\]\\)\\|"
78 "\\(fn:[-_[:word:]]+\\)"
80 "Regular expression for matching footnotes.")
82 (defconst org-footnote-definition-re
83 (org-re "^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
84 "Regular expression matching the definition of a footnote.")
86 (defvar org-footnote-forbidden-blocks
'("example" "verse" "src" "ascii" "beamer"
87 "docbook" "html" "latex" "odt")
88 "Names of blocks where footnotes are not allowed.")
90 (defgroup org-footnote nil
91 "Footnotes in Org-mode."
95 (defcustom org-footnote-section
"Footnotes"
96 "Outline heading containing footnote definitions before export.
97 This can be nil, to place footnotes locally at the end of the current
98 outline node. If can also be the name of a special outline heading
99 under which footnotes should be put.
100 This variable defines the place where Org puts the definition
101 automatically, i.e. when creating the footnote, and when sorting the notes.
102 However, by hand you may place definitions *anywhere*.
103 If this is a string, during export, all subtrees starting with this
104 heading will be removed after extracting footnote definitions."
107 (string :tag
"Collect footnotes under heading")
108 (const :tag
"Define footnotes locally" nil
)))
110 (defcustom org-footnote-tag-for-non-org-mode-files
"Footnotes:"
111 "Tag marking the beginning of footnote section.
112 The Org footnote engine can be used in arbitrary text files as well
113 as in Org-mode. Outside Org mode, new footnotes are always placed at
114 the end of the file. When you normalize the notes, any line containing
115 only this tag will be removed, a new one will be inserted at the end
116 of the file, followed by the collected and normalized footnotes.
118 If you don't want any tag in such buffers, set this variable to nil."
121 (string :tag
"Collect footnotes under tag")
122 (const :tag
"Don't use a tag" nil
)))
124 (defcustom org-footnote-define-inline nil
125 "Non-nil means define footnotes inline, at reference location.
126 When nil, footnotes will be defined in a special section near
127 the end of the document. When t, the [fn:label:definition] notation
128 will be used to define the footnote at the reference position."
132 (defcustom org-footnote-auto-label t
133 "Non-nil means define automatically new labels for footnotes.
136 nil prompt the user for each label
137 t create unique labels of the form [fn:1], [fn:2], ...
138 confirm like t, but let the user edit the created value. In particular,
139 the label can be removed from the minibuffer, to create
140 an anonymous footnote.
141 random Automatically generate a unique, random label.
142 plain Automatically create plain number labels like [1]"
145 (const :tag
"Prompt for label" nil
)
146 (const :tag
"Create automatic [fn:N]" t
)
147 (const :tag
"Offer automatic [fn:N] for editing" confirm
)
148 (const :tag
"Create a random label" random
)
149 (const :tag
"Create automatic [N]" plain
)))
151 (defcustom org-footnote-auto-adjust nil
152 "Non-nil means automatically adjust footnotes after insert/delete.
153 When this is t, after each insertion or deletion of a footnote,
154 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
155 If you want to have just sorting or just renumbering, set this variable
156 to `sort' or `renumber'.
158 The main values of this variable can be set with in-buffer options:
161 #+STARTUP: nofnadjust"
164 (const :tag
"Renumber" renumber
)
165 (const :tag
"Sort" sort
)
166 (const :tag
"Renumber and Sort" t
)))
168 (defcustom org-footnote-fill-after-inline-note-extraction nil
169 "Non-nil means fill paragraphs after extracting footnotes.
170 When extracting inline footnotes, the lengths of lines can change a lot.
171 When this option is set, paragraphs from which an inline footnote has been
172 extracted will be filled again."
176 (defun org-footnote-in-valid-context-p ()
177 "Is point in a context where footnotes are allowed?"
179 (not (or (org-in-commented-line)
180 (org-in-indented-comment-line)
181 ;; Avoid protected environments (LaTeX export)
182 (get-text-property (point) 'org-protected
)
183 ;; Avoid literal example.
184 (org-in-verbatim-emphasis)
187 (looking-at "[ \t]*:[ \t]+"))
188 ;; Avoid cited text and headers in message-mode.
189 (and (derived-mode-p 'message-mode
)
192 (looking-at message-cite-prefix-regexp
))
193 (message-point-in-header-p)))
194 ;; Avoid forbidden blocks.
195 (org-in-block-p org-footnote-forbidden-blocks
)))))
197 (defun org-footnote-at-reference-p ()
198 "Is the cursor at a footnote reference?
200 If so, return a list containing its label, beginning and ending
201 positions, and the definition, when inlined."
202 (when (and (org-footnote-in-valid-context-p)
203 (or (looking-at org-footnote-re
)
204 (org-in-regexp org-footnote-re
)
205 (save-excursion (re-search-backward org-footnote-re nil t
)))
206 ;; Only inline footnotes can start at bol.
207 (or (eq (char-before (match-end 0)) 58)
208 (/= (match-beginning 0) (point-at-bol))))
209 (let* ((beg (match-beginning 0))
210 (label (or (match-string 2) (match-string 3)
211 ;; Anonymous footnotes don't have labels
212 (and (match-string 1) (concat "fn:" (match-string 1)))))
213 ;; Inline footnotes don't end at (match-end 0) as
214 ;; `org-footnote-re' stops just after the second colon.
215 ;; Find the real ending with `scan-sexps', so Org doesn't
216 ;; get fooled by unrelated closing square brackets.
217 (end (ignore-errors (scan-sexps beg
1))))
218 ;; Point is really at a reference if it's located before true
219 ;; ending of the footnote.
220 (when (and end
(< (point) end
)
221 ;; Verify match isn't a part of a link.
226 (org-in-regexp org-bracket-link-regexp
))))
227 (and linkp
(< (point) (cdr linkp
))))))
228 ;; Verify point doesn't belong to a LaTeX macro.
229 ;; Beware though, when two footnotes are side by
230 ;; side, once the first one is changed into LaTeX,
231 ;; the second one might then be considered as an
232 ;; optional argument of the command. Thus, check
233 ;; the `org-protected' property of that command.
234 (or (not (org-inside-latex-macro-p))
235 (get-text-property (1- beg
) 'org-protected
)))
237 ;; Definition: ensure this is an inline footnote first.
238 (and (or (not label
) (match-string 1))
239 (org-trim (buffer-substring (match-end 0) (1- end
)))))))))
241 (defun org-footnote-at-definition-p ()
242 "Is the cursor at a footnote definition?
244 This matches only pure definitions like [1] or [fn:name] at the beginning
245 of a line. It does not match references like [fn:name:definition], where the
246 footnote text is included and defined locally.
248 The return value will be nil if not at a footnote definition, and a list with
249 label, start, end and definition of the footnote otherwise."
250 (when (org-footnote-in-valid-context-p)
253 (let ((lim (save-excursion (re-search-backward
254 (concat org-outline-regexp-bol
255 "\\|^[ \t]*$") nil t
))))
256 (when (re-search-backward org-footnote-definition-re lim t
)
258 (list (match-string 1)
261 ;; In a message, limit search to signature.
262 (let ((bound (and (derived-mode-p 'message-mode
)
264 (goto-char (point-max))
266 message-signature-separator nil t
)))))
267 (or (and (re-search-forward
269 (concat org-outline-regexp-bol
"\\|"
270 org-footnote-definition-re
"\\|"
273 (progn (skip-chars-forward " \t\n") (point-at-bol)))
275 (org-trim (buffer-substring (match-end 0) (point)))))))))
277 (defun org-footnote-get-next-reference (&optional label backward limit
)
278 "Return complete reference of the next footnote.
280 If LABEL is provided, get the next reference of that footnote. If
281 BACKWARD is non-nil, find previous reference instead. LIMIT is
282 the buffer position bounding the search.
284 Return value is a list like those provided by `org-footnote-at-reference-p'.
285 If no footnote is found, return nil."
287 (let* ((label-fmt (if label
(format "\\[%s[]:]" label
) org-footnote-re
)))
290 (unless (funcall (if backward
#'re-search-backward
#'re-search-forward
)
293 (unless backward
(backward-char))
294 (let ((ref (org-footnote-at-reference-p)))
295 (when ref
(throw 'exit ref
))))))))
297 (defun org-footnote-next-reference-or-definition (limit)
298 "Move point to next footnote reference or definition.
300 LIMIT is the buffer position bounding the search.
302 Return value is a list like those provided by
303 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
304 If no footnote is found, return nil."
305 (let* (ref (origin (point)))
308 (unless (re-search-forward org-footnote-re limit t
)
311 ;; Beware: with [1]-like footnotes point will be just after
312 ;; the closing square bracket.
315 ((setq ref
(org-footnote-at-reference-p))
317 ;; Definition: also grab the last square bracket, only
318 ;; matched in `org-footnote-re' for [1]-like footnotes.
319 ((save-match-data (org-footnote-at-definition-p))
320 (let ((end (match-end 0)))
322 (list nil
(match-beginning 0)
323 (if (eq (char-before end
) 93) end
(1+ end
)))))))))))
325 (defun org-footnote-get-definition (label)
326 "Return label, boundaries and definition of the footnote LABEL."
327 (let* ((label (regexp-quote (org-footnote-normalize-label label
)))
328 (re (format "^\\[%s\\]\\|.\\[%s:" label label
))
331 (when (or (re-search-forward re nil t
)
332 (and (goto-char (point-min))
333 (re-search-forward re nil t
))
334 (and (progn (widen) t
)
335 (goto-char (point-min))
336 (re-search-forward re nil t
)))
337 (let ((refp (org-footnote-at-reference-p)))
339 ((and (nth 3 refp
) refp
))
340 ((org-footnote-at-definition-p))))))))
342 (defun org-footnote-goto-definition (label)
343 "Move point to the definition of the footnote LABEL."
344 (interactive "sLabel: ")
346 (let ((def (org-footnote-get-definition label
)))
348 (error "Cannot find definition of footnote %s" label
)
349 (goto-char (nth 1 def
))
350 (looking-at (format "\\[%s\\]\\|\\[%s:" label label
))
351 (goto-char (match-end 0))
352 (org-show-context 'link-search
)
354 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))))
356 (defun org-footnote-goto-previous-reference (label)
357 "Find the first closest (to point) reference of footnote with label LABEL."
358 (interactive "sLabel: ")
360 (let* ((label (org-footnote-normalize-label label
)) ref
)
362 (setq ref
(or (org-footnote-get-next-reference label t
)
363 (org-footnote-get-next-reference label
)
367 (org-footnote-get-next-reference label t
)
368 (org-footnote-get-next-reference label
))))))
370 (error "Cannot find reference of footnote %s" label
)
371 (goto-char (nth 1 ref
))
372 (org-show-context 'link-search
))))
374 (defun org-footnote-normalize-label (label)
375 "Return LABEL as an appropriate string."
377 ((numberp label
) (number-to-string label
))
378 ((equal "" label
) nil
)
379 ((not (string-match "^[0-9]+$\\|^fn:" label
))
380 (concat "fn:" label
))
383 (defun org-footnote-all-labels (&optional with-defs
)
384 "Return list with all defined foot labels used in the buffer.
386 If WITH-DEFS is non-nil, also associate the definition to each
387 label. The function will then return an alist whose key is label
388 and value definition."
392 ;; Depending on WITH-DEFS, store label or (label . def) of
393 ;; footnote reference/definition given as argument in RTN.
395 (let ((lbl (car el
)))
396 (push (if with-defs
(cons lbl
(nth 3 el
)) lbl
) rtn
))))))
400 ;; Find all labels found in definitions.
401 (goto-char (point-min))
403 (while (re-search-forward org-footnote-definition-re nil t
)
404 (when (setq def
(org-footnote-at-definition-p))
405 (funcall push-to-rtn def
))))
406 ;; Find all labels found in references.
407 (goto-char (point-min))
409 (while (setq ref
(org-footnote-get-next-reference))
410 (goto-char (nth 2 ref
))
411 (and (car ref
) ; ignore anonymous footnotes
412 (not (funcall (if with-defs
#'assoc
#'member
) (car ref
) rtn
))
413 (funcall push-to-rtn ref
))))))
416 (defun org-footnote-unique-label (&optional current
)
417 "Return a new unique footnote label.
419 The function returns the first \"fn:N\" or \"N\" label that is
422 Optional argument CURRENT is the list of labels active in the
424 (unless current
(setq current
(org-footnote-all-labels)))
425 (let ((fmt (if (eq org-footnote-auto-label
'plain
) "%d" "fn:%d"))
427 (while (member (format fmt cnt
) current
)
431 (defun org-footnote-new ()
432 "Insert a new footnote.
433 This command prompts for a label. If this is a label referencing an
434 existing label, only insert the label. If the footnote label is empty
435 or new, let the user edit the definition of the footnote."
437 (unless (org-footnote-in-valid-context-p)
438 (error "Cannot insert a footnote here"))
439 (let* ((lbls (and (not (equal org-footnote-auto-label
'random
))
440 (org-footnote-all-labels)))
441 (propose (org-footnote-unique-label lbls
))
443 (org-footnote-normalize-label
445 ((member org-footnote-auto-label
'(t plain
))
447 ((equal org-footnote-auto-label
'random
)
449 (substring (org-id-uuid) 0 8))
451 (org-icompleting-read
452 "Label (leave empty for anonymous): "
453 (mapcar 'list lbls
) nil nil
454 (if (eq org-footnote-auto-label
'confirm
) propose nil
)))))))
456 ((and label
(bolp) (not org-footnote-define-inline
))
457 (error "Cannot create a non-inlined footnote at left margin"))
462 (insert "[" label
"]")
463 (message "New reference to existing note"))
464 (org-footnote-define-inline
465 (insert "[" label
": ]")
467 (org-footnote-auto-adjust-maybe))
469 (insert "[" label
"]")
470 (org-footnote-create-definition label
)
471 (org-footnote-auto-adjust-maybe)))))
473 (defvar org-blank-before-new-entry nil
) ; silence byte-compiler
474 (defun org-footnote-create-definition (label)
475 "Start the definition of a footnote with label LABEL."
476 (interactive "sLabel: ")
477 (let ((label (org-footnote-normalize-label label
)))
481 ;; If `org-footnote-section' is defined, find it, or create it
482 ;; at the end of the buffer.
483 (when org-footnote-section
484 (goto-char (point-min))
485 (let ((re (concat "^\\*+[ \t]+" org-footnote-section
"[ \t]*$")))
486 (unless (or (re-search-forward re nil t
)
487 (and (progn (widen) t
)
488 (re-search-forward re nil t
)))
489 (goto-char (point-max))
490 (skip-chars-backward " \t\r\n")
491 (unless (bolp) (newline))
492 ;; Insert new section. Separate it from the previous one
493 ;; with a blank line, unless `org-blank-before-new-entry'
494 ;; explicitly says no.
495 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
496 (zerop (save-excursion (org-back-over-empty-lines))))
498 (insert "* " org-footnote-section
"\n"))))
499 ;; Move to the end of this entry (which may be
500 ;; `org-footnote-section' or the current one).
501 (org-footnote-goto-local-insertion-point)
502 (org-show-context 'link-search
))
504 ;; In a non-Org file. Search for footnote tag, or create it if
505 ;; specified (at the end of buffer, or before signature if in
506 ;; Message mode). Set point after any definition already there.
507 (let ((tag (and org-footnote-tag-for-non-org-mode-files
508 (concat "^" (regexp-quote
509 org-footnote-tag-for-non-org-mode-files
)
511 (max (if (and (derived-mode-p 'message-mode
)
512 (goto-char (point-max))
514 message-signature-separator nil t
))
516 ;; Ensure one blank line separates last
517 ;; footnote from signature.
521 (point-max-marker))))
523 ;; Check if the footnote tag is defined but missing. In this
524 ;; case, insert it, before any footnote or one blank line
525 ;; after any previous text.
527 (when (and tag
(not (re-search-backward tag nil t
)))
528 (skip-chars-backward " \t\r\n")
529 (while (re-search-backward org-footnote-definition-re nil t
))
530 (unless (bolp) (newline 2))
531 (insert org-footnote-tag-for-non-org-mode-files
"\n\n")))
532 ;; Remove superfluous white space and clear marker.
533 (skip-chars-backward " \t\r\n")
534 (delete-region (point) max
)
535 (unless (bolp) (newline))
536 (set-marker max nil
))))
537 ;; Insert footnote label.
538 (insert "\n[" label
"] ")
539 ;; Only notify user about next possible action when in an Org
540 ;; buffer, as the bindings may have different meanings otherwise.
543 "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
546 (defun org-footnote-action (&optional special
)
547 "Do the right thing for footnotes.
549 When at a footnote reference, jump to the definition.
551 When at a definition, jump to the references if they exist, offer
552 to create them otherwise.
554 When neither at definition or reference, create a new footnote,
557 With prefix arg SPECIAL, offer additional commands in a menu."
562 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
563 (setq c
(read-char-exclusive))
565 ((eq c ?s
) (org-footnote-normalize 'sort
))
566 ((eq c ?r
) (org-footnote-renumber-fn:N
))
568 (org-footnote-renumber-fn:N
)
569 (org-footnote-normalize 'sort
))
570 ((eq c ?n
) (org-footnote-normalize))
571 ((eq c ?d
) (org-footnote-delete))
572 (t (error "No such footnote command %c" c
))))
573 ((setq tmp
(org-footnote-at-reference-p))
575 ;; Anonymous footnote: move point at the beginning of its
578 (goto-char (nth 1 tmp
))
580 ;; A definition exists: move to it.
581 ((ignore-errors (org-footnote-goto-definition (car tmp
))))
582 ;; No definition exists: offer to create it.
583 ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp
)))
584 (org-footnote-create-definition (car tmp
)))))
585 ((setq tmp
(org-footnote-at-definition-p))
586 (org-footnote-goto-previous-reference (car tmp
)))
587 (t (org-footnote-new)))))
589 (defvar org-footnote-insert-pos-for-preprocessor
'point-max
590 "See `org-footnote-normalize'.")
592 (defvar org-export-footnotes-seen nil
) ; silence byte-compiler
593 (defvar org-export-footnotes-data nil
) ; silence byte-compiler
596 (defun org-footnote-normalize (&optional sort-only export-props
)
597 "Collect the footnotes in various formats and normalize them.
599 This finds the different sorts of footnotes allowed in Org, and
600 normalizes them to the usual [N] format that is understood by the
603 When SORT-ONLY is set, only sort the footnote definitions into the
606 If Org is amidst an export process, EXPORT-PROPS will hold the
607 export properties of the buffer.
609 When EXPORT-PROPS is non-nil, the default action is to insert
610 normalized footnotes towards the end of the pre-processing
611 buffer. Some exporters (docbook, odt...) expect footnote
612 definitions to be available before any references to them. Such
613 exporters can let bind `org-footnote-insert-pos-for-preprocessor'
614 to symbol `point-min' to achieve the desired behaviour.
616 Additional note on `org-footnote-insert-pos-for-preprocessor':
617 1. This variable has not effect when FOR-PREPROCESSOR is nil.
618 2. This variable (potentially) obviates the need for extra scan
619 of pre-processor buffer as witnessed in
620 `org-export-docbook-get-footnotes'."
621 ;; This is based on Paul's function, but rewritten.
623 ;; Re-create `org-with-limited-levels', but not limited to Org
626 (and (boundp 'org-inlinetask-min-level
)
627 org-inlinetask-min-level
628 (1- org-inlinetask-min-level
)))
629 (nstars (and limit-level
630 (if org-odd-levels-only
631 (and limit-level
(1- (* limit-level
2)))
634 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ ")))
635 ;; Determine the highest marker used so far.
636 (ref-table (when export-props org-export-footnotes-seen
))
637 (count (if (and export-props ref-table
)
638 (apply 'max
(mapcar (lambda (e) (nth 1 e
)) ref-table
))
642 ;; 1. Find every footnote reference, extract the definition, and
643 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
644 ;; normalize references.
645 (goto-char (point-min))
646 (while (setq ref
(org-footnote-get-next-reference))
647 (let* ((lbl (car ref
))
648 ;; When footnote isn't anonymous, check if it's label
649 ;; (REF) is already stored in REF-TABLE. In that case,
650 ;; extract number used to identify it (MARKER). If
651 ;; footnote is unknown, increment the global counter
652 ;; (COUNT) to create an unused identifier.
653 (a (and lbl
(assoc lbl ref-table
)))
654 (marker (or (nth 1 a
) (incf count
)))
655 ;; Is the reference inline or pointing to an inline
657 (inlinep (or (stringp (nth 3 ref
)) (nth 3 a
))))
658 ;; Replace footnote reference with [MARKER]. Maybe fill
659 ;; paragraph once done. If SORT-ONLY is non-nil, only move
660 ;; to the end of reference found to avoid matching it twice.
661 ;; If EXPORT-PROPS isn't nil, also add `org-footnote'
662 ;; property to it, so it can be easily recognized by
665 (goto-char (nth 2 ref
))
666 (delete-region (nth 1 ref
) (nth 2 ref
))
667 (goto-char (nth 1 ref
))
668 (let ((new-ref (format "[%d]" marker
)))
669 (when export-props
(org-add-props new-ref
'(org-footnote t
)))
672 org-footnote-fill-after-inline-note-extraction
673 (org-fill-paragraph)))
674 ;; Add label (REF), identifier (MARKER), definition (DEF)
675 ;; and type (INLINEP) to REF-TABLE if data was unknown.
677 (let ((def (or (nth 3 ref
) ; inline
679 (cdr (assoc lbl org-export-footnotes-data
)))
680 (nth 3 (org-footnote-get-definition lbl
)))))
681 (push (list lbl marker
682 ;; When exporting, each definition goes
683 ;; through `org-export-preprocess-string' so
684 ;; it is ready to insert in the
685 ;; backend-specific buffer.
686 (if (and export-props def
)
690 '(:todo-keywords t
:tags t
:priority t
))))
691 (org-export-preprocess-string def parameters
))
693 inlinep
) ref-table
)))))
694 ;; 2. Find and remove the footnote section, if any. Also
695 ;; determine where footnotes shall be inserted (INS-POINT).
696 (goto-char (point-min))
698 ((and org-footnote-section
701 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section
)
704 (delete-region (match-beginning 0) (org-end-of-subtree t
)))
706 (goto-char (point-max))
707 (unless (bolp) (newline)))
709 ;; Remove any left-over tag in the buffer, if one is set up.
710 (when org-footnote-tag-for-non-org-mode-files
711 (let ((tag (concat "^" (regexp-quote
712 org-footnote-tag-for-non-org-mode-files
)
714 (while (re-search-forward tag nil t
)
716 (delete-region (point) (progn (forward-line) (point))))))
717 ;; In Message mode, ensure footnotes are inserted before the
719 (if (and (derived-mode-p 'message-mode
)
720 (goto-char (point-max))
721 (re-search-backward message-signature-separator nil t
))
723 (goto-char (point-max)))))
724 ;; During export, `org-footnote-insert-pos-for-preprocessor' has
725 ;; precedence over previously found position.
728 (if (and export-props
729 (eq org-footnote-insert-pos-for-preprocessor
'point-min
))
732 ;; 3. Clean-up REF-TABLE.
738 ;; When only sorting, ignore inline footnotes.
739 ((and sort-only
(nth 3 x
)) nil
)
740 ;; No definition available: provide one.
742 (append (butlast x
2)
743 (list (format "DEFINITION NOT FOUND: %s" (car x
))
747 (setq ref-table
(nreverse ref-table
))
748 ;; 4. Remove left-over definitions in the buffer.
749 (mapc (lambda (x) (unless (nth 3 x
)
750 (org-footnote-delete-definitions (car x
))))
752 ;; 5. Insert the footnotes again in the buffer, at the
754 (goto-char ins-point
)
756 ;; No footnote: exit.
758 ;; Cases when footnotes should be inserted in one place.
759 ((or (not (org-mode-p))
762 ;; Insert again the section title, if any. Ensure that title,
763 ;; or the subsequent footnotes, will be separated by a blank
764 ;; lines from the rest of the document. In an Org buffer,
765 ;; separate section with a blank line, unless explicitly
766 ;; stated in `org-blank-before-new-entry'.
769 (skip-chars-backward " \t\n\r")
770 (delete-region (point) ins-point
)
771 (unless (bolp) (newline))
772 ;; Keep one blank line between footnotes and signature.
773 (when (and (derived-mode-p 'message-mode
)
775 (re-search-forward message-signature-separator nil t
)))
777 (when org-footnote-tag-for-non-org-mode-files
778 (insert "\n" org-footnote-tag-for-non-org-mode-files
"\n")))
779 ((and org-footnote-section
(not export-props
))
780 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
781 (zerop (save-excursion (org-back-over-empty-lines))))
783 (insert "* " org-footnote-section
"\n")))
784 (set-marker ins-point nil
)
785 ;; Insert the footnotes, separated by a blank line.
786 (insert (mapconcat (lambda (x) (format "\n[%s] %s"
787 (nth (if sort-only
0 1) x
) (nth 2 x
)))
789 ;; When exporting, add newly inserted markers along with their
790 ;; associated definition to `org-export-footnotes-seen'.
792 (setq org-export-footnotes-seen ref-table
)))
793 ;; Else, insert each definition at the end of the section
794 ;; containing their first reference. Happens only in Org files
795 ;; with no special footnote section, and only when doing
797 (t (mapc 'org-insert-footnote-reference-near-definition
800 (defun org-insert-footnote-reference-near-definition (entry)
801 "Find first reference of footnote ENTRY and insert the definition there.
802 ENTRY is (fn-label num-mark definition)."
804 (goto-char (point-min))
805 (let ((ref (org-footnote-get-next-reference (car entry
))))
807 (goto-char (nth 2 ref
))
808 (org-footnote-goto-local-insertion-point)
809 (insert (format "\n[%s] %s\n" (car entry
) (nth 2 entry
)))))))
811 (defun org-footnote-goto-local-insertion-point ()
812 "Find insertion point for footnote, just before next outline heading."
813 (org-with-limited-levels (outline-next-heading))
814 (or (bolp) (newline))
815 (beginning-of-line 0)
816 (while (and (not (bobp)) (= (char-after) ?
#))
817 (beginning-of-line 0))
818 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
820 (skip-chars-backward "\n\r\t ")
823 (defun org-footnote-delete-references (label)
824 "Delete every reference to footnote LABEL.
825 Return the number of footnotes removed."
827 (goto-char (point-min))
829 (while (setq ref
(org-footnote-get-next-reference label
))
830 (goto-char (nth 1 ref
))
831 (delete-region (nth 1 ref
) (nth 2 ref
))
835 (defun org-footnote-delete-definitions (label)
836 "Delete every definition of the footnote LABEL.
837 Return the number of footnotes removed."
839 (goto-char (point-min))
840 (let ((def-re (concat "^\\[" (regexp-quote label
) "\\]"))
842 (while (re-search-forward def-re nil t
)
843 (let ((full-def (org-footnote-at-definition-p)))
844 (delete-region (nth 1 full-def
) (nth 2 full-def
)))
848 (defun org-footnote-delete (&optional label
)
849 "Delete the footnote at point.
850 This will remove the definition (even multiple definitions if they exist)
851 and all references of a footnote label.
853 If LABEL is non-nil, delete that footnote instead."
855 (let* ((nref 0) (ndef 0) x
856 ;; 1. Determine LABEL of footnote at point.
858 ;; LABEL is provided as argument.
860 ;; Footnote reference at point. If the footnote is
861 ;; anonymous, delete it and exit instead.
862 ((setq x
(org-footnote-at-reference-p))
865 (delete-region (nth 1 x
) (nth 2 x
))
866 (message "Anonymous footnote removed")
868 ;; Footnote definition at point.
869 ((setq x
(org-footnote-at-definition-p))
871 (t (error "Don't know which footnote to remove")))))
872 ;; 2. Now that LABEL is non-nil, find every reference and every
873 ;; definition, and delete them.
874 (setq nref
(org-footnote-delete-references label
)
875 ndef
(org-footnote-delete-definitions label
))
876 ;; 3. Verify consistency of footnotes and notify user.
877 (org-footnote-auto-adjust-maybe)
878 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
881 (defun org-footnote-renumber-fn:N
()
882 "Renumber the simple footnotes like fn:17 into a sequence in the document."
888 (goto-char (point-min))
889 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t
)
890 (setq i
(string-to-number (match-string 1)))
891 (when (and (string-match "\\S-" (buffer-substring
892 (point-at-bol) (match-beginning 0)))
894 (push (cons i
(number-to-string (incf n
))) map
)))
895 (goto-char (point-min))
896 (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t
)
897 (replace-match (concat "\\1"
898 (cdr (assq (string-to-number (match-string 2))
902 (defun org-footnote-auto-adjust-maybe ()
903 "Renumber and/or sort footnotes according to user settings."
904 (when (memq org-footnote-auto-adjust
'(t renumber
))
905 (org-footnote-renumber-fn:N
))
906 (when (memq org-footnote-auto-adjust
'(t sort
))
907 (let ((label (car (org-footnote-at-definition-p))))
908 (org-footnote-normalize 'sort
)
910 (goto-char (point-min))
911 (and (re-search-forward (concat "^\\[" (regexp-quote label
) "\\]")
914 (just-one-space)))))))
916 (provide 'org-footnote
)
918 ;;; org-footnote.el ends here