Silence byte-compiler
[org-mode.git] / lisp / org-footnote.el
blob759cc2e0f4ade5278b3c945e32538436149585d4
1 ;;; org-footnote.el --- Footnote support in Org -*- lexical-binding: t; -*-
2 ;;
3 ;; Copyright (C) 2009-2015 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.
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.
33 ;;; Code:
35 (eval-when-compile
36 (require 'cl))
37 (require 'org-macs)
38 (require 'org-compat)
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) ; defined in org.el
74 (defvar org-outline-regexp-bol) ; defined in org.el
76 (defconst org-footnote-re
77 ;; Only [1]-like footnotes are closed in this regexp, as footnotes
78 ;; from other types might contain square brackets (i.e. links) in
79 ;; their definition.
81 ;; `org-re' is used for regexp compatibility with XEmacs.
82 (concat "\\[\\(?:"
83 ;; Match inline footnotes.
84 (org-re "fn:\\([-_[:word:]]+\\)?:\\|")
85 ;; Match other footnotes.
86 "\\(?:\\([0-9]+\\)\\]\\)\\|"
87 (org-re "\\(fn:[-_[:word:]]+\\)")
88 "\\)")
89 "Regular expression for matching footnotes.")
91 (defconst org-footnote-definition-re
92 (org-re "^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
93 "Regular expression matching the definition of a footnote.")
95 (defconst org-footnote-forbidden-blocks
96 '("ascii" "beamer" "comment" "example" "html" "latex" "odt" "src")
97 "Names of blocks where footnotes are not allowed.")
99 (defgroup org-footnote nil
100 "Footnotes in Org-mode."
101 :tag "Org Footnote"
102 :group 'org)
104 (defcustom org-footnote-section "Footnotes"
105 "Outline heading containing footnote definitions.
107 This can be nil, to place footnotes locally at the end of the
108 current outline node. If can also be the name of a special
109 outline heading under which footnotes should be put.
111 This variable defines the place where Org puts the definition
112 automatically, i.e. when creating the footnote, and when sorting
113 the notes. However, by hand you may place definitions
114 *anywhere*.
116 If this is a string, during export, all subtrees starting with
117 this heading will be ignored.
119 If you don't use the customize interface to change this variable,
120 you will need to run the following command after the change:
122 \\[universal-argument] \\[org-element-cache-reset]"
123 :group 'org-footnote
124 :initialize 'custom-initialize-default
125 :set (lambda (var val)
126 (set var val)
127 (when (fboundp 'org-element-cache-reset)
128 (org-element-cache-reset 'all)))
129 :type '(choice
130 (string :tag "Collect footnotes under heading")
131 (const :tag "Define footnotes locally" nil)))
133 (defcustom org-footnote-tag-for-non-org-mode-files "Footnotes:"
134 "Tag marking the beginning of footnote section.
135 The Org footnote engine can be used in arbitrary text files as well
136 as in Org-mode. Outside Org mode, new footnotes are always placed at
137 the end of the file. When you normalize the notes, any line containing
138 only this tag will be removed, a new one will be inserted at the end
139 of the file, followed by the collected and normalized footnotes.
141 If you don't want any tag in such buffers, set this variable to nil."
142 :group 'org-footnote
143 :type '(choice
144 (string :tag "Collect footnotes under tag")
145 (const :tag "Don't use a tag" nil)))
147 (defcustom org-footnote-define-inline nil
148 "Non-nil means define footnotes inline, at reference location.
149 When nil, footnotes will be defined in a special section near
150 the end of the document. When t, the [fn:label:definition] notation
151 will be used to define the footnote at the reference position."
152 :group 'org-footnote
153 :type 'boolean)
155 (defcustom org-footnote-auto-label t
156 "Non-nil means define automatically new labels for footnotes.
157 Possible values are:
159 nil Prompt the user for each label.
160 t Create unique labels of the form [fn:1], [fn:2], etc.
161 confirm Like t, but let the user edit the created value.
162 The label can be removed from the minibuffer to create
163 an anonymous footnote.
164 random Automatically generate a unique, random label.
165 plain Automatically create plain number labels like [1]."
166 :group 'org-footnote
167 :type '(choice
168 (const :tag "Prompt for label" nil)
169 (const :tag "Create automatic [fn:N]" t)
170 (const :tag "Offer automatic [fn:N] for editing" confirm)
171 (const :tag "Create a random label" random)
172 (const :tag "Create automatic [N]" plain)))
174 (defcustom org-footnote-auto-adjust nil
175 "Non-nil means automatically adjust footnotes after insert/delete.
176 When this is t, after each insertion or deletion of a footnote,
177 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
178 If you want to have just sorting or just renumbering, set this variable
179 to `sort' or `renumber'.
181 The main values of this variable can be set with in-buffer options:
183 #+STARTUP: fnadjust
184 #+STARTUP: nofnadjust"
185 :group 'org-footnote
186 :type '(choice
187 (const :tag "No adjustment" nil)
188 (const :tag "Renumber" renumber)
189 (const :tag "Sort" sort)
190 (const :tag "Renumber and Sort" t)))
192 (defcustom org-footnote-fill-after-inline-note-extraction nil
193 "Non-nil means fill paragraphs after extracting footnotes.
194 When extracting inline footnotes, the lengths of lines can change a lot.
195 When this option is set, paragraphs from which an inline footnote has been
196 extracted will be filled again."
197 :group 'org-footnote
198 :type 'boolean)
200 (defun org-footnote-in-valid-context-p ()
201 "Is point in a context where footnotes are allowed?"
202 (save-match-data
203 (not (or (org-at-comment-p)
204 (org-inside-LaTeX-fragment-p)
205 ;; Avoid literal example.
206 (org-in-verbatim-emphasis)
207 (save-excursion
208 (beginning-of-line)
209 (looking-at "[ \t]*:[ \t]+"))
210 ;; Avoid cited text and headers in message-mode.
211 (and (derived-mode-p 'message-mode)
212 (or (save-excursion
213 (beginning-of-line)
214 (looking-at message-cite-prefix-regexp))
215 (message-point-in-header-p)))
216 ;; Avoid forbidden blocks.
217 (org-in-block-p org-footnote-forbidden-blocks)))))
219 (defun org-footnote-at-reference-p ()
220 "Is the cursor at a footnote reference?
222 If so, return a list containing its label, beginning and ending
223 positions, and the definition, when inlined."
224 (when (and (org-footnote-in-valid-context-p)
225 (or (looking-at org-footnote-re)
226 (org-in-regexp org-footnote-re)
227 (save-excursion (re-search-backward org-footnote-re nil t)))
228 (/= (match-beginning 0) (point-at-bol)))
229 (let* ((beg (match-beginning 0))
230 (label (or (org-match-string-no-properties 2)
231 (org-match-string-no-properties 3)
232 ;; Anonymous footnotes don't have labels
233 (and (match-string 1)
234 (concat "fn:" (org-match-string-no-properties 1)))))
235 ;; Inline footnotes don't end at (match-end 0) as
236 ;; `org-footnote-re' stops just after the second colon.
237 ;; Find the real ending with `scan-sexps', so Org doesn't
238 ;; get fooled by unrelated closing square brackets.
239 (end (ignore-errors (scan-sexps beg 1))))
240 ;; Point is really at a reference if it's located before true
241 ;; ending of the footnote.
242 (when (and end (< (point) end)
243 ;; Verify match isn't a part of a link.
244 (not (save-excursion
245 (goto-char beg)
246 (let ((linkp
247 (save-match-data
248 (org-in-regexp org-bracket-link-regexp))))
249 (and linkp (< (point) (cdr linkp))))))
250 ;; Verify point doesn't belong to a LaTeX macro.
251 (not (org-inside-latex-macro-p)))
252 (list label beg end
253 ;; Definition: ensure this is an inline footnote first.
254 (and (or (not label) (match-string 1))
255 (org-trim (buffer-substring-no-properties
256 (match-end 0) (1- end)))))))))
258 (defun org-footnote-at-definition-p ()
259 "Is point within a footnote definition?
261 This matches only pure definitions like [1] or [fn:name] at the
262 beginning of a line. It does not match references like
263 \[fn:name:definition], where the footnote text is included and
264 defined locally.
266 The return value will be nil if not at a footnote definition, and
267 a list with label, start, end and definition of the footnote
268 otherwise."
269 (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
270 (save-excursion
271 (end-of-line)
272 ;; Footnotes definitions are separated by new headlines, another
273 ;; footnote definition or 2 blank lines.
274 (let ((lim (save-excursion
275 (re-search-backward
276 (concat org-outline-regexp-bol
277 "\\|^\\([ \t]*\n\\)\\{2,\\}") nil t))))
278 (when (re-search-backward org-footnote-definition-re lim t)
279 (let ((label (org-match-string-no-properties 1))
280 (beg (match-beginning 0))
281 (beg-def (match-end 0))
282 ;; In message-mode, do not search after signature.
283 (end (let ((bound (and (derived-mode-p 'message-mode)
284 (save-excursion
285 (goto-char (point-max))
286 (re-search-backward
287 message-signature-separator nil t)))))
288 (if (progn
289 (end-of-line)
290 (re-search-forward
291 (concat org-outline-regexp-bol "\\|"
292 org-footnote-definition-re "\\|"
293 "^\\([ \t]*\n\\)\\{2,\\}") bound 'move))
294 (match-beginning 0)
295 (point)))))
296 (list label beg end
297 (org-trim (buffer-substring-no-properties beg-def end)))))))))
299 (defun org-footnote-get-next-reference (&optional label backward limit)
300 "Return complete reference of the next footnote.
302 If LABEL is provided, get the next reference of that footnote. If
303 BACKWARD is non-nil, find previous reference instead. LIMIT is
304 the buffer position bounding the search.
306 Return value is a list like those provided by `org-footnote-at-reference-p'.
307 If no footnote is found, return nil."
308 (save-excursion
309 (let* ((label-fmt (if label (format "\\[%s[]:]" label) org-footnote-re)))
310 (catch 'exit
311 (while t
312 (unless (funcall (if backward #'re-search-backward #'re-search-forward)
313 label-fmt limit t)
314 (throw 'exit nil))
315 (unless backward (backward-char))
316 (let ((ref (org-footnote-at-reference-p)))
317 (when ref (throw 'exit ref))))))))
319 (defun org-footnote-next-reference-or-definition (limit)
320 "Move point to next footnote reference or definition.
322 LIMIT is the buffer position bounding the search.
324 Return value is a list like those provided by
325 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
326 If no footnote is found, return nil."
327 (let* (ref (origin (point)))
328 (catch 'exit
329 (while t
330 (unless (re-search-forward org-footnote-re limit t)
331 (goto-char origin)
332 (throw 'exit nil))
333 ;; Beware: with [1]-like footnotes point will be just after
334 ;; the closing square bracket.
335 (backward-char)
336 (cond
337 ((setq ref (org-footnote-at-reference-p))
338 (throw 'exit ref))
339 ;; Definition: also grab the last square bracket, only
340 ;; matched in `org-footnote-re' for [1]-like footnotes.
341 ((save-match-data (org-footnote-at-definition-p))
342 (let ((end (match-end 0)))
343 (throw 'exit
344 (list nil (match-beginning 0)
345 (if (eq (char-before end) 93) end (1+ end)))))))))))
347 (defun org-footnote-get-definition (label)
348 "Return label, boundaries and definition of the footnote LABEL."
349 (let* ((label (regexp-quote (org-footnote-normalize-label label)))
350 (re (format "^\\[%s\\]\\|.\\[%s:" label label)))
351 (org-with-wide-buffer
352 (goto-char (point-min))
353 (catch 'found
354 (while (re-search-forward re nil t)
355 (let* ((datum (progn (backward-char) (org-element-context)))
356 (type (org-element-type datum)))
357 (when (memq type '(footnote-definition footnote-reference))
358 (throw 'found
359 (list
360 label
361 (org-element-property :begin datum)
362 (org-element-property :end datum)
363 (let ((cbeg (org-element-property :contents-begin datum)))
364 (if (not cbeg) ""
365 (replace-regexp-in-string
366 "[ \t\n]*\\'"
368 (buffer-substring-no-properties
369 cbeg
370 (org-element-property :contents-end datum))))))))))
371 nil))))
373 (defun org-footnote-goto-definition (label &optional location)
374 "Move point to the definition of the footnote LABEL.
376 LOCATION, when non-nil specifies the buffer position of the
377 definition.
379 Throw an error if there is no definition or if it cannot be
380 reached from current narrowed part of buffer. Return a non-nil
381 value if point was successfully moved."
382 (interactive "sLabel: ")
383 (let ((def-start (or location (nth 1 (org-footnote-get-definition label)))))
384 (cond
385 ((not def-start)
386 (user-error "Cannot find definition of footnote %s" label))
387 ((or (> def-start (point-max)) (< def-start (point-min)))
388 (user-error "Definition is outside narrowed part of buffer")))
389 (org-mark-ring-push)
390 (goto-char def-start)
391 (looking-at (format "\\[%s[]:] ?" label))
392 (goto-char (match-end 0))
393 (org-show-context 'link-search)
394 (when (derived-mode-p 'org-mode)
395 (message
396 (substitute-command-keys
397 "Edit definition and go back with `\\[org-mark-ring-goto]' or, if \
398 unique, with `\\[org-ctrl-c-ctrl-c]'.")))
401 (defun org-footnote-goto-previous-reference (label)
402 "Find the first closest (to point) reference of footnote with label LABEL."
403 (interactive "sLabel: ")
404 (org-mark-ring-push)
405 (let* ((label (org-footnote-normalize-label label)) ref)
406 (save-excursion
407 (setq ref (or (org-footnote-get-next-reference label t)
408 (org-footnote-get-next-reference label)
409 (save-restriction
410 (widen)
412 (org-footnote-get-next-reference label t)
413 (org-footnote-get-next-reference label))))))
414 (if (not ref)
415 (error "Cannot find reference of footnote %s" label)
416 (goto-char (nth 1 ref))
417 (org-show-context 'link-search))))
419 (defun org-footnote-normalize-label (label)
420 "Return LABEL as an appropriate string."
421 (cond
422 ((numberp label) (number-to-string label))
423 ((equal "" label) nil)
424 ((not (string-match "^[0-9]+$\\|^fn:" label))
425 (concat "fn:" label))
426 (t label)))
428 (defun org-footnote-all-labels (&optional with-defs)
429 "Return list with all defined foot labels used in the buffer.
431 If WITH-DEFS is non-nil, also associate the definition to each
432 label. The function will then return an alist whose key is label
433 and value definition."
434 (let* (rtn
435 (push-to-rtn
436 (function
437 ;; Depending on WITH-DEFS, store label or (label . def) of
438 ;; footnote reference/definition given as argument in RTN.
439 (lambda (el)
440 (let ((lbl (car el)))
441 (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
442 (save-excursion
443 (save-restriction
444 (widen)
445 ;; Find all labels found in definitions.
446 (goto-char (point-min))
447 (let (def)
448 (while (re-search-forward org-footnote-definition-re nil t)
449 (when (setq def (org-footnote-at-definition-p))
450 (funcall push-to-rtn def))))
451 ;; Find all labels found in references.
452 (goto-char (point-min))
453 (let (ref)
454 (while (setq ref (org-footnote-get-next-reference))
455 (goto-char (nth 2 ref))
456 (and (car ref) ; ignore anonymous footnotes
457 (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
458 (funcall push-to-rtn ref))))))
459 rtn))
461 (defun org-footnote-unique-label (&optional current)
462 "Return a new unique footnote label.
464 The function returns the first \"fn:N\" or \"N\" label that is
465 currently not used.
467 Optional argument CURRENT is the list of labels active in the
468 buffer."
469 (unless current (setq current (org-footnote-all-labels)))
470 (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
471 (cnt 1))
472 (while (member (format fmt cnt) current)
473 (incf cnt))
474 (format fmt cnt)))
476 (defun org-footnote--allow-reference-p ()
477 "Non-nil when a footnote reference can be inserted at point."
478 ;; XXX: This is similar to `org-footnote-in-valid-context-p' but
479 ;; more accurate and usually faster, except in some corner cases.
480 ;; It may replace it after doing proper benchmarks as it would be
481 ;; used in fontification.
482 (unless (bolp)
483 (let* ((context (org-element-context))
484 (type (org-element-type context)))
485 (cond
486 ;; No footnote reference in attributes.
487 ((let ((post (org-element-property :post-affiliated context)))
488 (and post (< (point) post)))
489 nil)
490 ;; Paragraphs and blank lines at top of document are fine.
491 ((memq type '(nil paragraph)))
492 ;; So are contents of verse blocks.
493 ((eq type 'verse-block)
494 (and (>= (point) (org-element-property :contents-begin context))
495 (< (point) (org-element-property :contents-end context))))
496 ;; In an headline or inlinetask, point must be either on the
497 ;; heading itself or on the blank lines below.
498 ((memq type '(headline inlinetask))
499 (or (not (org-at-heading-p))
500 (and (save-excursion (beginning-of-line)
501 (and (let ((case-fold-search t))
502 (not (looking-at "\\*+ END[ \t]*$")))
503 (looking-at org-complex-heading-regexp)))
504 (match-beginning 4)
505 (>= (point) (match-beginning 4))
506 (or (not (match-beginning 5))
507 (< (point) (match-beginning 5))))))
508 ;; White spaces after an object or blank lines after an element
509 ;; are OK.
510 ((>= (point)
511 (save-excursion (goto-char (org-element-property :end context))
512 (skip-chars-backward " \r\t\n")
513 (if (memq type org-element-all-objects) (point)
514 (1+ (line-beginning-position 2))))))
515 ;; Other elements are invalid.
516 ((memq type org-element-all-elements) nil)
517 ;; Just before object is fine.
518 ((= (point) (org-element-property :begin context)))
519 ;; Within recursive object too, but not in a link.
520 ((eq type 'link) nil)
521 ((let ((cbeg (org-element-property :contents-begin context))
522 (cend (org-element-property :contents-end context)))
523 (and cbeg (>= (point) cbeg) (<= (point) cend))))))))
525 (defun org-footnote-new ()
526 "Insert a new footnote.
527 This command prompts for a label. If this is a label referencing an
528 existing label, only insert the label. If the footnote label is empty
529 or new, let the user edit the definition of the footnote."
530 (interactive)
531 (unless (org-footnote--allow-reference-p)
532 (user-error "Cannot insert a footnote here"))
533 (let* ((all (org-footnote-all-labels))
534 (label
535 (org-footnote-normalize-label
536 (if (eq org-footnote-auto-label 'random)
537 (format "fn:%x" (random #x100000000))
538 (let ((propose (org-footnote-unique-label all)))
539 (if (memq org-footnote-auto-label '(t plain)) propose
540 (org-icompleting-read
541 "Label (leave empty for anonymous): "
542 (mapcar #'list all) nil nil
543 (and (eq org-footnote-auto-label 'confirm) propose))))))))
544 (cond ((not label)
545 (insert "[fn::]")
546 (backward-char 1))
547 ((member label all)
548 (insert "[" label "]")
549 (message "New reference to existing note"))
550 (org-footnote-define-inline
551 (insert "[" label ":]")
552 (backward-char 1)
553 (org-footnote-auto-adjust-maybe))
555 (insert "[" label "]")
556 (let ((p (org-footnote-create-definition label)))
557 ;; `org-footnote-goto-definition' needs to be called
558 ;; after `org-footnote-auto-adjust-maybe'. Otherwise
559 ;; both label and location of the definition are lost.
560 ;; On the contrary, it needs to be called before
561 ;; `org-edit-footnote-reference' so that the remote
562 ;; editing buffer can display the correct label.
563 (if (ignore-errors (org-footnote-goto-definition label p))
564 (org-footnote-auto-adjust-maybe)
565 ;; Definition was created outside current scope: edit
566 ;; it remotely.
567 (org-footnote-auto-adjust-maybe)
568 (org-edit-footnote-reference)))))))
570 (defvar electric-indent-mode)
571 (defvar org-blank-before-new-entry) ; Silence byte-compiler.
572 (defun org-footnote-create-definition (label)
573 "Start the definition of a footnote with label LABEL.
574 Return buffer position at the beginning of the definition. In an
575 Org buffer, this function doesn't move point."
576 (let ((label (org-footnote-normalize-label label))
577 electric-indent-mode) ; Prevent wrong indentation.
578 (cond
579 ;; In an Org document.
580 ((derived-mode-p 'org-mode)
581 ;; If `org-footnote-section' is defined, find it, or create it
582 ;; at the end of the buffer.
583 (org-with-wide-buffer
584 (cond
585 ((not org-footnote-section)
586 (org-footnote--goto-local-insertion-point))
587 ((save-excursion
588 (goto-char (point-min))
589 (re-search-forward
590 (concat "^\\*+[ \t]+" (regexp-quote org-footnote-section) "[ \t]*$")
591 nil t))
592 (goto-char (match-end 0))
593 (forward-line)
594 (unless (bolp) (insert "\n")))
596 (goto-char (point-max))
597 (unless (bolp) (insert "\n"))
598 ;; Insert new section. Separate it from the previous one
599 ;; with a blank line, unless `org-blank-before-new-entry'
600 ;; explicitly says no.
601 (when (and (cdr (assq 'heading org-blank-before-new-entry))
602 (zerop (save-excursion (org-back-over-empty-lines))))
603 (insert "\n"))
604 (insert "* " org-footnote-section "\n")))
605 (when (zerop (org-back-over-empty-lines)) (insert "\n"))
606 (insert "[" label "] \n")
607 (line-beginning-position 0)))
609 ;; In a non-Org file. Search for footnote tag, or create it if
610 ;; specified (at the end of buffer, or before signature if in
611 ;; Message mode). Set point after any definition already there.
612 (let ((tag (and org-footnote-tag-for-non-org-mode-files
613 (concat "^" (regexp-quote
614 org-footnote-tag-for-non-org-mode-files)
615 "[ \t]*$")))
616 (max (if (and (derived-mode-p 'message-mode)
617 (goto-char (point-max))
618 (re-search-backward
619 message-signature-separator nil t))
620 (progn
621 ;; Ensure one blank line separates last
622 ;; footnote from signature.
623 (beginning-of-line)
624 (open-line 2)
625 (point-marker))
626 (point-max-marker))))
627 (set-marker-insertion-type max t)
628 (goto-char max)
629 ;; Check if the footnote tag is defined but missing. In this
630 ;; case, insert it, before any footnote or one blank line
631 ;; after any previous text.
632 (when (and tag (not (re-search-backward tag nil t)))
633 (skip-chars-backward " \t\r\n")
634 (while (re-search-backward org-footnote-definition-re nil t))
635 (unless (bolp) (newline 2))
636 (insert org-footnote-tag-for-non-org-mode-files "\n\n"))
637 ;; Remove superfluous white space and clear marker.
638 (goto-char max)
639 (skip-chars-backward " \t\r\n")
640 (delete-region (point) max)
641 (unless (bolp) (newline))
642 (set-marker max nil))
643 (when (zerop (org-back-over-empty-lines)) (insert "\n"))
644 (insert "[" label "] \n")
645 (backward-char)
646 (line-beginning-position)))))
648 ;;;###autoload
649 (defun org-footnote-action (&optional special)
650 "Do the right thing for footnotes.
652 When at a footnote reference, jump to the definition.
654 When at a definition, jump to the references if they exist, offer
655 to create them otherwise.
657 When neither at definition or reference, create a new footnote,
658 interactively if possible.
660 With prefix arg SPECIAL, or when no footnote can be created,
661 offer additional commands in a menu."
662 (interactive "P")
663 (let* ((context (and (not special) (org-element-context)))
664 (type (org-element-type context)))
665 (cond
666 ;; On white space after element, insert a new footnote.
667 ((and context
668 (> (point)
669 (save-excursion
670 (goto-char (org-element-property :end context))
671 (skip-chars-backward " \t")
672 (point))))
673 (org-footnote-new))
674 ((eq type 'footnote-reference)
675 (let ((label (org-element-property :label context)))
676 (cond
677 ;; Anonymous footnote: move point at the beginning of its
678 ;; definition.
679 ((not label)
680 (goto-char (org-element-property :contents-begin context)))
681 ;; Check if a definition exists: then move to it.
682 ((let ((p (nth 1 (org-footnote-get-definition label))))
683 (when p (org-footnote-goto-definition label p))))
684 ;; No definition exists: offer to create it.
685 ((yes-or-no-p (format "No definition for %s. Create one? " label))
686 (let ((p (org-footnote-create-definition label)))
687 (or (ignore-errors (org-footnote-goto-definition label p))
688 ;; Since definition was created outside current scope,
689 ;; edit it remotely.
690 (org-edit-footnote-reference)))))))
691 ((eq type 'footnote-definition)
692 (org-footnote-goto-previous-reference
693 (org-element-property :label context)))
694 ((or special (not (org-footnote--allow-reference-p)))
695 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s | \
696 ->[n]umeric | [d]elete")
697 (let ((c (read-char-exclusive)))
698 (cond
699 ((eq c ?s) (org-footnote-normalize 'sort))
700 ((eq c ?r) (org-footnote-renumber-fn:N))
701 ((eq c ?S)
702 (org-footnote-renumber-fn:N)
703 (org-footnote-normalize 'sort))
704 ((eq c ?n) (org-footnote-normalize))
705 ((eq c ?d) (org-footnote-delete))
706 (t (error "No such footnote command %c" c)))))
707 (t (org-footnote-new)))))
709 ;;;###autoload
710 (defun org-footnote-normalize (&optional sort-only)
711 "Collect the footnotes in various formats and normalize them.
713 This finds the different sorts of footnotes allowed in Org, and
714 normalizes them to the usual [N] format.
716 When SORT-ONLY is set, only sort the footnote definitions into the
717 referenced sequence."
718 ;; This is based on Paul's function, but rewritten.
720 ;; Re-create `org-with-limited-levels', but not limited to Org
721 ;; buffers.
722 (let* ((limit-level
723 (and (boundp 'org-inlinetask-min-level)
724 org-inlinetask-min-level
725 (1- org-inlinetask-min-level)))
726 (nstars (and limit-level
727 (if org-odd-levels-only (1- (* limit-level 2))
728 limit-level)))
729 (org-outline-regexp
730 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
731 (count 0)
732 ins-point ref ref-table)
733 (org-with-wide-buffer
734 ;; 1. Find every footnote reference, extract the definition, and
735 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
736 ;; normalize references.
737 (goto-char (point-min))
738 (while (setq ref (org-footnote-get-next-reference))
739 (let* ((lbl (car ref))
740 (pos (nth 1 ref))
741 ;; When footnote isn't anonymous, check if it's label
742 ;; (REF) is already stored in REF-TABLE. In that case,
743 ;; extract number used to identify it (MARKER). If
744 ;; footnote is unknown, increment the global counter
745 ;; (COUNT) to create an unused identifier.
746 (a (and lbl (assoc lbl ref-table)))
747 (marker (or (nth 1 a) (incf count)))
748 ;; Is the reference inline or pointing to an inline
749 ;; footnote?
750 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
751 ;; Replace footnote reference with [MARKER]. Maybe fill
752 ;; paragraph once done. If SORT-ONLY is non-nil, only move
753 ;; to the end of reference found to avoid matching it twice.
754 (if sort-only (goto-char (nth 2 ref))
755 (delete-region (nth 1 ref) (nth 2 ref))
756 (goto-char (nth 1 ref))
757 (insert (format "[%d]" marker))
758 (and inlinep
759 org-footnote-fill-after-inline-note-extraction
760 (org-fill-paragraph)))
761 ;; Add label (REF), identifier (MARKER), definition (DEF)
762 ;; type (INLINEP) and position (POS) to REF-TABLE if data was
763 ;; unknown.
764 (unless a
765 (let ((def (or (nth 3 ref) ; Inline definition.
766 (nth 3 (org-footnote-get-definition lbl)))))
767 (push (list lbl marker def
768 ;; Reference beginning position is a marker
769 ;; to preserve it during further buffer
770 ;; modifications.
771 inlinep (copy-marker pos)) ref-table)))))
772 ;; 2. Find and remove the footnote section, if any. Also
773 ;; determine where footnotes shall be inserted (INS-POINT).
774 (cond
775 ((and org-footnote-section (derived-mode-p 'org-mode))
776 (goto-char (point-min))
777 (if (re-search-forward
778 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
779 "[ \t]*$") nil t)
780 (delete-region (match-beginning 0) (org-end-of-subtree t t)))
781 ;; A new footnote section is inserted by default at the end of
782 ;; the buffer.
783 (goto-char (point-max))
784 (skip-chars-backward " \r\t\n")
785 (forward-line)
786 (unless (bolp) (newline)))
787 ;; No footnote section set: Footnotes will be added at the end
788 ;; of the section containing their first reference.
789 ((derived-mode-p 'org-mode))
791 ;; Remove any left-over tag in the buffer, if one is set up.
792 (when org-footnote-tag-for-non-org-mode-files
793 (let ((tag (concat "^" (regexp-quote
794 org-footnote-tag-for-non-org-mode-files)
795 "[ \t]*$")))
796 (goto-char (point-min))
797 (while (re-search-forward tag nil t)
798 (replace-match "")
799 (delete-region (point) (progn (forward-line) (point))))))
800 ;; In Message mode, ensure footnotes are inserted before the
801 ;; signature.
802 (if (and (derived-mode-p 'message-mode)
803 (goto-char (point-max))
804 (re-search-backward message-signature-separator nil t))
805 (beginning-of-line)
806 (goto-char (point-max)))))
807 (setq ins-point (point-marker))
808 ;; 3. Clean-up REF-TABLE.
809 (setq ref-table
810 (delq nil
811 (mapcar
812 (lambda (x)
813 (cond
814 ;; When only sorting, ignore inline footnotes.
815 ;; Also clear position marker.
816 ((and sort-only (nth 3 x))
817 (set-marker (nth 4 x) nil) nil)
818 ;; No definition available: provide one.
819 ((not (nth 2 x))
820 (append
821 (list (car x) (nth 1 x)
822 (format "DEFINITION NOT FOUND: %s" (car x)))
823 (nthcdr 3 x)))
824 (t x)))
825 ref-table)))
826 (setq ref-table (nreverse ref-table))
827 ;; 4. Remove left-over definitions in the buffer.
828 (dolist (x ref-table)
829 (unless (nth 3 x) (org-footnote-delete-definitions (car x))))
830 ;; 5. Insert the footnotes again in the buffer, at the
831 ;; appropriate spot.
832 (goto-char ins-point)
833 (cond
834 ;; No footnote: exit.
835 ((not ref-table))
836 ;; Cases when footnotes should be inserted in one place.
837 ((or (not (derived-mode-p 'org-mode)) org-footnote-section)
838 ;; Insert again the section title, if any. Ensure that title,
839 ;; or the subsequent footnotes, will be separated by a blank
840 ;; lines from the rest of the document. In an Org buffer,
841 ;; separate section with a blank line, unless explicitly stated
842 ;; in `org-blank-before-new-entry'.
843 (if (not (derived-mode-p 'org-mode))
844 (progn (skip-chars-backward " \t\n\r")
845 (delete-region (point) ins-point)
846 (unless (bolp) (newline))
847 (when org-footnote-tag-for-non-org-mode-files
848 (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
849 (when (and (cdr (assq 'heading org-blank-before-new-entry))
850 (zerop (save-excursion (org-back-over-empty-lines))))
851 (insert "\n"))
852 (insert "* " org-footnote-section "\n"))
853 (set-marker ins-point nil)
854 ;; Insert the footnotes, separated by a blank line.
855 (insert
856 (mapconcat
857 (lambda (x)
858 ;; Clean markers.
859 (set-marker (nth 4 x) nil)
860 (format "\n[%s] %s" (nth (if sort-only 0 1) x) (nth 2 x)))
861 ref-table "\n"))
862 (unless (eobp) (insert "\n\n")))
863 ;; Each footnote definition has to be inserted at the end of the
864 ;; section where its first reference belongs.
866 (dolist (x ref-table)
867 (let ((pos (nth 4 x)))
868 (goto-char pos)
869 ;; Clean marker.
870 (set-marker pos nil))
871 (org-footnote--goto-local-insertion-point)
872 (insert (format "\n[%s] %s\n"
873 (nth (if sort-only 0 1) x)
874 (nth 2 x)))))))))
876 (defun org-footnote--goto-local-insertion-point ()
877 "Find insertion point for footnote, just before next outline heading.
878 Assume insertion point is within currently accessible part of the buffer."
879 (org-with-limited-levels (outline-next-heading))
880 ;; Skip file local variables. See `modify-file-local-variable'.
881 (when (eobp)
882 (let ((case-fold-search t))
883 (re-search-backward "^[ \t]*# +Local Variables:"
884 (max (- (point-max) 3000) (point-min))
885 t)))
886 (skip-chars-backward " \t\n")
887 (forward-line)
888 (unless (bolp) (insert "\n")))
890 (defun org-footnote-delete-references (label)
891 "Delete every reference to footnote LABEL.
892 Return the number of footnotes removed."
893 (save-excursion
894 (goto-char (point-min))
895 (let (ref (nref 0))
896 (while (setq ref (org-footnote-get-next-reference label))
897 (goto-char (nth 1 ref))
898 (delete-region (nth 1 ref) (nth 2 ref))
899 (incf nref))
900 nref)))
902 (defun org-footnote-delete-definitions (label)
903 "Delete every definition of the footnote LABEL.
904 Return the number of footnotes removed."
905 (save-excursion
906 (goto-char (point-min))
907 (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
908 (ndef 0))
909 (while (re-search-forward def-re nil t)
910 (let ((full-def (org-footnote-at-definition-p)))
911 (when full-def
912 ;; Remove the footnote, and all blank lines before it.
913 (goto-char (nth 1 full-def))
914 (skip-chars-backward " \r\t\n")
915 (unless (bolp) (forward-line))
916 (delete-region (point) (nth 2 full-def))
917 (incf ndef))))
918 ndef)))
920 (defun org-footnote-delete (&optional label)
921 "Delete the footnote at point.
922 This will remove the definition (even multiple definitions if they exist)
923 and all references of a footnote label.
925 If LABEL is non-nil, delete that footnote instead."
926 (catch 'done
927 (let* ((nref 0) (ndef 0) x
928 ;; 1. Determine LABEL of footnote at point.
929 (label (cond
930 ;; LABEL is provided as argument.
931 (label)
932 ;; Footnote reference at point. If the footnote is
933 ;; anonymous, delete it and exit instead.
934 ((setq x (org-footnote-at-reference-p))
935 (or (car x)
936 (progn
937 (delete-region (nth 1 x) (nth 2 x))
938 (message "Anonymous footnote removed")
939 (throw 'done t))))
940 ;; Footnote definition at point.
941 ((setq x (org-footnote-at-definition-p))
942 (car x))
943 (t (error "Don't know which footnote to remove")))))
944 ;; 2. Now that LABEL is non-nil, find every reference and every
945 ;; definition, and delete them.
946 (setq nref (org-footnote-delete-references label)
947 ndef (org-footnote-delete-definitions label))
948 ;; 3. Verify consistency of footnotes and notify user.
949 (org-footnote-auto-adjust-maybe)
950 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
951 ndef nref label))))
953 (defun org-footnote-renumber-fn:N ()
954 "Renumber the simple footnotes like fn:17 into a sequence in the document."
955 (interactive)
956 (let (map (n 0))
957 (org-with-wide-buffer
958 (goto-char (point-min))
959 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
960 (save-excursion
961 (goto-char (match-beginning 0))
962 ;; Ensure match is a footnote reference or definition.
963 (when (save-match-data (if (bolp)
964 (org-footnote-at-definition-p)
965 (org-footnote-at-reference-p)))
966 (let ((new-val (or (cdr (assoc (match-string 1) map))
967 (number-to-string (incf n)))))
968 (unless (assoc (match-string 1) map)
969 (push (cons (match-string 1) new-val) map))
970 (replace-match new-val nil nil nil 1))))))))
972 (defun org-footnote-auto-adjust-maybe ()
973 "Renumber and/or sort footnotes according to user settings."
974 (when (memq org-footnote-auto-adjust '(t renumber))
975 (org-footnote-renumber-fn:N))
976 (when (memq org-footnote-auto-adjust '(t sort))
977 (let ((label (car (org-footnote-at-definition-p))))
978 (org-footnote-normalize 'sort)
979 (when label
980 (goto-char (point-min))
981 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
982 nil t)
983 (progn (insert " ")
984 (just-one-space)))))))
986 (provide 'org-footnote)
988 ;; Local variables:
989 ;; generated-autoload-file: "org-loaddefs.el"
990 ;; End:
992 ;;; org-footnote.el ends here