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-at-comment-p
"org" ())
42 (declare-function org-at-heading-p
"org" (&optional ignored
))
43 (declare-function org-back-over-empty-lines
"org" ())
44 (declare-function org-back-to-heading
"org" (&optional invisible-ok
))
45 (declare-function org-combine-plists
"org" (&rest plists
))
46 (declare-function org-edit-footnote-reference
"org-src" ())
47 (declare-function org-element-context
"org-element" (&optional element
))
48 (declare-function org-element-property
"org-element" (property element
))
49 (declare-function org-element-type
"org-element" (element))
50 (declare-function org-end-of-subtree
"org" (&optional invisible-ok to-heading
))
51 (declare-function org-fill-paragraph
"org" (&optional justify
))
52 (declare-function org-icompleting-read
"org" (&rest args
))
53 (declare-function org-id-uuid
"org-id" ())
54 (declare-function org-in-block-p
"org" (names))
55 (declare-function org-in-regexp
"org" (re &optional nlines visually
))
56 (declare-function org-in-verbatim-emphasis
"org" ())
57 (declare-function org-inside-LaTeX-fragment-p
"org" ())
58 (declare-function org-inside-latex-macro-p
"org" ())
59 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
60 (declare-function org-show-context
"org" (&optional key
))
61 (declare-function org-skip-whitespace
"org" ())
62 (declare-function org-skip-whitespace
"org" ())
63 (declare-function org-trim
"org" (s))
64 (declare-function outline-next-heading
"outline")
66 (defvar message-cite-prefix-regexp
) ; defined in message.el
67 (defvar message-signature-separator
) ; defined in message.el
68 (defvar org-bracket-link-regexp
) ; defined in org.el
69 (defvar org-complex-heading-regexp
) ; defined in org.el
70 (defvar org-element-all-elements
) ; defined in org-element.el
71 (defvar org-element-all-objects
) ; defined in org-element.el
72 (defvar org-odd-levels-only
) ; defined in org.el
73 (defvar org-outline-regexp-bol
) ; defined in org.el
75 (defconst org-footnote-re
76 ;; Only [1]-like footnotes are closed in this regexp, as footnotes
77 ;; from other types might contain square brackets (i.e. links) in
80 ;; `org-re' is used for regexp compatibility with XEmacs.
82 ;; Match inline footnotes.
83 (org-re "fn:\\([-_[:word:]]+\\)?:\\|")
84 ;; Match other footnotes.
85 "\\(?:\\([0-9]+\\)\\]\\)\\|"
86 (org-re "\\(fn:[-_[:word:]]+\\)")
88 "Regular expression for matching footnotes.")
90 (defconst org-footnote-definition-re
91 (org-re "^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
92 "Regular expression matching the definition of a footnote.")
94 (defconst org-footnote-forbidden-blocks
95 '("ascii" "beamer" "comment" "example" "html" "latex" "odt" "src")
96 "Names of blocks where footnotes are not allowed.")
98 (defgroup org-footnote nil
99 "Footnotes in Org-mode."
103 (defcustom org-footnote-section
"Footnotes"
104 "Outline heading containing footnote definitions.
106 This can be nil, to place footnotes locally at the end of the
107 current outline node. If can also be the name of a special
108 outline heading under which footnotes should be put.
110 This variable defines the place where Org puts the definition
111 automatically, i.e. when creating the footnote, and when sorting
112 the notes. However, by hand you may place definitions
115 If this is a string, during export, all subtrees starting with
116 this heading will be ignored.
118 If you don't use the customize interface to change this variable,
119 you will need to run the following command after the change:
121 \\[universal-argument] \\[org-element-cache-reset]"
123 :initialize
'custom-initialize-default
124 :set
(lambda (var val
)
126 (when (fboundp 'org-element-cache-reset
)
127 (org-element-cache-reset 'all
)))
129 (string :tag
"Collect footnotes under heading")
130 (const :tag
"Define footnotes locally" nil
)))
132 (defcustom org-footnote-tag-for-non-org-mode-files
"Footnotes:"
133 "Tag marking the beginning of footnote section.
134 The Org footnote engine can be used in arbitrary text files as well
135 as in Org-mode. Outside Org mode, new footnotes are always placed at
136 the end of the file. When you normalize the notes, any line containing
137 only this tag will be removed, a new one will be inserted at the end
138 of the file, followed by the collected and normalized footnotes.
140 If you don't want any tag in such buffers, set this variable to nil."
143 (string :tag
"Collect footnotes under tag")
144 (const :tag
"Don't use a tag" nil
)))
146 (defcustom org-footnote-define-inline nil
147 "Non-nil means define footnotes inline, at reference location.
148 When nil, footnotes will be defined in a special section near
149 the end of the document. When t, the [fn:label:definition] notation
150 will be used to define the footnote at the reference position."
154 (defcustom org-footnote-auto-label t
155 "Non-nil means define automatically new labels for footnotes.
158 nil Prompt the user for each label.
159 t Create unique labels of the form [fn:1], [fn:2], etc.
160 confirm Like t, but let the user edit the created value.
161 The label can be removed from the minibuffer to create
162 an anonymous footnote.
163 random Automatically generate a unique, random label.
164 plain Automatically create plain number labels like [1]."
167 (const :tag
"Prompt for label" nil
)
168 (const :tag
"Create automatic [fn:N]" t
)
169 (const :tag
"Offer automatic [fn:N] for editing" confirm
)
170 (const :tag
"Create a random label" random
)
171 (const :tag
"Create automatic [N]" plain
)))
173 (defcustom org-footnote-auto-adjust nil
174 "Non-nil means automatically adjust footnotes after insert/delete.
175 When this is t, after each insertion or deletion of a footnote,
176 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
177 If you want to have just sorting or just renumbering, set this variable
178 to `sort' or `renumber'.
180 The main values of this variable can be set with in-buffer options:
183 #+STARTUP: nofnadjust"
186 (const :tag
"No adjustment" nil
)
187 (const :tag
"Renumber" renumber
)
188 (const :tag
"Sort" sort
)
189 (const :tag
"Renumber and Sort" t
)))
191 (defcustom org-footnote-fill-after-inline-note-extraction nil
192 "Non-nil means fill paragraphs after extracting footnotes.
193 When extracting inline footnotes, the lengths of lines can change a lot.
194 When this option is set, paragraphs from which an inline footnote has been
195 extracted will be filled again."
199 (defun org-footnote-in-valid-context-p ()
200 "Is point in a context where footnotes are allowed?"
202 (not (or (org-at-comment-p)
203 (org-inside-LaTeX-fragment-p)
204 ;; Avoid literal example.
205 (org-in-verbatim-emphasis)
208 (looking-at "[ \t]*:[ \t]+"))
209 ;; Avoid cited text and headers in message-mode.
210 (and (derived-mode-p 'message-mode
)
213 (looking-at message-cite-prefix-regexp
))
214 (message-point-in-header-p)))
215 ;; Avoid forbidden blocks.
216 (org-in-block-p org-footnote-forbidden-blocks
)))))
218 (defun org-footnote-at-reference-p ()
219 "Is the cursor at a footnote reference?
221 If so, return a list containing its label, beginning and ending
222 positions, and the definition, when inlined."
223 (when (and (org-footnote-in-valid-context-p)
224 (or (looking-at org-footnote-re
)
225 (org-in-regexp org-footnote-re
)
226 (save-excursion (re-search-backward org-footnote-re nil t
)))
227 (/= (match-beginning 0) (point-at-bol)))
228 (let* ((beg (match-beginning 0))
229 (label (or (org-match-string-no-properties 2)
230 (org-match-string-no-properties 3)
231 ;; Anonymous footnotes don't have labels
232 (and (match-string 1)
233 (concat "fn:" (org-match-string-no-properties 1)))))
234 ;; Inline footnotes don't end at (match-end 0) as
235 ;; `org-footnote-re' stops just after the second colon.
236 ;; Find the real ending with `scan-sexps', so Org doesn't
237 ;; get fooled by unrelated closing square brackets.
238 (end (ignore-errors (scan-sexps beg
1))))
239 ;; Point is really at a reference if it's located before true
240 ;; ending of the footnote.
241 (when (and end
(< (point) end
)
242 ;; Verify match isn't a part of a link.
247 (org-in-regexp org-bracket-link-regexp
))))
248 (and linkp
(< (point) (cdr linkp
))))))
249 ;; Verify point doesn't belong to a LaTeX macro.
250 (not (org-inside-latex-macro-p)))
252 ;; Definition: ensure this is an inline footnote first.
253 (and (or (not label
) (match-string 1))
254 (org-trim (buffer-substring-no-properties
255 (match-end 0) (1- end
)))))))))
257 (defun org-footnote-at-definition-p ()
258 "Is point within a footnote definition?
260 This matches only pure definitions like [1] or [fn:name] at the
261 beginning of a line. It does not match references like
262 \[fn:name:definition], where the footnote text is included and
265 The return value will be nil if not at a footnote definition, and
266 a list with label, start, end and definition of the footnote
268 (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
271 ;; Footnotes definitions are separated by new headlines, another
272 ;; footnote definition or 2 blank lines.
273 (let ((lim (save-excursion
275 (concat org-outline-regexp-bol
276 "\\|^\\([ \t]*\n\\)\\{2,\\}") nil t
))))
277 (when (re-search-backward org-footnote-definition-re lim t
)
278 (let ((label (org-match-string-no-properties 1))
279 (beg (match-beginning 0))
280 (beg-def (match-end 0))
281 ;; In message-mode, do not search after signature.
282 (end (let ((bound (and (derived-mode-p 'message-mode
)
284 (goto-char (point-max))
286 message-signature-separator nil t
)))))
290 (concat org-outline-regexp-bol
"\\|"
291 org-footnote-definition-re
"\\|"
292 "^\\([ \t]*\n\\)\\{2,\\}") bound
'move
))
296 (org-trim (buffer-substring-no-properties beg-def end
)))))))))
298 (defun org-footnote-get-next-reference (&optional label backward limit
)
299 "Return complete reference of the next footnote.
301 If LABEL is provided, get the next reference of that footnote. If
302 BACKWARD is non-nil, find previous reference instead. LIMIT is
303 the buffer position bounding the search.
305 Return value is a list like those provided by `org-footnote-at-reference-p'.
306 If no footnote is found, return nil."
308 (let* ((label-fmt (if label
(format "\\[%s[]:]" label
) org-footnote-re
)))
311 (unless (funcall (if backward
#'re-search-backward
#'re-search-forward
)
314 (unless backward
(backward-char))
315 (let ((ref (org-footnote-at-reference-p)))
316 (when ref
(throw 'exit ref
))))))))
318 (defun org-footnote-next-reference-or-definition (limit)
319 "Move point to next footnote reference or definition.
321 LIMIT is the buffer position bounding the search.
323 Return value is a list like those provided by
324 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
325 If no footnote is found, return nil."
326 (let* (ref (origin (point)))
329 (unless (re-search-forward org-footnote-re limit t
)
332 ;; Beware: with [1]-like footnotes point will be just after
333 ;; the closing square bracket.
336 ((setq ref
(org-footnote-at-reference-p))
338 ;; Definition: also grab the last square bracket, only
339 ;; matched in `org-footnote-re' for [1]-like footnotes.
340 ((save-match-data (org-footnote-at-definition-p))
341 (let ((end (match-end 0)))
343 (list nil
(match-beginning 0)
344 (if (eq (char-before end
) 93) end
(1+ end
)))))))))))
346 (defun org-footnote-get-definition (label)
347 "Return label, boundaries and definition of the footnote LABEL."
348 (let* ((label (regexp-quote (org-footnote-normalize-label label
)))
349 (re (format "^\\[%s\\]\\|.\\[%s:" label label
)))
350 (org-with-wide-buffer
351 (goto-char (point-min))
353 (while (re-search-forward re nil t
)
354 (let* ((datum (progn (backward-char) (org-element-context)))
355 (type (org-element-type datum
)))
356 (when (memq type
'(footnote-definition footnote-reference
))
360 (org-element-property :begin datum
)
361 (org-element-property :end datum
)
362 (let ((cbeg (org-element-property :contents-begin datum
)))
364 (replace-regexp-in-string
367 (buffer-substring-no-properties
369 (org-element-property :contents-end datum
))))))))))
372 (defun org-footnote-goto-definition (label &optional location
)
373 "Move point to the definition of the footnote LABEL.
375 LOCATION, when non-nil specifies the buffer position of the
378 Throw an error if there is no definition or if it cannot be
379 reached from current narrowed part of buffer. Return a non-nil
380 value if point was successfully moved."
381 (interactive "sLabel: ")
382 (let ((def-start (or location
(nth 1 (org-footnote-get-definition label
)))))
385 (user-error "Cannot find definition of footnote %s" label
))
386 ((or (> def-start
(point-max)) (< def-start
(point-min)))
387 (user-error "Definition is outside narrowed part of buffer")))
389 (goto-char def-start
)
390 (looking-at (format "\\[%s[]:] ?" label
))
391 (goto-char (match-end 0))
392 (org-show-context 'link-search
)
393 (when (derived-mode-p 'org-mode
)
395 (substitute-command-keys
396 "Edit definition and go back with `\\[org-mark-ring-goto]' or, if \
397 unique, with `\\[org-ctrl-c-ctrl-c]'.")))
400 (defun org-footnote-goto-previous-reference (label)
401 "Find the first closest (to point) reference of footnote with label LABEL."
402 (interactive "sLabel: ")
404 (let* ((label (org-footnote-normalize-label label
)) ref
)
406 (setq ref
(or (org-footnote-get-next-reference label t
)
407 (org-footnote-get-next-reference label
)
411 (org-footnote-get-next-reference label t
)
412 (org-footnote-get-next-reference label
))))))
414 (error "Cannot find reference of footnote %s" label
)
415 (goto-char (nth 1 ref
))
416 (org-show-context 'link-search
))))
418 (defun org-footnote-normalize-label (label)
419 "Return LABEL as an appropriate string."
421 ((numberp label
) (number-to-string label
))
422 ((equal "" label
) nil
)
423 ((not (string-match "^[0-9]+$\\|^fn:" label
))
424 (concat "fn:" label
))
427 (defun org-footnote-all-labels (&optional with-defs
)
428 "Return list with all defined foot labels used in the buffer.
430 If WITH-DEFS is non-nil, also associate the definition to each
431 label. The function will then return an alist whose key is label
432 and value definition."
436 ;; Depending on WITH-DEFS, store label or (label . def) of
437 ;; footnote reference/definition given as argument in RTN.
439 (let ((lbl (car el
)))
440 (push (if with-defs
(cons lbl
(nth 3 el
)) lbl
) rtn
))))))
444 ;; Find all labels found in definitions.
445 (goto-char (point-min))
447 (while (re-search-forward org-footnote-definition-re nil t
)
448 (when (setq def
(org-footnote-at-definition-p))
449 (funcall push-to-rtn def
))))
450 ;; Find all labels found in references.
451 (goto-char (point-min))
453 (while (setq ref
(org-footnote-get-next-reference))
454 (goto-char (nth 2 ref
))
455 (and (car ref
) ; ignore anonymous footnotes
456 (not (funcall (if with-defs
#'assoc
#'member
) (car ref
) rtn
))
457 (funcall push-to-rtn ref
))))))
460 (defun org-footnote-unique-label (&optional current
)
461 "Return a new unique footnote label.
463 The function returns the first \"fn:N\" or \"N\" label that is
466 Optional argument CURRENT is the list of labels active in the
468 (unless current
(setq current
(org-footnote-all-labels)))
469 (let ((fmt (if (eq org-footnote-auto-label
'plain
) "%d" "fn:%d"))
471 (while (member (format fmt cnt
) current
)
475 (defun org-footnote--allow-reference-p ()
476 "Non-nil when a footnote reference can be inserted at point."
477 ;; XXX: This is similar to `org-footnote-in-valid-context-p' but
478 ;; more accurate and usually faster, except in some corner cases.
479 ;; It may replace it after doing proper benchmarks as it would be
480 ;; used in fontification.
482 (let* ((context (org-element-context))
483 (type (org-element-type context
)))
485 ;; No footnote reference in attributes.
486 ((let ((post (org-element-property :post-affiliated context
)))
487 (and post
(< (point) post
)))
489 ;; Paragraphs and blank lines at top of document are fine.
490 ((memq type
'(nil paragraph
)))
491 ;; So are contents of verse blocks.
492 ((eq type
'verse-block
)
493 (and (>= (point) (org-element-property :contents-begin context
))
494 (< (point) (org-element-property :contents-end context
))))
495 ;; In an headline or inlinetask, point must be either on the
496 ;; heading itself or on the blank lines below.
497 ((memq type
'(headline inlinetask
))
498 (or (not (org-at-heading-p))
499 (and (save-excursion (beginning-of-line)
500 (and (let ((case-fold-search t
))
501 (not (looking-at "\\*+ END[ \t]*$")))
502 (looking-at org-complex-heading-regexp
)))
504 (>= (point) (match-beginning 4))
505 (or (not (match-beginning 5))
506 (< (point) (match-beginning 5))))))
507 ;; White spaces after an object or blank lines after an element
510 (save-excursion (goto-char (org-element-property :end context
))
511 (skip-chars-backward " \r\t\n")
512 (if (memq type org-element-all-objects
) (point)
513 (1+ (line-beginning-position 2))))))
514 ;; Other elements are invalid.
515 ((memq type org-element-all-elements
) nil
)
516 ;; Just before object is fine.
517 ((= (point) (org-element-property :begin context
)))
518 ;; Within recursive object too, but not in a link.
519 ((eq type
'link
) nil
)
520 ((let ((cbeg (org-element-property :contents-begin context
))
521 (cend (org-element-property :contents-end context
)))
522 (and cbeg
(>= (point) cbeg
) (<= (point) cend
))))))))
524 (defun org-footnote-new ()
525 "Insert a new footnote.
526 This command prompts for a label. If this is a label referencing an
527 existing label, only insert the label. If the footnote label is empty
528 or new, let the user edit the definition of the footnote."
530 (unless (org-footnote--allow-reference-p)
531 (user-error "Cannot insert a footnote here"))
532 (let* ((all (org-footnote-all-labels))
534 (org-footnote-normalize-label
535 (if (eq org-footnote-auto-label
'random
)
536 (format "fn:%x" (random #x100000000
))
537 (let ((propose (org-footnote-unique-label all
)))
538 (if (memq org-footnote-auto-label
'(t plain
)) propose
539 (org-icompleting-read
540 "Label (leave empty for anonymous): "
541 (mapcar #'list all
) nil nil
542 (and (eq org-footnote-auto-label
'confirm
) propose
))))))))
547 (insert "[" label
"]")
548 (message "New reference to existing note"))
549 (org-footnote-define-inline
550 (insert "[" label
":]")
552 (org-footnote-auto-adjust-maybe))
554 (insert "[" label
"]")
555 (let ((p (org-footnote-create-definition label
)))
556 ;; `org-footnote-goto-definition' needs to be called
557 ;; after `org-footnote-auto-adjust-maybe'. Otherwise
558 ;; both label and location of the definition are lost.
559 ;; On the contrary, it needs to be called before
560 ;; `org-edit-footnote-reference' so that the remote
561 ;; editing buffer can display the correct label.
562 (if (ignore-errors (org-footnote-goto-definition label p
))
563 (org-footnote-auto-adjust-maybe)
564 ;; Definition was created outside current scope: edit
566 (org-footnote-auto-adjust-maybe)
567 (org-edit-footnote-reference)))))))
569 (defvar org-blank-before-new-entry
) ; Silence byte-compiler.
570 (defun org-footnote-create-definition (label)
571 "Start the definition of a footnote with label LABEL.
572 Return buffer position at the beginning of the definition. In an
573 Org buffer, this function doesn't move point."
574 (let ((label (org-footnote-normalize-label label
))
575 electric-indent-mode
) ; Prevent wrong indentation.
577 ;; In an Org document.
578 ((derived-mode-p 'org-mode
)
579 ;; If `org-footnote-section' is defined, find it, or create it
580 ;; at the end of the buffer.
581 (org-with-wide-buffer
583 ((not org-footnote-section
)
584 (org-footnote--goto-local-insertion-point))
586 (goto-char (point-min))
588 (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section
) "[ \t]*$")
590 (goto-char (match-end 0))
592 (unless (bolp) (insert "\n")))
594 (goto-char (point-max))
595 (unless (bolp) (insert "\n"))
596 ;; Insert new section. Separate it from the previous one
597 ;; with a blank line, unless `org-blank-before-new-entry'
598 ;; explicitly says no.
599 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
600 (zerop (save-excursion (org-back-over-empty-lines))))
602 (insert "* " org-footnote-section
"\n")))
603 (when (zerop (org-back-over-empty-lines)) (insert "\n"))
604 (insert "[" label
"] \n")
605 (line-beginning-position 0)))
607 ;; In a non-Org file. Search for footnote tag, or create it if
608 ;; specified (at the end of buffer, or before signature if in
609 ;; Message mode). Set point after any definition already there.
610 (let ((tag (and org-footnote-tag-for-non-org-mode-files
611 (concat "^" (regexp-quote
612 org-footnote-tag-for-non-org-mode-files
)
614 (max (if (and (derived-mode-p 'message-mode
)
615 (goto-char (point-max))
617 message-signature-separator nil t
))
619 ;; Ensure one blank line separates last
620 ;; footnote from signature.
624 (point-max-marker))))
625 (set-marker-insertion-type max t
)
627 ;; Check if the footnote tag is defined but missing. In this
628 ;; case, insert it, before any footnote or one blank line
629 ;; after any previous text.
630 (when (and tag
(not (re-search-backward tag nil t
)))
631 (skip-chars-backward " \t\r\n")
632 (while (re-search-backward org-footnote-definition-re nil t
))
633 (unless (bolp) (newline 2))
634 (insert org-footnote-tag-for-non-org-mode-files
"\n\n"))
635 ;; Remove superfluous white space and clear marker.
637 (skip-chars-backward " \t\r\n")
638 (delete-region (point) max
)
639 (unless (bolp) (newline))
640 (set-marker max nil
))
641 (when (zerop (org-back-over-empty-lines)) (insert "\n"))
642 (insert "[" label
"] \n")
644 (line-beginning-position)))))
647 (defun org-footnote-action (&optional special
)
648 "Do the right thing for footnotes.
650 When at a footnote reference, jump to the definition.
652 When at a definition, jump to the references if they exist, offer
653 to create them otherwise.
655 When neither at definition or reference, create a new footnote,
656 interactively if possible.
658 With prefix arg SPECIAL, or when no footnote can be created,
659 offer additional commands in a menu."
661 (let* ((context (and (not special
) (org-element-context)))
662 (type (org-element-type context
)))
664 ;; On white space after element, insert a new footnote.
668 (goto-char (org-element-property :end context
))
669 (skip-chars-backward " \t")
672 ((eq type
'footnote-reference
)
673 (let ((label (org-element-property :label context
)))
675 ;; Anonymous footnote: move point at the beginning of its
678 (goto-char (org-element-property :contents-begin context
)))
679 ;; Check if a definition exists: then move to it.
680 ((let ((p (nth 1 (org-footnote-get-definition label
))))
681 (when p
(org-footnote-goto-definition label p
))))
682 ;; No definition exists: offer to create it.
683 ((yes-or-no-p (format "No definition for %s. Create one? " label
))
684 (let ((p (org-footnote-create-definition label
)))
685 (or (ignore-errors (org-footnote-goto-definition label p
))
686 ;; Since definition was created outside current scope,
688 (org-edit-footnote-reference)))))))
689 ((eq type
'footnote-definition
)
690 (org-footnote-goto-previous-reference
691 (org-element-property :label context
)))
692 ((or special
(not (org-footnote--allow-reference-p)))
693 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | \
694 ->[n]umeric | [d]elete")
695 (let ((c (read-char-exclusive)))
697 ((eq c ?s
) (org-footnote-normalize 'sort
))
698 ((eq c ?r
) (org-footnote-renumber-fn:N
))
700 (org-footnote-renumber-fn:N
)
701 (org-footnote-normalize 'sort
))
702 ((eq c ?n
) (org-footnote-normalize))
703 ((eq c ?d
) (org-footnote-delete))
704 (t (error "No such footnote command %c" c
)))))
705 (t (org-footnote-new)))))
708 (defun org-footnote-normalize (&optional sort-only
)
709 "Collect the footnotes in various formats and normalize them.
711 This finds the different sorts of footnotes allowed in Org, and
712 normalizes them to the usual [N] format.
714 When SORT-ONLY is set, only sort the footnote definitions into the
715 referenced sequence."
716 ;; This is based on Paul's function, but rewritten.
718 ;; Re-create `org-with-limited-levels', but not limited to Org
721 (and (boundp 'org-inlinetask-min-level
)
722 org-inlinetask-min-level
723 (1- org-inlinetask-min-level
)))
724 (nstars (and limit-level
725 (if org-odd-levels-only
(1- (* limit-level
2))
728 (concat "\\*" (if nstars
(format "\\{1,%d\\} " nstars
) "+ ")))
730 ins-point ref ref-table
)
731 (org-with-wide-buffer
732 ;; 1. Find every footnote reference, extract the definition, and
733 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
734 ;; normalize references.
735 (goto-char (point-min))
736 (while (setq ref
(org-footnote-get-next-reference))
737 (let* ((lbl (car ref
))
739 ;; When footnote isn't anonymous, check if it's label
740 ;; (REF) is already stored in REF-TABLE. In that case,
741 ;; extract number used to identify it (MARKER). If
742 ;; footnote is unknown, increment the global counter
743 ;; (COUNT) to create an unused identifier.
744 (a (and lbl
(assoc lbl ref-table
)))
745 (marker (or (nth 1 a
) (incf count
)))
746 ;; Is the reference inline or pointing to an inline
748 (inlinep (or (stringp (nth 3 ref
)) (nth 3 a
))))
749 ;; Replace footnote reference with [MARKER]. Maybe fill
750 ;; paragraph once done. If SORT-ONLY is non-nil, only move
751 ;; to the end of reference found to avoid matching it twice.
752 (if sort-only
(goto-char (nth 2 ref
))
753 (delete-region (nth 1 ref
) (nth 2 ref
))
754 (goto-char (nth 1 ref
))
755 (insert (format "[%d]" marker
))
757 org-footnote-fill-after-inline-note-extraction
758 (org-fill-paragraph)))
759 ;; Add label (REF), identifier (MARKER), definition (DEF)
760 ;; type (INLINEP) and position (POS) to REF-TABLE if data was
763 (let ((def (or (nth 3 ref
) ; Inline definition.
764 (nth 3 (org-footnote-get-definition lbl
)))))
765 (push (list lbl marker def
766 ;; Reference beginning position is a marker
767 ;; to preserve it during further buffer
769 inlinep
(copy-marker pos
)) ref-table
)))))
770 ;; 2. Find and remove the footnote section, if any. Also
771 ;; determine where footnotes shall be inserted (INS-POINT).
773 ((and org-footnote-section
(derived-mode-p 'org-mode
))
774 (goto-char (point-min))
775 (if (re-search-forward
776 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section
)
778 (delete-region (match-beginning 0) (org-end-of-subtree t t
)))
779 ;; A new footnote section is inserted by default at the end of
781 (goto-char (point-max))
782 (skip-chars-backward " \r\t\n")
784 (unless (bolp) (newline)))
785 ;; No footnote section set: Footnotes will be added at the end
786 ;; of the section containing their first reference.
787 ((derived-mode-p 'org-mode
))
789 ;; Remove any left-over tag in the buffer, if one is set up.
790 (when org-footnote-tag-for-non-org-mode-files
791 (let ((tag (concat "^" (regexp-quote
792 org-footnote-tag-for-non-org-mode-files
)
794 (goto-char (point-min))
795 (while (re-search-forward tag nil t
)
797 (delete-region (point) (progn (forward-line) (point))))))
798 ;; In Message mode, ensure footnotes are inserted before the
800 (if (and (derived-mode-p 'message-mode
)
801 (goto-char (point-max))
802 (re-search-backward message-signature-separator nil t
))
804 (goto-char (point-max)))))
805 (setq ins-point
(point-marker))
806 ;; 3. Clean-up REF-TABLE.
812 ;; When only sorting, ignore inline footnotes.
813 ;; Also clear position marker.
814 ((and sort-only
(nth 3 x
))
815 (set-marker (nth 4 x
) nil
) nil
)
816 ;; No definition available: provide one.
819 (list (car x
) (nth 1 x
)
820 (format "DEFINITION NOT FOUND: %s" (car x
)))
824 (setq ref-table
(nreverse ref-table
))
825 ;; 4. Remove left-over definitions in the buffer.
826 (dolist (x ref-table
)
827 (unless (nth 3 x
) (org-footnote-delete-definitions (car x
))))
828 ;; 5. Insert the footnotes again in the buffer, at the
830 (goto-char ins-point
)
832 ;; No footnote: exit.
834 ;; Cases when footnotes should be inserted in one place.
835 ((or (not (derived-mode-p 'org-mode
)) org-footnote-section
)
836 ;; Insert again the section title, if any. Ensure that title,
837 ;; or the subsequent footnotes, will be separated by a blank
838 ;; lines from the rest of the document. In an Org buffer,
839 ;; separate section with a blank line, unless explicitly stated
840 ;; in `org-blank-before-new-entry'.
841 (if (not (derived-mode-p 'org-mode
))
842 (progn (skip-chars-backward " \t\n\r")
843 (delete-region (point) ins-point
)
844 (unless (bolp) (newline))
845 (when org-footnote-tag-for-non-org-mode-files
846 (insert "\n" org-footnote-tag-for-non-org-mode-files
"\n")))
847 (when (and (cdr (assq 'heading org-blank-before-new-entry
))
848 (zerop (save-excursion (org-back-over-empty-lines))))
850 (insert "* " org-footnote-section
"\n"))
851 (set-marker ins-point nil
)
852 ;; Insert the footnotes, separated by a blank line.
857 (set-marker (nth 4 x
) nil
)
858 (format "\n[%s] %s" (nth (if sort-only
0 1) x
) (nth 2 x
)))
860 (unless (eobp) (insert "\n\n")))
861 ;; Each footnote definition has to be inserted at the end of the
862 ;; section where its first reference belongs.
864 (dolist (x ref-table
)
865 (let ((pos (nth 4 x
)))
868 (set-marker pos nil
))
869 (org-footnote--goto-local-insertion-point)
870 (insert (format "\n[%s] %s\n"
871 (nth (if sort-only
0 1) x
)
874 (defun org-footnote--goto-local-insertion-point ()
875 "Find insertion point for footnote, just before next outline heading.
876 Assume insertion point is within currently accessible part of the buffer."
877 (org-with-limited-levels (outline-next-heading))
878 ;; Skip file local variables. See `modify-file-local-variable'.
880 (let ((case-fold-search t
))
881 (re-search-backward "^[ \t]*# +Local Variables:"
882 (max (- (point-max) 3000) (point-min))
884 (skip-chars-backward " \t\n")
886 (unless (bolp) (insert "\n")))
888 (defun org-footnote-delete-references (label)
889 "Delete every reference to footnote LABEL.
890 Return the number of footnotes removed."
892 (goto-char (point-min))
894 (while (setq ref
(org-footnote-get-next-reference label
))
895 (goto-char (nth 1 ref
))
896 (delete-region (nth 1 ref
) (nth 2 ref
))
900 (defun org-footnote-delete-definitions (label)
901 "Delete every definition of the footnote LABEL.
902 Return the number of footnotes removed."
904 (goto-char (point-min))
905 (let ((def-re (concat "^\\[" (regexp-quote label
) "\\]"))
907 (while (re-search-forward def-re nil t
)
908 (let ((full-def (org-footnote-at-definition-p)))
910 ;; Remove the footnote, and all blank lines before it.
911 (goto-char (nth 1 full-def
))
912 (skip-chars-backward " \r\t\n")
913 (unless (bolp) (forward-line))
914 (delete-region (point) (nth 2 full-def
))
918 (defun org-footnote-delete (&optional label
)
919 "Delete the footnote at point.
920 This will remove the definition (even multiple definitions if they exist)
921 and all references of a footnote label.
923 If LABEL is non-nil, delete that footnote instead."
925 (let* ((nref 0) (ndef 0) x
926 ;; 1. Determine LABEL of footnote at point.
928 ;; LABEL is provided as argument.
930 ;; Footnote reference at point. If the footnote is
931 ;; anonymous, delete it and exit instead.
932 ((setq x
(org-footnote-at-reference-p))
935 (delete-region (nth 1 x
) (nth 2 x
))
936 (message "Anonymous footnote removed")
938 ;; Footnote definition at point.
939 ((setq x
(org-footnote-at-definition-p))
941 (t (error "Don't know which footnote to remove")))))
942 ;; 2. Now that LABEL is non-nil, find every reference and every
943 ;; definition, and delete them.
944 (setq nref
(org-footnote-delete-references label
)
945 ndef
(org-footnote-delete-definitions label
))
946 ;; 3. Verify consistency of footnotes and notify user.
947 (org-footnote-auto-adjust-maybe)
948 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
951 (defun org-footnote-renumber-fn:N
()
952 "Renumber the simple footnotes like fn:17 into a sequence in the document."
955 (org-with-wide-buffer
956 (goto-char (point-min))
957 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t
)
959 (goto-char (match-beginning 0))
960 ;; Ensure match is a footnote reference or definition.
961 (when (save-match-data (if (bolp)
962 (org-footnote-at-definition-p)
963 (org-footnote-at-reference-p)))
964 (let ((new-val (or (cdr (assoc (match-string 1) map
))
965 (number-to-string (incf n
)))))
966 (unless (assoc (match-string 1) map
)
967 (push (cons (match-string 1) new-val
) map
))
968 (replace-match new-val nil nil nil
1))))))))
970 (defun org-footnote-auto-adjust-maybe ()
971 "Renumber and/or sort footnotes according to user settings."
972 (when (memq org-footnote-auto-adjust
'(t renumber
))
973 (org-footnote-renumber-fn:N
))
974 (when (memq org-footnote-auto-adjust
'(t sort
))
975 (let ((label (car (org-footnote-at-definition-p))))
976 (org-footnote-normalize 'sort
)
978 (goto-char (point-min))
979 (and (re-search-forward (concat "^\\[" (regexp-quote label
) "\\]")
982 (just-one-space)))))))
984 (provide 'org-footnote
)
987 ;; generated-autoload-file: "org-loaddefs.el"
990 ;;; org-footnote.el ends here