1 ;;; org-footnote.el --- Footnote support in Org and elsewhere
3 ;; Copyright (C) 2009-2012 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 (/= (match-beginning 0) (point-at-bol)))
209 (let* ((beg (match-beginning 0))
210 (label (or (org-match-string-no-properties 2)
211 (org-match-string-no-properties 3)
212 ;; Anonymous footnotes don't have labels
213 (and (match-string 1)
214 (concat "fn:" (org-match-string-no-properties 1)))))
215 ;; Inline footnotes don't end at (match-end 0) as
216 ;; `org-footnote-re' stops just after the second colon.
217 ;; Find the real ending with `scan-sexps', so Org doesn't
218 ;; get fooled by unrelated closing square brackets.
219 (end (ignore-errors (scan-sexps beg
1))))
220 ;; Point is really at a reference if it's located before true
221 ;; ending of the footnote.
222 (when (and end
(< (point) end
)
223 ;; Verify match isn't a part of a link.
228 (org-in-regexp org-bracket-link-regexp
))))
229 (and linkp
(< (point) (cdr linkp
))))))
230 ;; Verify point doesn't belong to a LaTeX macro.
231 ;; Beware though, when two footnotes are side by
232 ;; side, once the first one is changed into LaTeX,
233 ;; the second one might then be considered as an
234 ;; optional argument of the command. Thus, check
235 ;; the `org-protected' property of that command.
236 (or (not (org-inside-latex-macro-p))
237 (get-text-property (1- beg
) 'org-protected
)))
239 ;; Definition: ensure this is an inline footnote first.
240 (and (or (not label
) (match-string 1))
241 (org-trim (buffer-substring-no-properties
242 (match-end 0) (1- end
)))))))))
244 (defun org-footnote-at-definition-p ()
245 "Is the cursor at a footnote definition?
247 This matches only pure definitions like [1] or [fn:name] at the beginning
248 of a line. It does not match references like [fn:name:definition], where the
249 footnote text is included and defined locally.
251 The return value will be nil if not at a footnote definition, and a list with
252 label, start, end and definition of the footnote otherwise."
253 (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
256 (let ((lim (save-excursion (re-search-backward
257 (concat org-outline-regexp-bol
258 "\\|^[ \t]*$") nil t
))))
259 (when (re-search-backward org-footnote-definition-re lim t
)
261 (list (org-match-string-no-properties 1)
264 ;; In a message, limit search to signature.
265 (let ((bound (and (derived-mode-p 'message-mode
)
267 (goto-char (point-max))
269 message-signature-separator nil t
)))))
270 (or (and (re-search-forward
271 (concat org-outline-regexp-bol
"\\|"
272 org-footnote-definition-re
"\\|"
275 (progn (skip-chars-forward " \t\n") (point-at-bol)))
277 (org-trim (buffer-substring-no-properties
278 (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 ((bolp) (error "Cannot create a footnote reference at left margin"))
467 (insert "[" label
"]")
468 (message "New reference to existing note"))
469 (org-footnote-define-inline
470 (insert "[" label
": ]")
472 (org-footnote-auto-adjust-maybe))
474 (insert "[" label
"]")
475 (org-footnote-create-definition label
)
476 (org-footnote-auto-adjust-maybe)))))
478 (defvar org-blank-before-new-entry nil
) ; silence byte-compiler
479 (defun org-footnote-create-definition (label)
480 "Start the definition of a footnote with label LABEL."
481 (interactive "sLabel: ")
482 (let ((label (org-footnote-normalize-label label
)))
485 ((eq major-mode
'org-mode
)
486 ;; If `org-footnote-section' is defined, find it, or create it
487 ;; at the end of the buffer.
488 (when org-footnote-section
489 (goto-char (point-min))
490 (let ((re (concat "^\\*+[ \t]+" org-footnote-section
"[ \t]*$")))
491 (unless (or (re-search-forward re nil t
)
492 (and (progn (widen) t
)
493 (re-search-forward re nil t
)))
494 (goto-char (point-max))
495 (skip-chars-backward " \t\r\n")
496 (unless (bolp) (newline))
497 ;; Insert new section. Separate it from the previous one
498 ;; with a blank line, unless `org-blank-before-new-entry'
499 ;; explicitly says no.
500 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
501 (zerop (save-excursion (org-back-over-empty-lines))))
503 (insert "* " org-footnote-section
"\n"))))
504 ;; Move to the end of this entry (which may be
505 ;; `org-footnote-section' or the current one).
506 (org-footnote-goto-local-insertion-point)
507 (org-show-context 'link-search
))
509 ;; In a non-Org file. Search for footnote tag, or create it if
510 ;; specified (at the end of buffer, or before signature if in
511 ;; Message mode). Set point after any definition already there.
512 (let ((tag (and org-footnote-tag-for-non-org-mode-files
513 (concat "^" (regexp-quote
514 org-footnote-tag-for-non-org-mode-files
)
516 (max (if (and (derived-mode-p 'message-mode
)
517 (goto-char (point-max))
519 message-signature-separator nil t
))
521 ;; Ensure one blank line separates last
522 ;; footnote from signature.
526 (point-max-marker))))
527 (set-marker-insertion-type max t
)
529 ;; Check if the footnote tag is defined but missing. In this
530 ;; case, insert it, before any footnote or one blank line
531 ;; after any previous text.
532 (when (and tag
(not (re-search-backward tag nil t
)))
533 (skip-chars-backward " \t\r\n")
534 (while (re-search-backward org-footnote-definition-re nil t
))
535 (unless (bolp) (newline 2))
536 (insert org-footnote-tag-for-non-org-mode-files
"\n\n"))
537 ;; Remove superfluous white space and clear marker.
539 (skip-chars-backward " \t\r\n")
540 (delete-region (point) max
)
541 (unless (bolp) (newline))
542 (set-marker max nil
))))
543 ;; Insert footnote label.
544 (insert "\n[" label
"] ")
545 ;; Only notify user about next possible action when in an Org
546 ;; buffer, as the bindings may have different meanings otherwise.
547 (when (eq major-mode
'org-mode
)
549 "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
552 (defun org-footnote-action (&optional special
)
553 "Do the right thing for footnotes.
555 When at a footnote reference, jump to the definition.
557 When at a definition, jump to the references if they exist, offer
558 to create them otherwise.
560 When neither at definition or reference, create a new footnote,
563 With prefix arg SPECIAL, offer additional commands in a menu."
568 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
569 (setq c
(read-char-exclusive))
571 ((eq c ?s
) (org-footnote-normalize 'sort
))
572 ((eq c ?r
) (org-footnote-renumber-fn:N
))
574 (org-footnote-renumber-fn:N
)
575 (org-footnote-normalize 'sort
))
576 ((eq c ?n
) (org-footnote-normalize))
577 ((eq c ?d
) (org-footnote-delete))
578 (t (error "No such footnote command %c" c
))))
579 ((setq tmp
(org-footnote-at-reference-p))
581 ;; Anonymous footnote: move point at the beginning of its
584 (goto-char (nth 1 tmp
))
586 ;; A definition exists: move to it.
587 ((ignore-errors (org-footnote-goto-definition (car tmp
))))
588 ;; No definition exists: offer to create it.
589 ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp
)))
590 (org-footnote-create-definition (car tmp
)))))
591 ((setq tmp
(org-footnote-at-definition-p))
592 (org-footnote-goto-previous-reference (car tmp
)))
593 (t (org-footnote-new)))))
595 (defvar org-footnote-insert-pos-for-preprocessor
'point-max
596 "See `org-footnote-normalize'.")
598 (defvar org-export-footnotes-seen nil
) ; silence byte-compiler
599 (defvar org-export-footnotes-data nil
) ; silence byte-compiler
602 (defun org-footnote-normalize (&optional sort-only export-props
)
603 "Collect the footnotes in various formats and normalize them.
605 This finds the different sorts of footnotes allowed in Org, and
606 normalizes them to the usual [N] format that is understood by the
609 When SORT-ONLY is set, only sort the footnote definitions into the
612 If Org is amidst an export process, EXPORT-PROPS will hold the
613 export properties of the buffer.
615 When EXPORT-PROPS is non-nil, the default action is to insert
616 normalized footnotes towards the end of the pre-processing
617 buffer. Some exporters (docbook, odt...) expect footnote
618 definitions to be available before any references to them. Such
619 exporters can let bind `org-footnote-insert-pos-for-preprocessor'
620 to symbol `point-min' to achieve the desired behaviour.
622 Additional note on `org-footnote-insert-pos-for-preprocessor':
623 1. This variable has not effect when FOR-PREPROCESSOR is nil.
624 2. This variable (potentially) obviates the need for extra scan
625 of pre-processor buffer as witnessed in
626 `org-export-docbook-get-footnotes'."
627 ;; This is based on Paul's function, but rewritten.
629 ;; Re-create `org-with-limited-levels', but not limited to Org
632 (and (boundp 'org-inlinetask-min-level
)
633 org-inlinetask-min-level
634 (1- org-inlinetask-min-level
)))
635 (nstars (and limit-level
636 (if org-odd-levels-only
637 (and limit-level
(1- (* limit-level
2)))
640 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ ")))
641 ;; Determine the highest marker used so far.
642 (ref-table (when export-props org-export-footnotes-seen
))
643 (count (if (and export-props ref-table
)
644 (apply 'max
(mapcar (lambda (e) (nth 1 e
)) ref-table
))
648 ;; 1. Find every footnote reference, extract the definition, and
649 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
650 ;; normalize references.
651 (goto-char (point-min))
652 (while (setq ref
(org-footnote-get-next-reference))
653 (let* ((lbl (car ref
))
654 ;; When footnote isn't anonymous, check if it's label
655 ;; (REF) is already stored in REF-TABLE. In that case,
656 ;; extract number used to identify it (MARKER). If
657 ;; footnote is unknown, increment the global counter
658 ;; (COUNT) to create an unused identifier.
659 (a (and lbl
(assoc lbl ref-table
)))
660 (marker (or (nth 1 a
) (incf count
)))
661 ;; Is the reference inline or pointing to an inline
663 (inlinep (or (stringp (nth 3 ref
)) (nth 3 a
))))
664 ;; Replace footnote reference with [MARKER]. Maybe fill
665 ;; paragraph once done. If SORT-ONLY is non-nil, only move
666 ;; to the end of reference found to avoid matching it twice.
667 ;; If EXPORT-PROPS isn't nil, also add `org-footnote'
668 ;; property to it, so it can be easily recognized by
671 (goto-char (nth 2 ref
))
672 (delete-region (nth 1 ref
) (nth 2 ref
))
673 (goto-char (nth 1 ref
))
674 (let ((new-ref (format "[%d]" marker
)))
675 (when export-props
(org-add-props new-ref
'(org-footnote t
)))
678 org-footnote-fill-after-inline-note-extraction
679 (org-fill-paragraph)))
680 ;; Add label (REF), identifier (MARKER), definition (DEF)
681 ;; and type (INLINEP) to REF-TABLE if data was unknown.
683 (let ((def (or (nth 3 ref
) ; inline
685 (cdr (assoc lbl org-export-footnotes-data
)))
686 (nth 3 (org-footnote-get-definition lbl
)))))
687 (push (list lbl marker
688 ;; When exporting, each definition goes
689 ;; through `org-export-preprocess-string' so
690 ;; it is ready to insert in the
691 ;; backend-specific buffer.
692 (if (and export-props def
)
696 '(:todo-keywords t
:tags t
:priority t
))))
697 (org-export-preprocess-string def parameters
))
699 inlinep
) ref-table
)))))
700 ;; 2. Find and remove the footnote section, if any. Also
701 ;; determine where footnotes shall be inserted (INS-POINT).
702 (goto-char (point-min))
704 ((and org-footnote-section
705 (eq major-mode
'org-mode
)
707 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section
)
710 (delete-region (match-beginning 0) (org-end-of-subtree t
)))
711 ((eq major-mode
'org-mode
)
712 (goto-char (point-max))
713 (unless (bolp) (newline)))
715 ;; Remove any left-over tag in the buffer, if one is set up.
716 (when org-footnote-tag-for-non-org-mode-files
717 (let ((tag (concat "^" (regexp-quote
718 org-footnote-tag-for-non-org-mode-files
)
720 (while (re-search-forward tag nil t
)
722 (delete-region (point) (progn (forward-line) (point))))))
723 ;; In Message mode, ensure footnotes are inserted before the
725 (if (and (derived-mode-p 'message-mode
)
726 (goto-char (point-max))
727 (re-search-backward message-signature-separator nil t
))
729 (goto-char (point-max)))))
730 ;; During export, `org-footnote-insert-pos-for-preprocessor' has
731 ;; precedence over previously found position.
734 (if (and export-props
735 (eq org-footnote-insert-pos-for-preprocessor
'point-min
))
738 ;; 3. Clean-up REF-TABLE.
744 ;; When only sorting, ignore inline footnotes.
745 ((and sort-only
(nth 3 x
)) nil
)
746 ;; No definition available: provide one.
748 (append (butlast x
2)
749 (list (format "DEFINITION NOT FOUND: %s" (car x
))
753 (setq ref-table
(nreverse ref-table
))
754 ;; 4. Remove left-over definitions in the buffer.
755 (mapc (lambda (x) (unless (nth 3 x
)
756 (org-footnote-delete-definitions (car x
))))
758 ;; 5. Insert the footnotes again in the buffer, at the
760 (goto-char ins-point
)
762 ;; No footnote: exit.
764 ;; Cases when footnotes should be inserted in one place.
765 ((or (not (eq major-mode
'org-mode
))
768 ;; Insert again the section title, if any. Ensure that title,
769 ;; or the subsequent footnotes, will be separated by a blank
770 ;; lines from the rest of the document. In an Org buffer,
771 ;; separate section with a blank line, unless explicitly
772 ;; stated in `org-blank-before-new-entry'.
774 ((not (eq major-mode
'org-mode
))
775 (skip-chars-backward " \t\n\r")
776 (delete-region (point) ins-point
)
777 (unless (bolp) (newline))
778 ;; Keep one blank line between footnotes and signature.
779 (when (and (derived-mode-p 'message-mode
)
781 (re-search-forward message-signature-separator nil t
)))
783 (when org-footnote-tag-for-non-org-mode-files
784 (insert "\n" org-footnote-tag-for-non-org-mode-files
"\n")))
785 ((and org-footnote-section
(not export-props
))
786 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
787 (zerop (save-excursion (org-back-over-empty-lines))))
789 (insert "* " org-footnote-section
"\n")))
790 (set-marker ins-point nil
)
791 ;; Insert the footnotes, separated by a blank line.
792 (insert (mapconcat (lambda (x) (format "\n[%s] %s"
793 (nth (if sort-only
0 1) x
) (nth 2 x
)))
795 (unless (eobp) (insert "\n"))
796 ;; When exporting, add newly inserted markers along with their
797 ;; associated definition to `org-export-footnotes-seen'.
799 (setq org-export-footnotes-seen ref-table
)))
800 ;; Else, insert each definition at the end of the section
801 ;; containing their first reference. Happens only in Org files
802 ;; with no special footnote section, and only when doing
804 (t (mapc 'org-insert-footnote-reference-near-definition
807 (defun org-insert-footnote-reference-near-definition (entry)
808 "Find first reference of footnote ENTRY and insert the definition there.
809 ENTRY is (fn-label num-mark definition)."
811 (goto-char (point-min))
812 (let ((ref (org-footnote-get-next-reference (car entry
))))
814 (goto-char (nth 2 ref
))
815 (org-footnote-goto-local-insertion-point)
816 (insert (format "\n[%s] %s\n" (car entry
) (nth 2 entry
)))))))
818 (defun org-footnote-goto-local-insertion-point ()
819 "Find insertion point for footnote, just before next outline heading."
820 (org-with-limited-levels (outline-next-heading))
821 (or (bolp) (newline))
822 (beginning-of-line 0)
823 (while (and (not (bobp)) (= (char-after) ?
#))
824 (beginning-of-line 0))
825 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
827 (skip-chars-backward "\n\r\t ")
830 (defun org-footnote-delete-references (label)
831 "Delete every reference to footnote LABEL.
832 Return the number of footnotes removed."
834 (goto-char (point-min))
836 (while (setq ref
(org-footnote-get-next-reference label
))
837 (goto-char (nth 1 ref
))
838 (delete-region (nth 1 ref
) (nth 2 ref
))
842 (defun org-footnote-delete-definitions (label)
843 "Delete every definition of the footnote LABEL.
844 Return the number of footnotes removed."
846 (goto-char (point-min))
847 (let ((def-re (concat "^\\[" (regexp-quote label
) "\\]"))
849 (while (re-search-forward def-re nil t
)
850 (let ((full-def (org-footnote-at-definition-p)))
851 (delete-region (nth 1 full-def
) (nth 2 full-def
)))
855 (defun org-footnote-delete (&optional label
)
856 "Delete the footnote at point.
857 This will remove the definition (even multiple definitions if they exist)
858 and all references of a footnote label.
860 If LABEL is non-nil, delete that footnote instead."
862 (let* ((nref 0) (ndef 0) x
863 ;; 1. Determine LABEL of footnote at point.
865 ;; LABEL is provided as argument.
867 ;; Footnote reference at point. If the footnote is
868 ;; anonymous, delete it and exit instead.
869 ((setq x
(org-footnote-at-reference-p))
872 (delete-region (nth 1 x
) (nth 2 x
))
873 (message "Anonymous footnote removed")
875 ;; Footnote definition at point.
876 ((setq x
(org-footnote-at-definition-p))
878 (t (error "Don't know which footnote to remove")))))
879 ;; 2. Now that LABEL is non-nil, find every reference and every
880 ;; definition, and delete them.
881 (setq nref
(org-footnote-delete-references label
)
882 ndef
(org-footnote-delete-definitions label
))
883 ;; 3. Verify consistency of footnotes and notify user.
884 (org-footnote-auto-adjust-maybe)
885 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
888 (defun org-footnote-renumber-fn:N
()
889 "Renumber the simple footnotes like fn:17 into a sequence in the document."
892 (org-with-wide-buffer
893 (goto-char (point-min))
894 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t
)
896 (goto-char (match-beginning 0))
897 ;; Ensure match is a footnote reference or definition.
898 (when (save-match-data (if (bolp)
899 (org-footnote-at-definition-p)
900 (org-footnote-at-reference-p)))
901 (let ((new-val (or (cdr (assoc (match-string 1) map
))
902 (number-to-string (incf n
)))))
903 (unless (assoc (match-string 1) map
)
904 (push (cons (match-string 1) new-val
) map
))
905 (replace-match new-val nil nil nil
1))))))))
907 (defun org-footnote-auto-adjust-maybe ()
908 "Renumber and/or sort footnotes according to user settings."
909 (when (memq org-footnote-auto-adjust
'(t renumber
))
910 (org-footnote-renumber-fn:N
))
911 (when (memq org-footnote-auto-adjust
'(t sort
))
912 (let ((label (car (org-footnote-at-definition-p))))
913 (org-footnote-normalize 'sort
)
915 (goto-char (point-min))
916 (and (re-search-forward (concat "^\\[" (regexp-quote label
) "\\]")
919 (just-one-space)))))))
921 (provide 'org-footnote
)
923 ;;; org-footnote.el ends here