1 ;;; org-footnote.el --- Footnote support in Org and elsewhere
3 ;; Copyright (C) 2009-2015 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-element-context
"org-element" (&optional element
))
45 (declare-function org-element-property
"org-element" (property element
))
46 (declare-function org-element-type
"org-element" (element))
47 (declare-function org-end-of-subtree
"org" (&optional invisible-ok to-heading
))
48 (declare-function org-fill-paragraph
"org" (&optional justify
))
49 (declare-function org-icompleting-read
"org" (&rest args
))
50 (declare-function org-id-uuid
"org-id" ())
51 (declare-function org-in-block-p
"org" (names))
52 (declare-function org-at-comment-p
"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 org-skip-whitespace
"org" ())
61 (declare-function outline-next-heading
"outline")
62 (declare-function org-skip-whitespace
"org" ())
64 (defvar org-outline-regexp-bol
) ; defined in org.el
65 (defvar org-odd-levels-only
) ; defined in org.el
66 (defvar org-bracket-link-regexp
) ; defined in org.el
67 (defvar message-cite-prefix-regexp
) ; defined in message.el
68 (defvar message-signature-separator
) ; defined in message.el
70 (defconst org-footnote-re
71 ;; Only [1]-like footnotes are closed in this regexp, as footnotes
72 ;; from other types might contain square brackets (i.e. links) in
75 ;; `org-re' is used for regexp compatibility with XEmacs.
77 ;; Match inline footnotes.
78 (org-re "fn:\\([-_[:word:]]+\\)?:\\|")
79 ;; Match other footnotes.
80 "\\(?:\\([0-9]+\\)\\]\\)\\|"
81 (org-re "\\(fn:[-_[:word:]]+\\)")
83 "Regular expression for matching footnotes.")
85 (defconst org-footnote-definition-re
86 (org-re "^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
87 "Regular expression matching the definition of a footnote.")
89 (defconst org-footnote-forbidden-blocks
90 '("ascii" "beamer" "comment" "example" "html" "latex" "odt" "src")
91 "Names of blocks where footnotes are not allowed.")
93 (defgroup org-footnote nil
94 "Footnotes in Org-mode."
98 (defcustom org-footnote-section
"Footnotes"
99 "Outline heading containing footnote definitions.
101 This can be nil, to place footnotes locally at the end of the
102 current outline node. If can also be the name of a special
103 outline heading under which footnotes should be put.
105 This variable defines the place where Org puts the definition
106 automatically, i.e. when creating the footnote, and when sorting
107 the notes. However, by hand you may place definitions
110 If this is a string, during export, all subtrees starting with
111 this heading will be ignored.
113 If you don't use the customize interface to change this variable,
114 you will need to run the following command after the change:
116 \\[universal-argument] \\[org-element-cache-reset]"
118 :initialize
'custom-initialize-default
119 :set
(lambda (var val
)
121 (when (fboundp 'org-element-cache-reset
)
122 (org-element-cache-reset 'all
)))
124 (string :tag
"Collect footnotes under heading")
125 (const :tag
"Define footnotes locally" nil
)))
127 (defcustom org-footnote-tag-for-non-org-mode-files
"Footnotes:"
128 "Tag marking the beginning of footnote section.
129 The Org footnote engine can be used in arbitrary text files as well
130 as in Org-mode. Outside Org mode, new footnotes are always placed at
131 the end of the file. When you normalize the notes, any line containing
132 only this tag will be removed, a new one will be inserted at the end
133 of the file, followed by the collected and normalized footnotes.
135 If you don't want any tag in such buffers, set this variable to nil."
138 (string :tag
"Collect footnotes under tag")
139 (const :tag
"Don't use a tag" nil
)))
141 (defcustom org-footnote-define-inline nil
142 "Non-nil means define footnotes inline, at reference location.
143 When nil, footnotes will be defined in a special section near
144 the end of the document. When t, the [fn:label:definition] notation
145 will be used to define the footnote at the reference position."
149 (defcustom org-footnote-auto-label t
150 "Non-nil means define automatically new labels for footnotes.
153 nil Prompt the user for each label.
154 t Create unique labels of the form [fn:1], [fn:2], etc.
155 confirm Like t, but let the user edit the created value.
156 The label can be removed from the minibuffer to create
157 an anonymous footnote.
158 random Automatically generate a unique, random label.
159 plain Automatically create plain number labels like [1]."
162 (const :tag
"Prompt for label" nil
)
163 (const :tag
"Create automatic [fn:N]" t
)
164 (const :tag
"Offer automatic [fn:N] for editing" confirm
)
165 (const :tag
"Create a random label" random
)
166 (const :tag
"Create automatic [N]" plain
)))
168 (defcustom org-footnote-auto-adjust nil
169 "Non-nil means automatically adjust footnotes after insert/delete.
170 When this is t, after each insertion or deletion of a footnote,
171 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
172 If you want to have just sorting or just renumbering, set this variable
173 to `sort' or `renumber'.
175 The main values of this variable can be set with in-buffer options:
178 #+STARTUP: nofnadjust"
181 (const :tag
"No adjustment" nil
)
182 (const :tag
"Renumber" renumber
)
183 (const :tag
"Sort" sort
)
184 (const :tag
"Renumber and Sort" t
)))
186 (defcustom org-footnote-fill-after-inline-note-extraction nil
187 "Non-nil means fill paragraphs after extracting footnotes.
188 When extracting inline footnotes, the lengths of lines can change a lot.
189 When this option is set, paragraphs from which an inline footnote has been
190 extracted will be filled again."
194 (defun org-footnote-in-valid-context-p ()
195 "Is point in a context where footnotes are allowed?"
197 (not (or (org-at-comment-p)
198 (org-inside-LaTeX-fragment-p)
199 ;; Avoid literal example.
200 (org-in-verbatim-emphasis)
203 (looking-at "[ \t]*:[ \t]+"))
204 ;; Avoid cited text and headers in message-mode.
205 (and (derived-mode-p 'message-mode
)
208 (looking-at message-cite-prefix-regexp
))
209 (message-point-in-header-p)))
210 ;; Avoid forbidden blocks.
211 (org-in-block-p org-footnote-forbidden-blocks
)))))
213 (defun org-footnote-at-reference-p ()
214 "Is the cursor at a footnote reference?
216 If so, return a list containing its label, beginning and ending
217 positions, and the definition, when inlined."
218 (when (and (org-footnote-in-valid-context-p)
219 (or (looking-at org-footnote-re
)
220 (org-in-regexp org-footnote-re
)
221 (save-excursion (re-search-backward org-footnote-re nil t
)))
222 (/= (match-beginning 0) (point-at-bol)))
223 (let* ((beg (match-beginning 0))
224 (label (or (org-match-string-no-properties 2)
225 (org-match-string-no-properties 3)
226 ;; Anonymous footnotes don't have labels
227 (and (match-string 1)
228 (concat "fn:" (org-match-string-no-properties 1)))))
229 ;; Inline footnotes don't end at (match-end 0) as
230 ;; `org-footnote-re' stops just after the second colon.
231 ;; Find the real ending with `scan-sexps', so Org doesn't
232 ;; get fooled by unrelated closing square brackets.
233 (end (ignore-errors (scan-sexps beg
1))))
234 ;; Point is really at a reference if it's located before true
235 ;; ending of the footnote.
236 (when (and end
(< (point) end
)
237 ;; Verify match isn't a part of a link.
242 (org-in-regexp org-bracket-link-regexp
))))
243 (and linkp
(< (point) (cdr linkp
))))))
244 ;; Verify point doesn't belong to a LaTeX macro.
245 (not (org-inside-latex-macro-p)))
247 ;; Definition: ensure this is an inline footnote first.
248 (and (or (not label
) (match-string 1))
249 (org-trim (buffer-substring-no-properties
250 (match-end 0) (1- end
)))))))))
252 (defun org-footnote-at-definition-p ()
253 "Is point within a footnote definition?
255 This matches only pure definitions like [1] or [fn:name] at the
256 beginning of a line. It does not match references like
257 \[fn:name:definition], where the footnote text is included and
260 The return value will be nil if not at a footnote definition, and
261 a list with label, start, end and definition of the footnote
263 (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
266 ;; Footnotes definitions are separated by new headlines, another
267 ;; footnote definition or 2 blank lines.
268 (let ((lim (save-excursion
270 (concat org-outline-regexp-bol
271 "\\|^\\([ \t]*\n\\)\\{2,\\}") nil t
))))
272 (when (re-search-backward org-footnote-definition-re lim t
)
273 (let ((label (org-match-string-no-properties 1))
274 (beg (match-beginning 0))
275 (beg-def (match-end 0))
276 ;; In message-mode, do not search after signature.
277 (end (let ((bound (and (derived-mode-p 'message-mode
)
279 (goto-char (point-max))
281 message-signature-separator nil t
)))))
285 (concat org-outline-regexp-bol
"\\|"
286 org-footnote-definition-re
"\\|"
287 "^\\([ \t]*\n\\)\\{2,\\}") bound
'move
))
291 (org-trim (buffer-substring-no-properties beg-def end
)))))))))
293 (defun org-footnote-get-next-reference (&optional label backward limit
)
294 "Return complete reference of the next footnote.
296 If LABEL is provided, get the next reference of that footnote. If
297 BACKWARD is non-nil, find previous reference instead. LIMIT is
298 the buffer position bounding the search.
300 Return value is a list like those provided by `org-footnote-at-reference-p'.
301 If no footnote is found, return nil."
303 (let* ((label-fmt (if label
(format "\\[%s[]:]" label
) org-footnote-re
)))
306 (unless (funcall (if backward
#'re-search-backward
#'re-search-forward
)
309 (unless backward
(backward-char))
310 (let ((ref (org-footnote-at-reference-p)))
311 (when ref
(throw 'exit ref
))))))))
313 (defun org-footnote-next-reference-or-definition (limit)
314 "Move point to next footnote reference or definition.
316 LIMIT is the buffer position bounding the search.
318 Return value is a list like those provided by
319 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
320 If no footnote is found, return nil."
321 (let* (ref (origin (point)))
324 (unless (re-search-forward org-footnote-re limit t
)
327 ;; Beware: with [1]-like footnotes point will be just after
328 ;; the closing square bracket.
331 ((setq ref
(org-footnote-at-reference-p))
333 ;; Definition: also grab the last square bracket, only
334 ;; matched in `org-footnote-re' for [1]-like footnotes.
335 ((save-match-data (org-footnote-at-definition-p))
336 (let ((end (match-end 0)))
338 (list nil
(match-beginning 0)
339 (if (eq (char-before end
) 93) end
(1+ end
)))))))))))
341 (defun org-footnote-get-definition (label)
342 "Return label, boundaries and definition of the footnote LABEL."
343 (let* ((label (regexp-quote (org-footnote-normalize-label label
)))
344 (re (format "^\\[%s\\]\\|.\\[%s:" label label
)))
345 (org-with-wide-buffer
346 (goto-char (point-min))
348 (while (re-search-forward re nil t
)
349 (let* ((datum (progn (backward-char) (org-element-context)))
350 (type (org-element-type datum
)))
351 (when (memq type
'(footnote-definition footnote-reference
))
354 (org-element-property :begin datum
)
355 (org-element-property :end datum
)
356 (replace-regexp-in-string
359 (buffer-substring-no-properties
360 (org-element-property :contents-begin datum
)
361 (org-element-property :contents-end datum
))))))))
364 (defun org-footnote-goto-definition (label)
365 "Move point to the definition of the footnote LABEL.
366 Return a non-nil value when a definition has been found."
367 (interactive "sLabel: ")
368 (let ((def-start (nth 1 (org-footnote-get-definition label
))))
371 (user-error "Cannot find definition of footnote %s" label
))
372 ((or (> def-start
(point-max))
373 (< def-start
(point-min)))
374 (user-error "Footnote definition outside of narrowed part of buffer"))
377 (goto-char def-start
)
378 (looking-at (format "\\[%s[]:]" label
))
379 (goto-char (match-end 0))
380 (org-show-context 'link-search
)
381 (when (derived-mode-p 'org-mode
)
382 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))
385 (defun org-footnote-goto-previous-reference (label)
386 "Find the first closest (to point) reference of footnote with label LABEL."
387 (interactive "sLabel: ")
389 (let* ((label (org-footnote-normalize-label label
)) ref
)
391 (setq ref
(or (org-footnote-get-next-reference label t
)
392 (org-footnote-get-next-reference label
)
396 (org-footnote-get-next-reference label t
)
397 (org-footnote-get-next-reference label
))))))
399 (error "Cannot find reference of footnote %s" label
)
400 (goto-char (nth 1 ref
))
401 (org-show-context 'link-search
))))
403 (defun org-footnote-normalize-label (label)
404 "Return LABEL as an appropriate string."
406 ((numberp label
) (number-to-string label
))
407 ((equal "" label
) nil
)
408 ((not (string-match "^[0-9]+$\\|^fn:" label
))
409 (concat "fn:" label
))
412 (defun org-footnote-all-labels (&optional with-defs
)
413 "Return list with all defined foot labels used in the buffer.
415 If WITH-DEFS is non-nil, also associate the definition to each
416 label. The function will then return an alist whose key is label
417 and value definition."
421 ;; Depending on WITH-DEFS, store label or (label . def) of
422 ;; footnote reference/definition given as argument in RTN.
424 (let ((lbl (car el
)))
425 (push (if with-defs
(cons lbl
(nth 3 el
)) lbl
) rtn
))))))
429 ;; Find all labels found in definitions.
430 (goto-char (point-min))
432 (while (re-search-forward org-footnote-definition-re nil t
)
433 (when (setq def
(org-footnote-at-definition-p))
434 (funcall push-to-rtn def
))))
435 ;; Find all labels found in references.
436 (goto-char (point-min))
438 (while (setq ref
(org-footnote-get-next-reference))
439 (goto-char (nth 2 ref
))
440 (and (car ref
) ; ignore anonymous footnotes
441 (not (funcall (if with-defs
#'assoc
#'member
) (car ref
) rtn
))
442 (funcall push-to-rtn ref
))))))
445 (defun org-footnote-unique-label (&optional current
)
446 "Return a new unique footnote label.
448 The function returns the first \"fn:N\" or \"N\" label that is
451 Optional argument CURRENT is the list of labels active in the
453 (unless current
(setq current
(org-footnote-all-labels)))
454 (let ((fmt (if (eq org-footnote-auto-label
'plain
) "%d" "fn:%d"))
456 (while (member (format fmt cnt
) current
)
460 (defun org-footnote--allow-reference-p ()
461 "Non-nil when a footnote reference can be inserted at point."
462 ;; XXX: This is similar to `org-footnote-in-valid-context-p' but
463 ;; more accurate and usually faster, except in some corner cases.
464 ;; It may replace it after doing proper benchmarks as it would be
465 ;; used in fontification.
467 (let* ((context (org-element-context))
468 (type (org-element-type context
)))
470 ;; No footnote reference in attributes.
471 ((let ((post (org-element-property :post-affiliated context
)))
472 (and post
(< (point) post
)))
474 ;; Paragraphs and blank lines at top of document are fine.
475 ((memq type
'(nil paragraph
)))
476 ;; So are contents of verse blocks.
477 ((eq type
'verse-block
)
478 (and (>= (point) (org-element-property :contents-begin context
))
479 (< (point) (org-element-property :contents-end context
))))
480 ;; In an headline or inlinetask, point must be either on the
481 ;; heading itself or on the blank lines below.
482 ((memq type
'(headline inlinetask
))
483 (or (not (org-at-heading-p))
484 (and (save-excursion (beginning-of-line)
485 (and (let ((case-fold-search t
))
486 (not (looking-at "\\*+ END[ \t]*$")))
487 (looking-at org-complex-heading-regexp
)))
489 (>= (point) (match-beginning 4))
490 (or (not (match-beginning 5))
491 (< (point) (match-beginning 5))))))
492 ;; White spaces after an object or blank lines after an element
495 (save-excursion (goto-char (org-element-property :end context
))
496 (skip-chars-backward " \r\t\n")
497 (if (memq type org-element-all-objects
) (point)
498 (1+ (line-beginning-position 2))))))
499 ;; Other elements are invalid.
500 ((memq type org-element-all-elements
) nil
)
501 ;; Just before object is fine.
502 ((= (point) (org-element-property :begin context
)))
503 ;; Within recursive object too, but not in a link.
504 ((eq type
'link
) nil
)
505 ((let ((cbeg (org-element-property :contents-begin context
))
506 (cend (org-element-property :contents-end context
)))
507 (and cbeg
(>= (point) cbeg
) (<= (point) cend
))))))))
509 (defun org-footnote-new ()
510 "Insert a new footnote.
511 This command prompts for a label. If this is a label referencing an
512 existing label, only insert the label. If the footnote label is empty
513 or new, let the user edit the definition of the footnote."
515 (unless (org-footnote--allow-reference-p)
516 (user-error "Cannot insert a footnote here"))
517 (let* ((all (org-footnote-all-labels))
519 (org-footnote-normalize-label
520 (if (eq org-footnote-auto-label
'random
)
521 (format "fn:%x" (random #x100000000
))
522 (let ((propose (org-footnote-unique-label all
)))
523 (if (memq org-footnote-auto-label
'(t plain
)) propose
524 (org-icompleting-read
525 "Label (leave empty for anonymous): "
526 (mapcar #'list all
) nil nil
527 (and (eq org-footnote-auto-label
'confirm
) propose
))))))))
532 (insert "[" label
"]")
533 (message "New reference to existing note"))
534 (org-footnote-define-inline
535 (insert "[" label
": ]")
537 (org-footnote-auto-adjust-maybe))
539 (insert "[" label
"]")
540 (org-footnote-create-definition label
)
541 (org-footnote-auto-adjust-maybe)))))
543 (defvar org-blank-before-new-entry
) ; silence byte-compiler
544 (defun org-footnote-create-definition (label)
545 "Start the definition of a footnote with label LABEL."
546 (interactive "sLabel: ")
547 (let ((label (org-footnote-normalize-label label
))
548 electric-indent-mode
) ;; Prevent wrong indentation
551 ((derived-mode-p 'org-mode
)
552 ;; If `org-footnote-section' is defined, find it, or create it
553 ;; at the end of the buffer.
554 (when org-footnote-section
555 (goto-char (point-min))
556 (let ((re (concat "^\\*+[ \t]+" org-footnote-section
"[ \t]*$")))
557 (unless (or (re-search-forward re nil t
)
558 (and (progn (widen) t
)
559 (re-search-forward re nil t
)))
560 (goto-char (point-max))
561 (skip-chars-backward " \t\r\n")
562 (unless (bolp) (newline))
563 ;; Insert new section. Separate it from the previous one
564 ;; with a blank line, unless `org-blank-before-new-entry'
565 ;; explicitly says no.
566 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
567 (zerop (save-excursion (org-back-over-empty-lines))))
569 (insert "* " org-footnote-section
"\n"))))
570 ;; Move to the end of this entry (which may be
571 ;; `org-footnote-section' or the current one).
572 (org-footnote-goto-local-insertion-point)
573 (org-show-context 'link-search
))
575 ;; In a non-Org file. Search for footnote tag, or create it if
576 ;; specified (at the end of buffer, or before signature if in
577 ;; Message mode). Set point after any definition already there.
578 (let ((tag (and org-footnote-tag-for-non-org-mode-files
579 (concat "^" (regexp-quote
580 org-footnote-tag-for-non-org-mode-files
)
582 (max (if (and (derived-mode-p 'message-mode
)
583 (goto-char (point-max))
585 message-signature-separator nil t
))
587 ;; Ensure one blank line separates last
588 ;; footnote from signature.
592 (point-max-marker))))
593 (set-marker-insertion-type max t
)
595 ;; Check if the footnote tag is defined but missing. In this
596 ;; case, insert it, before any footnote or one blank line
597 ;; after any previous text.
598 (when (and tag
(not (re-search-backward tag nil t
)))
599 (skip-chars-backward " \t\r\n")
600 (while (re-search-backward org-footnote-definition-re nil t
))
601 (unless (bolp) (newline 2))
602 (insert org-footnote-tag-for-non-org-mode-files
"\n\n"))
603 ;; Remove superfluous white space and clear marker.
605 (skip-chars-backward " \t\r\n")
606 (delete-region (point) max
)
607 (unless (bolp) (newline))
608 (set-marker max nil
))))
609 ;; Insert footnote label.
610 (when (zerop (org-back-over-empty-lines)) (newline))
611 (insert "[" label
"] \n")
613 ;; Only notify user about next possible action when in an Org
614 ;; buffer, as the bindings may have different meanings otherwise.
615 (when (derived-mode-p 'org-mode
)
617 "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
620 (defun org-footnote-action (&optional special
)
621 "Do the right thing for footnotes.
623 When at a footnote reference, jump to the definition.
625 When at a definition, jump to the references if they exist, offer
626 to create them otherwise.
628 When neither at definition or reference, create a new footnote,
629 interactively if possible.
631 With prefix arg SPECIAL, or when no footnote can be created,
632 offer additional commands in a menu."
634 (let* ((context (and (not special
) (org-element-context)))
635 (type (org-element-type context
)))
637 ((eq type
'footnote-reference
)
638 (let ((label (org-element-property :label context
)))
640 ;; Anonymous footnote: move point at the beginning of its
643 (goto-char (org-element-property :contents-begin context
)))
644 ;; A definition exists: move to it.
645 ((ignore-errors (org-footnote-goto-definition label
)))
646 ;; No definition exists: offer to create it.
647 ((yes-or-no-p (format "No definition for %s. Create one? " label
))
648 (org-footnote-create-definition label
)))))
649 ((eq type
'footnote-definition
)
650 (org-footnote-goto-previous-reference
651 (org-element-property :label context
)))
653 (zerop (current-column))
654 (not (org-footnote-in-valid-context-p)))
655 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
656 (let ((c (read-char-exclusive)))
658 ((eq c ?s
) (org-footnote-normalize 'sort
))
659 ((eq c ?r
) (org-footnote-renumber-fn:N
))
661 (org-footnote-renumber-fn:N
)
662 (org-footnote-normalize 'sort
))
663 ((eq c ?n
) (org-footnote-normalize))
664 ((eq c ?d
) (org-footnote-delete))
665 (t (error "No such footnote command %c" c
)))))
666 (t (org-footnote-new)))))
669 (defun org-footnote-normalize (&optional sort-only
)
670 "Collect the footnotes in various formats and normalize them.
672 This finds the different sorts of footnotes allowed in Org, and
673 normalizes them to the usual [N] format.
675 When SORT-ONLY is set, only sort the footnote definitions into the
676 referenced sequence."
677 ;; This is based on Paul's function, but rewritten.
679 ;; Re-create `org-with-limited-levels', but not limited to Org
682 (and (boundp 'org-inlinetask-min-level
)
683 org-inlinetask-min-level
684 (1- org-inlinetask-min-level
)))
685 (nstars (and limit-level
686 (if org-odd-levels-only
(1- (* limit-level
2))
689 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ ")))
691 ins-point ref ref-table
)
693 ;; 1. Find every footnote reference, extract the definition, and
694 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
695 ;; normalize references.
696 (goto-char (point-min))
697 (while (setq ref
(org-footnote-get-next-reference))
698 (let* ((lbl (car ref
))
700 ;; When footnote isn't anonymous, check if it's label
701 ;; (REF) is already stored in REF-TABLE. In that case,
702 ;; extract number used to identify it (MARKER). If
703 ;; footnote is unknown, increment the global counter
704 ;; (COUNT) to create an unused identifier.
705 (a (and lbl
(assoc lbl ref-table
)))
706 (marker (or (nth 1 a
) (incf count
)))
707 ;; Is the reference inline or pointing to an inline
709 (inlinep (or (stringp (nth 3 ref
)) (nth 3 a
))))
710 ;; Replace footnote reference with [MARKER]. Maybe fill
711 ;; paragraph once done. If SORT-ONLY is non-nil, only move
712 ;; to the end of reference found to avoid matching it twice.
713 (if sort-only
(goto-char (nth 2 ref
))
714 (delete-region (nth 1 ref
) (nth 2 ref
))
715 (goto-char (nth 1 ref
))
716 (insert (format "[%d]" marker
))
718 org-footnote-fill-after-inline-note-extraction
719 (org-fill-paragraph)))
720 ;; Add label (REF), identifier (MARKER), definition (DEF)
721 ;; type (INLINEP) and position (POS) to REF-TABLE if data
724 (let ((def (or (nth 3 ref
) ; Inline definition.
725 (nth 3 (org-footnote-get-definition lbl
)))))
726 (push (list lbl marker def
727 ;; Reference beginning position is a marker
728 ;; to preserve it during further buffer
730 inlinep
(copy-marker pos
)) ref-table
)))))
731 ;; 2. Find and remove the footnote section, if any. Also
732 ;; determine where footnotes shall be inserted (INS-POINT).
734 ((and org-footnote-section
(derived-mode-p 'org-mode
))
735 (goto-char (point-min))
736 (if (re-search-forward
737 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section
)
739 (delete-region (match-beginning 0) (org-end-of-subtree t t
)))
740 ;; A new footnote section is inserted by default at the end of
742 (goto-char (point-max))
743 (skip-chars-backward " \r\t\n")
745 (unless (bolp) (newline)))
746 ;; No footnote section set: Footnotes will be added at the end
747 ;; of the section containing their first reference.
748 ((derived-mode-p 'org-mode
))
750 ;; Remove any left-over tag in the buffer, if one is set up.
751 (when org-footnote-tag-for-non-org-mode-files
752 (let ((tag (concat "^" (regexp-quote
753 org-footnote-tag-for-non-org-mode-files
)
755 (goto-char (point-min))
756 (while (re-search-forward tag nil t
)
758 (delete-region (point) (progn (forward-line) (point))))))
759 ;; In Message mode, ensure footnotes are inserted before the
761 (if (and (derived-mode-p 'message-mode
)
762 (goto-char (point-max))
763 (re-search-backward message-signature-separator nil t
))
765 (goto-char (point-max)))))
766 (setq ins-point
(point-marker))
767 ;; 3. Clean-up REF-TABLE.
773 ;; When only sorting, ignore inline footnotes.
774 ;; Also clear position marker.
775 ((and sort-only
(nth 3 x
))
776 (set-marker (nth 4 x
) nil
) nil
)
777 ;; No definition available: provide one.
780 (list (car x
) (nth 1 x
)
781 (format "DEFINITION NOT FOUND: %s" (car x
)))
785 (setq ref-table
(nreverse ref-table
))
786 ;; 4. Remove left-over definitions in the buffer.
788 (unless (nth 3 x
) (org-footnote-delete-definitions (car x
))))
790 ;; 5. Insert the footnotes again in the buffer, at the
792 (goto-char ins-point
)
794 ;; No footnote: exit.
796 ;; Cases when footnotes should be inserted in one place.
797 ((or (not (derived-mode-p 'org-mode
)) org-footnote-section
)
798 ;; Insert again the section title, if any. Ensure that title,
799 ;; or the subsequent footnotes, will be separated by a blank
800 ;; lines from the rest of the document. In an Org buffer,
801 ;; separate section with a blank line, unless explicitly
802 ;; stated in `org-blank-before-new-entry'.
803 (if (not (derived-mode-p 'org-mode
))
804 (progn (skip-chars-backward " \t\n\r")
805 (delete-region (point) ins-point
)
806 (unless (bolp) (newline))
807 (when org-footnote-tag-for-non-org-mode-files
808 (insert "\n" org-footnote-tag-for-non-org-mode-files
"\n")))
809 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
810 (zerop (save-excursion (org-back-over-empty-lines))))
812 (insert "* " org-footnote-section
"\n"))
813 (set-marker ins-point nil
)
814 ;; Insert the footnotes, separated by a blank line.
819 (set-marker (nth 4 x
) nil
)
820 (format "\n[%s] %s" (nth (if sort-only
0 1) x
) (nth 2 x
)))
822 (unless (eobp) (insert "\n\n")))
823 ;; Each footnote definition has to be inserted at the end of
824 ;; the section where its first reference belongs.
828 (let ((pos (nth 4 x
)))
831 (set-marker pos nil
))
832 (org-footnote-goto-local-insertion-point)
833 (insert (format "\n[%s] %s\n"
834 (if sort-only
(car x
) (nth 1 x
))
838 (defun org-footnote-goto-local-insertion-point ()
839 "Find insertion point for footnote, just before next outline heading."
840 (org-with-limited-levels (outline-next-heading))
841 (or (bolp) (newline))
842 (beginning-of-line 0)
843 (while (and (not (bobp)) (= (char-after) ?
#))
844 (beginning-of-line 0))
845 (if (let ((case-fold-search t
)) (looking-at "[ \t]*#\\+tblfm:")) (beginning-of-line 2))
847 (skip-chars-backward "\n\r\t ")
850 (defun org-footnote-delete-references (label)
851 "Delete every reference to footnote LABEL.
852 Return the number of footnotes removed."
854 (goto-char (point-min))
856 (while (setq ref
(org-footnote-get-next-reference label
))
857 (goto-char (nth 1 ref
))
858 (delete-region (nth 1 ref
) (nth 2 ref
))
862 (defun org-footnote-delete-definitions (label)
863 "Delete every definition of the footnote LABEL.
864 Return the number of footnotes removed."
866 (goto-char (point-min))
867 (let ((def-re (concat "^\\[" (regexp-quote label
) "\\]"))
869 (while (re-search-forward def-re nil t
)
870 (let ((full-def (org-footnote-at-definition-p)))
872 ;; Remove the footnote, and all blank lines before it.
873 (goto-char (nth 1 full-def
))
874 (skip-chars-backward " \r\t\n")
875 (unless (bolp) (forward-line))
876 (delete-region (point) (nth 2 full-def
))
880 (defun org-footnote-delete (&optional label
)
881 "Delete the footnote at point.
882 This will remove the definition (even multiple definitions if they exist)
883 and all references of a footnote label.
885 If LABEL is non-nil, delete that footnote instead."
887 (let* ((nref 0) (ndef 0) x
888 ;; 1. Determine LABEL of footnote at point.
890 ;; LABEL is provided as argument.
892 ;; Footnote reference at point. If the footnote is
893 ;; anonymous, delete it and exit instead.
894 ((setq x
(org-footnote-at-reference-p))
897 (delete-region (nth 1 x
) (nth 2 x
))
898 (message "Anonymous footnote removed")
900 ;; Footnote definition at point.
901 ((setq x
(org-footnote-at-definition-p))
903 (t (error "Don't know which footnote to remove")))))
904 ;; 2. Now that LABEL is non-nil, find every reference and every
905 ;; definition, and delete them.
906 (setq nref
(org-footnote-delete-references label
)
907 ndef
(org-footnote-delete-definitions label
))
908 ;; 3. Verify consistency of footnotes and notify user.
909 (org-footnote-auto-adjust-maybe)
910 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
913 (defun org-footnote-renumber-fn:N
()
914 "Renumber the simple footnotes like fn:17 into a sequence in the document."
917 (org-with-wide-buffer
918 (goto-char (point-min))
919 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t
)
921 (goto-char (match-beginning 0))
922 ;; Ensure match is a footnote reference or definition.
923 (when (save-match-data (if (bolp)
924 (org-footnote-at-definition-p)
925 (org-footnote-at-reference-p)))
926 (let ((new-val (or (cdr (assoc (match-string 1) map
))
927 (number-to-string (incf n
)))))
928 (unless (assoc (match-string 1) map
)
929 (push (cons (match-string 1) new-val
) map
))
930 (replace-match new-val nil nil nil
1))))))))
932 (defun org-footnote-auto-adjust-maybe ()
933 "Renumber and/or sort footnotes according to user settings."
934 (when (memq org-footnote-auto-adjust
'(t renumber
))
935 (org-footnote-renumber-fn:N
))
936 (when (memq org-footnote-auto-adjust
'(t sort
))
937 (let ((label (car (org-footnote-at-definition-p))))
938 (org-footnote-normalize 'sort
)
940 (goto-char (point-min))
941 (and (re-search-forward (concat "^\\[" (regexp-quote label
) "\\]")
944 (just-one-space)))))))
946 (provide 'org-footnote
)
949 ;; generated-autoload-file: "org-loaddefs.el"
952 ;;; org-footnote.el ends here