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