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