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