test files: use cl- prefixed functions, and require cl-lib
[org-mode/org-tableheadings.git] / lisp / org-footnote.el
blobc460861fdd8ecc1778363fbfb0f725287162f4cb
1 ;;; org-footnote.el --- Footnote support in Org -*- lexical-binding: t; -*-
2 ;;
3 ;; Copyright (C) 2009-2018 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: https://orgmode.org
8 ;;
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 <https://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
27 ;; This file contains the code dealing with footnotes in Org mode.
29 ;;; Code:
31 ;;;; Declarations
33 (require 'cl-lib)
34 (require 'org-macs)
35 (require 'org-compat)
37 (declare-function org-at-comment-p "org" ())
38 (declare-function org-at-heading-p "org" (&optional ignored))
39 (declare-function org-back-over-empty-lines "org" ())
40 (declare-function org-edit-footnote-reference "org-src" ())
41 (declare-function org-element-at-point "org-element" ())
42 (declare-function org-element-class "org-element" (datum &optional parent))
43 (declare-function org-element-context "org-element" (&optional element))
44 (declare-function org-element-lineage "org-element" (blob &optional types with-self))
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 region))
49 (declare-function org-in-block-p "org" (names))
50 (declare-function org-in-verbatim-emphasis "org" ())
51 (declare-function org-inside-LaTeX-fragment-p "org" ())
52 (declare-function org-inside-latex-macro-p "org" ())
53 (declare-function org-mark-ring-push "org" (&optional pos buffer))
54 (declare-function org-show-context "org" (&optional key))
55 (declare-function outline-next-heading "outline")
57 (defvar electric-indent-mode)
58 (defvar org-blank-before-new-entry) ; defined in org.el
59 (defvar org-bracket-link-regexp) ; defined in org.el
60 (defvar org-complex-heading-regexp) ; defined in org.el
61 (defvar org-odd-levels-only) ; defined in org.el
62 (defvar org-outline-regexp) ; defined in org.el
63 (defvar org-outline-regexp-bol) ; defined in org.el
66 ;;;; Constants
68 (defconst org-footnote-re
69 "\\[fn:\\(?:\\(?1:[-_[:word:]]+\\)?\\(:\\)\\|\\(?1:[-_[:word:]]+\\)\\]\\)"
70 "Regular expression for matching footnotes.
71 Match group 1 contains footnote's label. It is nil for anonymous
72 footnotes. Match group 2 is non-nil only when footnote is
73 inline, i.e., it contains its own definition.")
75 (defconst org-footnote-definition-re "^\\[fn:\\([-_[:word:]]+\\)\\]"
76 "Regular expression matching the definition of a footnote.
77 Match group 1 contains definition's label.")
79 (defconst org-footnote-forbidden-blocks '("comment" "example" "export" "src")
80 "Names of blocks where footnotes are not allowed.")
83 ;;;; Customization
85 (defgroup org-footnote nil
86 "Footnotes in Org mode."
87 :tag "Org Footnote"
88 :group 'org)
90 (defcustom org-footnote-section "Footnotes"
91 "Outline heading containing footnote definitions.
93 This can be nil, to place footnotes locally at the end of the
94 current outline node. If can also be the name of a special
95 outline heading under which footnotes should be put.
97 This variable defines the place where Org puts the definition
98 automatically, i.e. when creating the footnote, and when sorting
99 the notes. However, by hand you may place definitions
100 *anywhere*.
102 If this is a string, during export, all subtrees starting with
103 this heading will be ignored.
105 If you don't use the customize interface to change this variable,
106 you will need to run the following command after the change:
108 `\\[universal-argument] \\[org-element-cache-reset]'"
109 :group 'org-footnote
110 :initialize 'custom-initialize-default
111 :set (lambda (var val)
112 (set var val)
113 (when (fboundp 'org-element-cache-reset)
114 (org-element-cache-reset 'all)))
115 :type '(choice
116 (string :tag "Collect footnotes under heading")
117 (const :tag "Define footnotes locally" nil)))
119 (defcustom org-footnote-define-inline nil
120 "Non-nil means define footnotes inline, at reference location.
121 When nil, footnotes will be defined in a special section near
122 the end of the document. When t, the [fn:label:definition] notation
123 will be used to define the footnote at the reference position."
124 :group 'org-footnote
125 :type 'boolean)
127 (defcustom org-footnote-auto-label t
128 "Non-nil means define automatically new labels for footnotes.
129 Possible values are:
131 nil Prompt the user for each label.
132 t Create unique labels of the form [fn:1], [fn:2], etc.
133 confirm Like t, but let the user edit the created value.
134 The label can be removed from the minibuffer to create
135 an anonymous footnote.
136 random Automatically generate a unique, random label."
137 :group 'org-footnote
138 :type '(choice
139 (const :tag "Prompt for label" nil)
140 (const :tag "Create automatic [fn:N]" t)
141 (const :tag "Offer automatic [fn:N] for editing" confirm)
142 (const :tag "Create a random label" random)))
144 (defcustom org-footnote-auto-adjust nil
145 "Non-nil means automatically adjust footnotes after insert/delete.
146 When this is t, after each insertion or deletion of a footnote,
147 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
148 If you want to have just sorting or just renumbering, set this variable
149 to `sort' or `renumber'.
151 The main values of this variable can be set with in-buffer options:
153 #+STARTUP: fnadjust
154 #+STARTUP: nofnadjust"
155 :group 'org-footnote
156 :type '(choice
157 (const :tag "No adjustment" nil)
158 (const :tag "Renumber" renumber)
159 (const :tag "Sort" sort)
160 (const :tag "Renumber and Sort" t)))
162 (defcustom org-footnote-fill-after-inline-note-extraction nil
163 "Non-nil means fill paragraphs after extracting footnotes.
164 When extracting inline footnotes, the lengths of lines can change a lot.
165 When this option is set, paragraphs from which an inline footnote has been
166 extracted will be filled again."
167 :group 'org-footnote
168 :type 'boolean)
171 ;;;; Predicates
173 (defun org-footnote-in-valid-context-p ()
174 "Is point in a context where footnotes are allowed?"
175 (save-match-data
176 (not (or (org-at-comment-p)
177 (org-inside-LaTeX-fragment-p)
178 ;; Avoid literal example.
179 (org-in-verbatim-emphasis)
180 (save-excursion
181 (beginning-of-line)
182 (looking-at "[ \t]*:[ \t]+"))
183 ;; Avoid forbidden blocks.
184 (org-in-block-p org-footnote-forbidden-blocks)))))
186 (defun org-footnote-at-reference-p ()
187 "Is the cursor at a footnote reference?
189 If so, return a list containing its label, beginning and ending
190 positions, and the definition, when inlined."
191 (when (and (org-footnote-in-valid-context-p)
192 (or (looking-at org-footnote-re)
193 (org-in-regexp org-footnote-re)
194 (save-excursion (re-search-backward org-footnote-re nil t)))
195 (/= (match-beginning 0) (line-beginning-position)))
196 (let* ((beg (match-beginning 0))
197 (label (match-string-no-properties 1))
198 ;; Inline footnotes don't end at (match-end 0) as
199 ;; `org-footnote-re' stops just after the second colon.
200 ;; Find the real ending with `scan-sexps', so Org doesn't
201 ;; get fooled by unrelated closing square brackets.
202 (end (ignore-errors (scan-sexps beg 1))))
203 ;; Point is really at a reference if it's located before true
204 ;; ending of the footnote.
205 (when (and end
206 (< (point) end)
207 ;; Verify match isn't a part of a link.
208 (not (save-excursion
209 (goto-char beg)
210 (let ((linkp
211 (save-match-data
212 (org-in-regexp org-bracket-link-regexp))))
213 (and linkp (< (point) (cdr linkp))))))
214 ;; Verify point doesn't belong to a LaTeX macro.
215 (not (org-inside-latex-macro-p)))
216 (list label beg end
217 ;; Definition: ensure this is an inline footnote first.
218 (and (match-end 2)
219 (org-trim
220 (buffer-substring-no-properties
221 (match-end 0) (1- end)))))))))
223 (defun org-footnote-at-definition-p ()
224 "Is point within a footnote definition?
226 This matches only pure definitions like [1] or [fn:name] at the
227 beginning of a line. It does not match references like
228 \[fn:name:definition], where the footnote text is included and
229 defined locally.
231 The return value will be nil if not at a footnote definition, and
232 a list with label, start, end and definition of the footnote
233 otherwise."
234 (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
235 (save-excursion
236 (end-of-line)
237 ;; Footnotes definitions are separated by new headlines, another
238 ;; footnote definition or 2 blank lines.
239 (let ((lim (save-excursion
240 (re-search-backward
241 (concat org-outline-regexp-bol
242 "\\|^\\([ \t]*\n\\)\\{2,\\}") nil t))))
243 (when (re-search-backward org-footnote-definition-re lim t)
244 (let ((label (match-string-no-properties 1))
245 (beg (match-beginning 0))
246 (beg-def (match-end 0))
247 (end (if (progn
248 (end-of-line)
249 (re-search-forward
250 (concat org-outline-regexp-bol "\\|"
251 org-footnote-definition-re "\\|"
252 "^\\([ \t]*\n\\)\\{2,\\}") nil 'move))
253 (match-beginning 0)
254 (point))))
255 (list label beg end
256 (org-trim (buffer-substring-no-properties beg-def end)))))))))
259 ;;;; Internal functions
261 (defun org-footnote--allow-reference-p ()
262 "Non-nil when a footnote reference can be inserted at point."
263 ;; XXX: This is similar to `org-footnote-in-valid-context-p' but
264 ;; more accurate and usually faster, except in some corner cases.
265 ;; It may replace it after doing proper benchmarks as it would be
266 ;; used in fontification.
267 (unless (bolp)
268 (let* ((context (org-element-context))
269 (type (org-element-type context)))
270 (cond
271 ;; No footnote reference in attributes.
272 ((let ((post (org-element-property :post-affiliated context)))
273 (and post (< (point) post)))
274 nil)
275 ;; Paragraphs and blank lines at top of document are fine.
276 ((memq type '(nil paragraph)))
277 ;; So are contents of verse blocks.
278 ((eq type 'verse-block)
279 (and (>= (point) (org-element-property :contents-begin context))
280 (< (point) (org-element-property :contents-end context))))
281 ;; In an headline or inlinetask, point must be either on the
282 ;; heading itself or on the blank lines below.
283 ((memq type '(headline inlinetask))
284 (or (not (org-at-heading-p))
285 (and (save-excursion
286 (beginning-of-line)
287 (and (let ((case-fold-search t))
288 (not (looking-at-p "\\*+ END[ \t]*$")))
289 (let ((case-fold-search nil))
290 (looking-at org-complex-heading-regexp))))
291 (match-beginning 4)
292 (>= (point) (match-beginning 4))
293 (or (not (match-beginning 5))
294 (< (point) (match-beginning 5))))))
295 ;; White spaces after an object or blank lines after an element
296 ;; are OK.
297 ((>= (point)
298 (save-excursion (goto-char (org-element-property :end context))
299 (skip-chars-backward " \r\t\n")
300 (if (eq (org-element-class context) 'object) (point)
301 (1+ (line-beginning-position 2))))))
302 ;; Other elements are invalid.
303 ((eq (org-element-class context) 'element) nil)
304 ;; Just before object is fine.
305 ((= (point) (org-element-property :begin context)))
306 ;; Within recursive object too, but not in a link.
307 ((eq type 'link) nil)
308 ((let ((cbeg (org-element-property :contents-begin context))
309 (cend (org-element-property :contents-end context)))
310 (and cbeg (>= (point) cbeg) (<= (point) cend))))))))
312 (defun org-footnote--clear-footnote-section ()
313 "Remove all footnote sections in buffer and create a new one.
314 New section is created at the end of the buffer. Leave point
315 within the new section."
316 (when org-footnote-section
317 (goto-char (point-min))
318 (let ((regexp (format "^\\*+ +%s[ \t]*$"
319 (regexp-quote org-footnote-section))))
320 (while (re-search-forward regexp nil t)
321 (delete-region
322 (match-beginning 0)
323 (org-end-of-subtree t t))))
324 (goto-char (point-max))
325 ;; Clean-up blank lines at the end of the buffer.
326 (skip-chars-backward " \r\t\n")
327 (unless (bobp)
328 (forward-line)
329 (when (eolp) (insert "\n")))
330 (delete-region (point) (point-max))
331 (when (and (cdr (assq 'heading org-blank-before-new-entry))
332 (zerop (save-excursion (org-back-over-empty-lines))))
333 (insert "\n"))
334 (insert "* " org-footnote-section "\n")))
336 (defun org-footnote--set-label (label)
337 "Set label of footnote at point to string LABEL.
338 Assume point is at the beginning of the reference or definition
339 to rename."
340 (forward-char 4)
341 (cond ((eq (char-after) ?:) (insert label))
342 ((looking-at "\\([-_[:word:]]+\\)") (replace-match label nil nil nil 1))
343 (t nil)))
345 (defun org-footnote--collect-references (&optional anonymous)
346 "Collect all labeled footnote references in current buffer.
348 Return an alist where associations follow the pattern
350 (LABEL MARKER TOP-LEVEL SIZE)
352 with
354 LABEL the label of the of the definition,
355 MARKER a marker pointing to its beginning,
356 TOP-LEVEL a boolean, nil when the footnote is contained within
357 another one,
358 SIZE the length of the inline definition, in characters,
359 or nil for non-inline references.
361 When optional ANONYMOUS is non-nil, also collect anonymous
362 references. In such cases, LABEL is nil.
364 References are sorted according to a deep-reading order."
365 (org-with-wide-buffer
366 (goto-char (point-min))
367 (let ((regexp (if anonymous org-footnote-re "\\[fn:[-_[:word:]]+[]:]"))
368 references nested)
369 (save-excursion
370 (while (re-search-forward regexp nil t)
371 ;; Ignore definitions.
372 (unless (and (eq (char-before) ?\])
373 (= (line-beginning-position) (match-beginning 0)))
374 ;; Ensure point is within the reference before parsing it.
375 (backward-char)
376 (let ((object (org-element-context)))
377 (when (eq (org-element-type object) 'footnote-reference)
378 (let* ((label (org-element-property :label object))
379 (begin (org-element-property :begin object))
380 (size
381 (and (eq (org-element-property :type object) 'inline)
382 (- (org-element-property :contents-end object)
383 (org-element-property :contents-begin object)))))
384 (let ((d (org-element-lineage object '(footnote-definition))))
385 (push (list label (copy-marker begin) (not d) size)
386 references)
387 (when d
388 ;; Nested references are stored in alist NESTED.
389 ;; Associations there follow the pattern
391 ;; (DEFINITION-LABEL . REFERENCES)
392 (let* ((def-label (org-element-property :label d))
393 (labels (assoc def-label nested)))
394 (if labels (push label (cdr labels))
395 (push (list def-label label) nested)))))))))))
396 ;; Sort the list of references. Nested footnotes have priority
397 ;; over top-level ones.
398 (letrec ((ordered nil)
399 (add-reference
400 (lambda (ref allow-nested)
401 (when (or allow-nested (nth 2 ref))
402 (push ref ordered)
403 (dolist (r (mapcar (lambda (l) (assoc l references))
404 (reverse
405 (cdr (assoc (nth 0 ref) nested)))))
406 (funcall add-reference r t))))))
407 (dolist (r (reverse references) (nreverse ordered))
408 (funcall add-reference r nil))))))
410 (defun org-footnote--collect-definitions (&optional delete)
411 "Collect all footnote definitions in current buffer.
413 Return an alist where associations follow the pattern
415 (LABEL . DEFINITION)
417 with LABEL and DEFINITION being, respectively, the label and the
418 definition of the footnote, as strings.
420 When optional argument DELETE is non-nil, delete the definition
421 while collecting them."
422 (org-with-wide-buffer
423 (goto-char (point-min))
424 (let (definitions seen)
425 (while (re-search-forward org-footnote-definition-re nil t)
426 (backward-char)
427 (let ((element (org-element-at-point)))
428 (let ((label (org-element-property :label element)))
429 (when (and (eq (org-element-type element) 'footnote-definition)
430 (not (member label seen)))
431 (push label seen)
432 (let* ((beg (progn
433 (goto-char (org-element-property :begin element))
434 (skip-chars-backward " \r\t\n")
435 (if (bobp) (point) (line-beginning-position 2))))
436 (end (progn
437 (goto-char (org-element-property :end element))
438 (skip-chars-backward " \r\t\n")
439 (line-beginning-position 2)))
440 (def (org-trim (buffer-substring-no-properties beg end))))
441 (push (cons label def) definitions)
442 (when delete (delete-region beg end)))))))
443 definitions)))
445 (defun org-footnote--goto-local-insertion-point ()
446 "Find insertion point for footnote, just before next outline heading.
447 Assume insertion point is within currently accessible part of the buffer."
448 (org-with-limited-levels (outline-next-heading))
449 (skip-chars-backward " \t\n")
450 (unless (bobp) (forward-line))
451 (unless (bolp) (insert "\n")))
454 ;;;; Navigation
456 (defun org-footnote-get-next-reference (&optional label backward limit)
457 "Return complete reference of the next footnote.
459 If LABEL is provided, get the next reference of that footnote. If
460 BACKWARD is non-nil, find previous reference instead. LIMIT is
461 the buffer position bounding the search.
463 Return value is a list like those provided by `org-footnote-at-reference-p'.
464 If no footnote is found, return nil."
465 (save-excursion
466 (let* ((label-fmt (if label (format "\\[fn:%s[]:]" label) org-footnote-re)))
467 (catch 'exit
468 (while t
469 (unless (funcall (if backward #'re-search-backward #'re-search-forward)
470 label-fmt limit t)
471 (throw 'exit nil))
472 (unless backward (backward-char))
473 (let ((ref (org-footnote-at-reference-p)))
474 (when ref (throw 'exit ref))))))))
476 (defun org-footnote-next-reference-or-definition (limit)
477 "Move point to next footnote reference or definition.
479 LIMIT is the buffer position bounding the search.
481 Return value is a list like those provided by
482 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
483 If no footnote is found, return nil."
484 (let* (ref (origin (point)))
485 (catch 'exit
486 (while t
487 (unless (re-search-forward org-footnote-re limit t)
488 (goto-char origin)
489 (throw 'exit nil))
490 ;; Beware: with non-inline footnotes point will be just after
491 ;; the closing square bracket.
492 (backward-char)
493 (cond
494 ((setq ref (org-footnote-at-reference-p))
495 (throw 'exit ref))
496 ;; Definition: also grab the last square bracket, matched in
497 ;; `org-footnote-re' for non-inline footnotes.
498 ((save-match-data (org-footnote-at-definition-p))
499 (let ((end (match-end 0)))
500 (throw 'exit
501 (list nil (match-beginning 0)
502 (if (eq (char-before end) ?\]) end (1+ end)))))))))))
504 (defun org-footnote-goto-definition (label &optional location)
505 "Move point to the definition of the footnote LABEL.
507 LOCATION, when non-nil specifies the buffer position of the
508 definition.
510 Throw an error if there is no definition or if it cannot be
511 reached from current narrowed part of buffer. Return a non-nil
512 value if point was successfully moved."
513 (interactive "sLabel: ")
514 (let* ((label (org-footnote-normalize-label label))
515 (def-start (or location (nth 1 (org-footnote-get-definition label)))))
516 (cond
517 ((not def-start)
518 (user-error "Cannot find definition of footnote %s" label))
519 ((or (> def-start (point-max)) (< def-start (point-min)))
520 (user-error "Definition is outside narrowed part of buffer")))
521 (org-mark-ring-push)
522 (goto-char def-start)
523 (looking-at (format "\\[fn:%s[]:] ?" (regexp-quote label)))
524 (goto-char (match-end 0))
525 (org-show-context 'link-search)
526 (when (derived-mode-p 'org-mode)
527 (message "%s" (substitute-command-keys
528 "Edit definition and go back with \
529 `\\[org-mark-ring-goto]' or, if unique, with `\\[org-ctrl-c-ctrl-c]'.")))
532 (defun org-footnote-goto-previous-reference (label)
533 "Find the first closest (to point) reference of footnote with label LABEL."
534 (interactive "sLabel: ")
535 (org-mark-ring-push)
536 (let ((label (org-footnote-normalize-label label))
537 ref)
538 (save-excursion
539 (setq ref (or (org-footnote-get-next-reference label t)
540 (org-footnote-get-next-reference label)
541 (save-restriction
542 (widen)
544 (org-footnote-get-next-reference label t)
545 (org-footnote-get-next-reference label))))))
546 (if (not ref)
547 (error "Cannot find reference of footnote %s" label)
548 (goto-char (nth 1 ref))
549 (org-show-context 'link-search))))
552 ;;;; Getters
554 (defun org-footnote-normalize-label (label)
555 "Return LABEL without \"fn:\" prefix.
556 If LABEL is the empty string or constituted of white spaces only,
557 return nil instead."
558 (pcase (org-trim label)
559 ("" nil)
560 ((pred (string-prefix-p "fn:")) (substring label 3))
561 (_ label)))
563 (defun org-footnote-get-definition (label)
564 "Return label, boundaries and definition of the footnote LABEL."
565 (let* ((label (regexp-quote (org-footnote-normalize-label label)))
566 (re (format "^\\[fn:%s\\]\\|.\\[fn:%s:" label label)))
567 (org-with-wide-buffer
568 (goto-char (point-min))
569 (catch 'found
570 (while (re-search-forward re nil t)
571 (let* ((datum (progn (backward-char) (org-element-context)))
572 (type (org-element-type datum)))
573 (when (memq type '(footnote-definition footnote-reference))
574 (throw 'found
575 (list
576 label
577 (org-element-property :begin datum)
578 (org-element-property :end datum)
579 (let ((cbeg (org-element-property :contents-begin datum)))
580 (if (not cbeg) ""
581 (replace-regexp-in-string
582 "[ \t\n]*\\'"
584 (buffer-substring-no-properties
585 cbeg
586 (org-element-property :contents-end datum))))))))))
587 nil))))
589 (defun org-footnote-all-labels ()
590 "List all defined footnote labels used throughout the buffer.
591 This function ignores narrowing, if any."
592 (org-with-wide-buffer
593 (goto-char (point-min))
594 (let (all)
595 (while (re-search-forward org-footnote-re nil t)
596 (backward-char)
597 (let ((context (org-element-context)))
598 (when (memq (org-element-type context)
599 '(footnote-definition footnote-reference))
600 (let ((label (org-element-property :label context)))
601 (when label (cl-pushnew label all :test #'equal))))))
602 all)))
604 (defun org-footnote-unique-label (&optional current)
605 "Return a new unique footnote label.
607 The function returns the first numeric label currently unused.
609 Optional argument CURRENT is the list of labels active in the
610 buffer."
611 (let ((current (or current (org-footnote-all-labels))))
612 (let ((count 1))
613 (while (member (number-to-string count) current)
614 (cl-incf count))
615 (number-to-string count))))
618 ;;;; Adding, Deleting Footnotes
620 (defun org-footnote-new ()
621 "Insert a new footnote.
622 This command prompts for a label. If this is a label referencing an
623 existing label, only insert the label. If the footnote label is empty
624 or new, let the user edit the definition of the footnote."
625 (interactive)
626 (unless (org-footnote--allow-reference-p)
627 (user-error "Cannot insert a footnote here"))
628 (let* ((all (org-footnote-all-labels))
629 (label
630 (if (eq org-footnote-auto-label 'random)
631 (format "%x" (random most-positive-fixnum))
632 (org-footnote-normalize-label
633 (let ((propose (org-footnote-unique-label all)))
634 (if (eq org-footnote-auto-label t) propose
635 (completing-read
636 "Label (leave empty for anonymous): "
637 (mapcar #'list all) nil nil
638 (and (eq org-footnote-auto-label 'confirm) propose))))))))
639 (cond ((not label)
640 (insert "[fn::]")
641 (backward-char 1))
642 ((member label all)
643 (insert "[fn:" label "]")
644 (message "New reference to existing note"))
645 (org-footnote-define-inline
646 (insert "[fn:" label ":]")
647 (backward-char 1)
648 (org-footnote-auto-adjust-maybe))
650 (insert "[fn:" label "]")
651 (let ((p (org-footnote-create-definition label)))
652 ;; `org-footnote-goto-definition' needs to be called
653 ;; after `org-footnote-auto-adjust-maybe'. Otherwise
654 ;; both label and location of the definition are lost.
655 ;; On the contrary, it needs to be called before
656 ;; `org-edit-footnote-reference' so that the remote
657 ;; editing buffer can display the correct label.
658 (if (ignore-errors (org-footnote-goto-definition label p))
659 (org-footnote-auto-adjust-maybe)
660 ;; Definition was created outside current scope: edit
661 ;; it remotely.
662 (org-footnote-auto-adjust-maybe)
663 (org-edit-footnote-reference)))))))
665 (defun org-footnote-create-definition (label)
666 "Start the definition of a footnote with label LABEL.
667 Return buffer position at the beginning of the definition. This
668 function doesn't move point."
669 (let ((label (org-footnote-normalize-label label))
670 electric-indent-mode) ; Prevent wrong indentation.
671 (org-preserve-local-variables
672 (org-with-wide-buffer
673 (cond
674 ((not org-footnote-section) (org-footnote--goto-local-insertion-point))
675 ((save-excursion
676 (goto-char (point-min))
677 (re-search-forward
678 (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section) "[ \t]*$")
679 nil t))
680 (goto-char (match-end 0))
681 (forward-line)
682 (unless (bolp) (insert "\n")))
683 (t (org-footnote--clear-footnote-section)))
684 (when (zerop (org-back-over-empty-lines)) (insert "\n"))
685 (insert "[fn:" label "] \n")
686 (line-beginning-position 0)))))
688 (defun org-footnote-delete-references (label)
689 "Delete every reference to footnote LABEL.
690 Return the number of footnotes removed."
691 (save-excursion
692 (goto-char (point-min))
693 (let (ref (nref 0))
694 (while (setq ref (org-footnote-get-next-reference label))
695 (goto-char (nth 1 ref))
696 (delete-region (nth 1 ref) (nth 2 ref))
697 (cl-incf nref))
698 nref)))
700 (defun org-footnote-delete-definitions (label)
701 "Delete every definition of the footnote LABEL.
702 Return the number of footnotes removed."
703 (save-excursion
704 (goto-char (point-min))
705 (let ((def-re (format "^\\[fn:%s\\]" (regexp-quote label)))
706 (ndef 0))
707 (while (re-search-forward def-re nil t)
708 (pcase (org-footnote-at-definition-p)
709 (`(,_ ,start ,end ,_)
710 ;; Remove the footnote, and all blank lines before it.
711 (delete-region (progn
712 (goto-char start)
713 (skip-chars-backward " \r\t\n")
714 (if (bobp) (point) (line-beginning-position 2)))
715 (progn
716 (goto-char end)
717 (skip-chars-backward " \r\t\n")
718 (if (bobp) (point) (line-beginning-position 2))))
719 (cl-incf ndef))))
720 ndef)))
722 (defun org-footnote-delete (&optional label)
723 "Delete the footnote at point.
724 This will remove the definition (even multiple definitions if they exist)
725 and all references of a footnote label.
727 If LABEL is non-nil, delete that footnote instead."
728 (catch 'done
729 (org-preserve-local-variables
730 (let* ((nref 0) (ndef 0) x
731 ;; 1. Determine LABEL of footnote at point.
732 (label (cond
733 ;; LABEL is provided as argument.
734 (label)
735 ;; Footnote reference at point. If the footnote is
736 ;; anonymous, delete it and exit instead.
737 ((setq x (org-footnote-at-reference-p))
738 (or (car x)
739 (progn
740 (delete-region (nth 1 x) (nth 2 x))
741 (message "Anonymous footnote removed")
742 (throw 'done t))))
743 ;; Footnote definition at point.
744 ((setq x (org-footnote-at-definition-p))
745 (car x))
746 (t (error "Don't know which footnote to remove")))))
747 ;; 2. Now that LABEL is non-nil, find every reference and every
748 ;; definition, and delete them.
749 (setq nref (org-footnote-delete-references label)
750 ndef (org-footnote-delete-definitions label))
751 ;; 3. Verify consistency of footnotes and notify user.
752 (org-footnote-auto-adjust-maybe)
753 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
754 ndef nref label)))))
757 ;;;; Sorting, Renumbering, Normalizing
759 (defun org-footnote-renumber-fn:N ()
760 "Order numbered footnotes into a sequence in the document."
761 (interactive)
762 (let* ((c 0)
763 (references (cl-remove-if-not
764 (lambda (r) (string-match-p "\\`[0-9]+\\'" (car r)))
765 (org-footnote--collect-references)))
766 (alist (mapcar (lambda (l) (cons l (number-to-string (cl-incf c))))
767 (delete-dups (mapcar #'car references)))))
768 (org-with-wide-buffer
769 ;; Re-number references.
770 (dolist (ref references)
771 (goto-char (nth 1 ref))
772 (org-footnote--set-label (cdr (assoc (nth 0 ref) alist))))
773 ;; Re-number definitions.
774 (goto-char (point-min))
775 (while (re-search-forward "^\\[fn:\\([0-9]+\\)\\]" nil t)
776 (replace-match (or (cdr (assoc (match-string 1) alist))
777 ;; Un-referenced definitions get higher
778 ;; numbers.
779 (number-to-string (cl-incf c)))
780 nil nil nil 1)))))
782 (defun org-footnote-sort ()
783 "Rearrange footnote definitions in the current buffer.
784 Sort footnote definitions so they match order of footnote
785 references. Also relocate definitions at the end of their
786 relative section or within a single footnote section, according
787 to `org-footnote-section'. Inline definitions are ignored."
788 (let ((references (org-footnote--collect-references)))
789 (org-preserve-local-variables
790 (let ((definitions (org-footnote--collect-definitions 'delete)))
791 (org-with-wide-buffer
792 (org-footnote--clear-footnote-section)
793 ;; Insert footnote definitions at the appropriate location,
794 ;; separated by a blank line. Each definition is inserted
795 ;; only once throughout the buffer.
796 (let (inserted)
797 (dolist (cell references)
798 (let ((label (car cell))
799 (nested (not (nth 2 cell)))
800 (inline (nth 3 cell)))
801 (unless (or (member label inserted) inline)
802 (push label inserted)
803 (unless (or org-footnote-section nested)
804 ;; If `org-footnote-section' is non-nil, or
805 ;; reference is nested, point is already at the
806 ;; correct position. Otherwise, move at the
807 ;; appropriate location within the section
808 ;; containing the reference.
809 (goto-char (nth 1 cell))
810 (org-footnote--goto-local-insertion-point))
811 (insert "\n"
812 (or (cdr (assoc label definitions))
813 (format "[fn:%s] DEFINITION NOT FOUND." label))
814 "\n"))))
815 ;; Insert un-referenced footnote definitions at the end.
816 (pcase-dolist (`(,label . ,definition) definitions)
817 (unless (member label inserted)
818 (insert "\n" definition "\n")))))))))
820 (defun org-footnote-normalize ()
821 "Turn every footnote in buffer into a numbered one."
822 (interactive)
823 (org-preserve-local-variables
824 (let ((n 0)
825 (translations nil)
826 (definitions nil)
827 (references (org-footnote--collect-references 'anonymous)))
828 (org-with-wide-buffer
829 ;; Update label for reference. We need to do this before
830 ;; clearing definitions in order to rename nested footnotes
831 ;; before they are deleted.
832 (dolist (cell references)
833 (let* ((label (car cell))
834 (anonymous (not label))
835 (new
836 (cond
837 ;; In order to differentiate anonymous references
838 ;; from regular ones, set their labels to integers,
839 ;; not strings.
840 (anonymous (setcar cell (cl-incf n)))
841 ((cdr (assoc label translations)))
842 (t (let ((l (number-to-string (cl-incf n))))
843 (push (cons label l) translations)
844 l)))))
845 (goto-char (nth 1 cell)) ; Move to reference's start.
846 (org-footnote--set-label
847 (if anonymous (number-to-string new) new))
848 (let ((size (nth 3 cell)))
849 ;; Transform inline footnotes into regular references and
850 ;; retain their definition for later insertion as
851 ;; a regular footnote definition.
852 (when size
853 (let ((def (concat
854 (format "[fn:%s] " new)
855 (org-trim
856 (substring
857 (delete-and-extract-region
858 (point) (+ (point) size 1))
859 1)))))
860 (push (cons (if anonymous new label) def) definitions)
861 (when org-footnote-fill-after-inline-note-extraction
862 (org-fill-paragraph)))))))
863 ;; Collect definitions. Update labels according to ALIST.
864 (let ((definitions
865 (nconc definitions
866 (org-footnote--collect-definitions 'delete)))
867 (inserted))
868 (org-footnote--clear-footnote-section)
869 (dolist (cell references)
870 (let* ((label (car cell))
871 (anonymous (integerp label))
872 (pos (nth 1 cell)))
873 ;; Move to appropriate location, if required. When there
874 ;; is a footnote section or reference is nested, point is
875 ;; already at the expected location.
876 (unless (or org-footnote-section (not (nth 2 cell)))
877 (goto-char pos)
878 (org-footnote--goto-local-insertion-point))
879 ;; Insert new definition once label is updated.
880 (unless (member label inserted)
881 (push label inserted)
882 (let ((stored (cdr (assoc label definitions)))
883 ;; Anonymous footnotes' label is already
884 ;; up-to-date.
885 (new (if anonymous label
886 (cdr (assoc label translations)))))
887 (insert "\n"
888 (cond
889 ((not stored)
890 (format "[fn:%s] DEFINITION NOT FOUND." new))
891 (anonymous stored)
893 (replace-regexp-in-string
894 "\\`\\[fn:\\(.*?\\)\\]" new stored nil nil 1)))
895 "\n")))))
896 ;; Insert un-referenced footnote definitions at the end.
897 (pcase-dolist (`(,label . ,definition) definitions)
898 (unless (member label inserted)
899 (insert "\n"
900 (replace-regexp-in-string org-footnote-definition-re
901 (format "[fn:%d]" (cl-incf n))
902 definition)
903 "\n"))))))))
905 (defun org-footnote-auto-adjust-maybe ()
906 "Renumber and/or sort footnotes according to user settings."
907 (when (memq org-footnote-auto-adjust '(t renumber))
908 (org-footnote-renumber-fn:N))
909 (when (memq org-footnote-auto-adjust '(t sort))
910 (let ((label (car (org-footnote-at-definition-p))))
911 (org-footnote-sort)
912 (when label
913 (goto-char (point-min))
914 (and (re-search-forward (format "^\\[fn:%s\\]" (regexp-quote label))
915 nil t)
916 (progn (insert " ")
917 (just-one-space)))))))
920 ;;;; End-user interface
922 ;;;###autoload
923 (defun org-footnote-action (&optional special)
924 "Do the right thing for footnotes.
926 When at a footnote reference, jump to the definition.
928 When at a definition, jump to the references if they exist, offer
929 to create them otherwise.
931 When neither at definition or reference, create a new footnote,
932 interactively if possible.
934 With prefix arg SPECIAL, or when no footnote can be created,
935 offer additional commands in a menu."
936 (interactive "P")
937 (let* ((context (and (not special) (org-element-context)))
938 (type (org-element-type context)))
939 (cond
940 ;; On white space after element, insert a new footnote.
941 ((and context
942 (> (point)
943 (save-excursion
944 (goto-char (org-element-property :end context))
945 (skip-chars-backward " \t")
946 (point))))
947 (org-footnote-new))
948 ((eq type 'footnote-reference)
949 (let ((label (org-element-property :label context)))
950 (cond
951 ;; Anonymous footnote: move point at the beginning of its
952 ;; definition.
953 ((not label)
954 (goto-char (org-element-property :contents-begin context)))
955 ;; Check if a definition exists: then move to it.
956 ((let ((p (nth 1 (org-footnote-get-definition label))))
957 (when p (org-footnote-goto-definition label p))))
958 ;; No definition exists: offer to create it.
959 ((yes-or-no-p (format "No definition for %s. Create one? " label))
960 (let ((p (org-footnote-create-definition label)))
961 (or (ignore-errors (org-footnote-goto-definition label p))
962 ;; Since definition was created outside current scope,
963 ;; edit it remotely.
964 (org-edit-footnote-reference)))))))
965 ((eq type 'footnote-definition)
966 (org-footnote-goto-previous-reference
967 (org-element-property :label context)))
968 ((or special (not (org-footnote--allow-reference-p)))
969 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | [n]ormalize | \
970 \[d]elete")
971 (pcase (read-char-exclusive)
972 (?s (org-footnote-sort))
973 (?r (org-footnote-renumber-fn:N))
974 (?S (org-footnote-renumber-fn:N)
975 (org-footnote-sort))
976 (?n (org-footnote-normalize))
977 (?d (org-footnote-delete))
978 (char (error "No such footnote command %c" char))))
979 (t (org-footnote-new)))))
982 (provide 'org-footnote)
984 ;; Local variables:
985 ;; generated-autoload-file: "org-loaddefs.el"
986 ;; End:
988 ;;; org-footnote.el ends here