org-footnote: Fix 5954f6aa25b51a3a9a8f258fb0f15ef51be31366
[org-mode.git] / lisp / org-footnote.el
blob679b47f27d09f0fa30783bdfd4836a72d8014854
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 pos)
346 (save-excursion
347 (save-restriction
348 (when (or (re-search-forward re nil t)
349 (and (goto-char (point-min))
350 (re-search-forward re nil t))
351 (and (progn (widen) t)
352 (goto-char (point-min))
353 (re-search-forward re nil t)))
354 (let ((refp (org-footnote-at-reference-p)))
355 (cond
356 ((and (nth 3 refp) refp))
357 ((org-footnote-at-definition-p)))))))))
359 (defun org-footnote-goto-definition (label)
360 "Move point to the definition of the footnote LABEL.
361 Return a non-nil value when a definition has been found."
362 (interactive "sLabel: ")
363 (let ((def-start (nth 1 (org-footnote-get-definition label))))
364 (cond
365 ((not def-start)
366 (user-error "Cannot find definition of footnote %s" label))
367 ((or (> def-start (point-max))
368 (< def-start (point-min)))
369 (user-error "Footnote definition outside of narrowed part of buffer"))
371 (org-mark-ring-push)
372 (goto-char def-start)
373 (looking-at (format "\\[%s[]:]" label))
374 (goto-char (match-end 0))
375 (org-show-context 'link-search)
376 (when (derived-mode-p 'org-mode)
377 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))
378 t))))
380 (defun org-footnote-goto-previous-reference (label)
381 "Find the first closest (to point) reference of footnote with label LABEL."
382 (interactive "sLabel: ")
383 (org-mark-ring-push)
384 (let* ((label (org-footnote-normalize-label label)) ref)
385 (save-excursion
386 (setq ref (or (org-footnote-get-next-reference label t)
387 (org-footnote-get-next-reference label)
388 (save-restriction
389 (widen)
391 (org-footnote-get-next-reference label t)
392 (org-footnote-get-next-reference label))))))
393 (if (not ref)
394 (error "Cannot find reference of footnote %s" label)
395 (goto-char (nth 1 ref))
396 (org-show-context 'link-search))))
398 (defun org-footnote-normalize-label (label)
399 "Return LABEL as an appropriate string."
400 (cond
401 ((numberp label) (number-to-string label))
402 ((equal "" label) nil)
403 ((not (string-match "^[0-9]+$\\|^fn:" label))
404 (concat "fn:" label))
405 (t label)))
407 (defun org-footnote-all-labels (&optional with-defs)
408 "Return list with all defined foot labels used in the buffer.
410 If WITH-DEFS is non-nil, also associate the definition to each
411 label. The function will then return an alist whose key is label
412 and value definition."
413 (let* (rtn
414 (push-to-rtn
415 (function
416 ;; Depending on WITH-DEFS, store label or (label . def) of
417 ;; footnote reference/definition given as argument in RTN.
418 (lambda (el)
419 (let ((lbl (car el)))
420 (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
421 (save-excursion
422 (save-restriction
423 (widen)
424 ;; Find all labels found in definitions.
425 (goto-char (point-min))
426 (let (def)
427 (while (re-search-forward org-footnote-definition-re nil t)
428 (when (setq def (org-footnote-at-definition-p))
429 (funcall push-to-rtn def))))
430 ;; Find all labels found in references.
431 (goto-char (point-min))
432 (let (ref)
433 (while (setq ref (org-footnote-get-next-reference))
434 (goto-char (nth 2 ref))
435 (and (car ref) ; ignore anonymous footnotes
436 (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
437 (funcall push-to-rtn ref))))))
438 rtn))
440 (defun org-footnote-unique-label (&optional current)
441 "Return a new unique footnote label.
443 The function returns the first \"fn:N\" or \"N\" label that is
444 currently not used.
446 Optional argument CURRENT is the list of labels active in the
447 buffer."
448 (unless current (setq current (org-footnote-all-labels)))
449 (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
450 (cnt 1))
451 (while (member (format fmt cnt) current)
452 (incf cnt))
453 (format fmt cnt)))
455 (defun org-footnote--allow-reference-p ()
456 "Non-nil when a footnote reference can be inserted at point."
457 ;; XXX: This is similar to `org-footnote-in-valid-context-p' but
458 ;; more accurate and usually faster, except in some corner cases.
459 ;; It may replace it after doing proper benchmarks as it would be
460 ;; used in fontification.
461 (unless (bolp)
462 (let* ((context (org-element-context))
463 (type (org-element-type context)))
464 (cond
465 ;; No footnote reference in attributes.
466 ((let ((post (org-element-property :post-affiliated context)))
467 (and post (< (point) post)))
468 nil)
469 ;; Paragraphs and blank lines at top of document are fine.
470 ((memq type '(nil paragraph)))
471 ;; So are contents of verse blocks.
472 ((eq type 'verse-block)
473 (and (>= (point) (org-element-property :contents-begin context))
474 (< (point) (org-element-property :contents-end context))))
475 ;; In an headline or inlinetask, point must be either on the
476 ;; heading itself or on the blank lines below.
477 ((memq type '(headline inlinetask))
478 (or (not (org-at-heading-p))
479 (and (save-excursion (beginning-of-line)
480 (and (let ((case-fold-search t))
481 (not (looking-at "\\*+ END[ \t]*$")))
482 (looking-at org-complex-heading-regexp)))
483 (match-beginning 4)
484 (>= (point) (match-beginning 4))
485 (or (not (match-beginning 5))
486 (< (point) (match-beginning 5))))))
487 ;; White spaces after an object or blank lines after an element
488 ;; are OK.
489 ((>= (point)
490 (save-excursion (goto-char (org-element-property :end context))
491 (skip-chars-backward " \r\t\n")
492 (if (memq type org-element-all-objects) (point)
493 (1+ (line-beginning-position 2))))))
494 ;; Other elements are invalid.
495 ((memq type org-element-all-elements) nil)
496 ;; Just before object is fine.
497 ((= (point) (org-element-property :begin context)))
498 ;; Within recursive object too, but not in a link.
499 ((eq type 'link) nil)
500 ((let ((cbeg (org-element-property :contents-begin context))
501 (cend (org-element-property :contents-end context)))
502 (and cbeg (>= (point) cbeg) (<= (point) cend))))))))
504 (defun org-footnote-new ()
505 "Insert a new footnote.
506 This command prompts for a label. If this is a label referencing an
507 existing label, only insert the label. If the footnote label is empty
508 or new, let the user edit the definition of the footnote."
509 (interactive)
510 (unless (org-footnote--allow-reference-p)
511 (user-error "Cannot insert a footnote here"))
512 (let* ((all (org-footnote-all-labels))
513 (label
514 (org-footnote-normalize-label
515 (if (eq org-footnote-auto-label 'random)
516 (format "fn:%x" (random #x100000000))
517 (let ((propose (org-footnote-unique-label all)))
518 (if (memq org-footnote-auto-label '(t plain)) propose
519 (org-icompleting-read
520 "Label (leave empty for anonymous): "
521 (mapcar #'list all) nil nil
522 (and (eq org-footnote-auto-label 'confirm) propose))))))))
523 (cond ((not label)
524 (insert "[fn:: ]")
525 (backward-char 1))
526 ((member label all)
527 (insert "[" label "]")
528 (message "New reference to existing note"))
529 (org-footnote-define-inline
530 (insert "[" label ": ]")
531 (backward-char 1)
532 (org-footnote-auto-adjust-maybe))
534 (insert "[" label "]")
535 (org-footnote-create-definition label)
536 (org-footnote-auto-adjust-maybe)))))
538 (defvar org-blank-before-new-entry) ; silence byte-compiler
539 (defun org-footnote-create-definition (label)
540 "Start the definition of a footnote with label LABEL."
541 (interactive "sLabel: ")
542 (let ((label (org-footnote-normalize-label label))
543 electric-indent-mode) ;; Prevent wrong indentation
544 (cond
545 ;; In an Org file.
546 ((derived-mode-p 'org-mode)
547 ;; If `org-footnote-section' is defined, find it, or create it
548 ;; at the end of the buffer.
549 (when org-footnote-section
550 (goto-char (point-min))
551 (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
552 (unless (or (re-search-forward re nil t)
553 (and (progn (widen) t)
554 (re-search-forward re nil t)))
555 (goto-char (point-max))
556 (skip-chars-backward " \t\r\n")
557 (unless (bolp) (newline))
558 ;; Insert new section. Separate it from the previous one
559 ;; with a blank line, unless `org-blank-before-new-entry'
560 ;; explicitly says no.
561 (when (and (cdr (assq 'heading org-blank-before-new-entry))
562 (zerop (save-excursion (org-back-over-empty-lines))))
563 (insert "\n"))
564 (insert "* " org-footnote-section "\n"))))
565 ;; Move to the end of this entry (which may be
566 ;; `org-footnote-section' or the current one).
567 (org-footnote-goto-local-insertion-point)
568 (org-show-context 'link-search))
570 ;; In a non-Org file. Search for footnote tag, or create it if
571 ;; specified (at the end of buffer, or before signature if in
572 ;; Message mode). Set point after any definition already there.
573 (let ((tag (and org-footnote-tag-for-non-org-mode-files
574 (concat "^" (regexp-quote
575 org-footnote-tag-for-non-org-mode-files)
576 "[ \t]*$")))
577 (max (if (and (derived-mode-p 'message-mode)
578 (goto-char (point-max))
579 (re-search-backward
580 message-signature-separator nil t))
581 (progn
582 ;; Ensure one blank line separates last
583 ;; footnote from signature.
584 (beginning-of-line)
585 (open-line 2)
586 (point-marker))
587 (point-max-marker))))
588 (set-marker-insertion-type max t)
589 (goto-char max)
590 ;; Check if the footnote tag is defined but missing. In this
591 ;; case, insert it, before any footnote or one blank line
592 ;; after any previous text.
593 (when (and tag (not (re-search-backward tag nil t)))
594 (skip-chars-backward " \t\r\n")
595 (while (re-search-backward org-footnote-definition-re nil t))
596 (unless (bolp) (newline 2))
597 (insert org-footnote-tag-for-non-org-mode-files "\n\n"))
598 ;; Remove superfluous white space and clear marker.
599 (goto-char max)
600 (skip-chars-backward " \t\r\n")
601 (delete-region (point) max)
602 (unless (bolp) (newline))
603 (set-marker max nil))))
604 ;; Insert footnote label.
605 (when (zerop (org-back-over-empty-lines)) (newline))
606 (insert "[" label "] \n")
607 (backward-char)
608 ;; Only notify user about next possible action when in an Org
609 ;; buffer, as the bindings may have different meanings otherwise.
610 (when (derived-mode-p 'org-mode)
611 (message
612 "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
614 ;;;###autoload
615 (defun org-footnote-action (&optional special)
616 "Do the right thing for footnotes.
618 When at a footnote reference, jump to the definition.
620 When at a definition, jump to the references if they exist, offer
621 to create them otherwise.
623 When neither at definition or reference, create a new footnote,
624 interactively if possible.
626 With prefix arg SPECIAL, or when no footnote can be created,
627 offer additional commands in a menu."
628 (interactive "P")
629 (let* ((context (and (not special) (org-element-context)))
630 (type (org-element-type context)))
631 (cond
632 ((eq type 'footnote-reference)
633 (let ((label (org-element-property :label context)))
634 (cond
635 ;; Anonymous footnote: move point at the beginning of its
636 ;; definition.
637 ((not label)
638 (goto-char (org-element-property :contents-begin context)))
639 ;; A definition exists: move to it.
640 ((ignore-errors (org-footnote-goto-definition label)))
641 ;; No definition exists: offer to create it.
642 ((yes-or-no-p (format "No definition for %s. Create one? " label))
643 (org-footnote-create-definition label)))))
644 ((eq type 'footnote-definition)
645 (org-footnote-goto-previous-reference
646 (org-element-property :label context)))
647 ((or special
648 (zerop (current-column))
649 (not (org-footnote-in-valid-context-p)))
650 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
651 (let ((c (read-char-exclusive)))
652 (cond
653 ((eq c ?s) (org-footnote-normalize 'sort))
654 ((eq c ?r) (org-footnote-renumber-fn:N))
655 ((eq c ?S)
656 (org-footnote-renumber-fn:N)
657 (org-footnote-normalize 'sort))
658 ((eq c ?n) (org-footnote-normalize))
659 ((eq c ?d) (org-footnote-delete))
660 (t (error "No such footnote command %c" c)))))
661 (t (org-footnote-new)))))
663 ;;;###autoload
664 (defun org-footnote-normalize (&optional sort-only)
665 "Collect the footnotes in various formats and normalize them.
667 This finds the different sorts of footnotes allowed in Org, and
668 normalizes them to the usual [N] format.
670 When SORT-ONLY is set, only sort the footnote definitions into the
671 referenced sequence."
672 ;; This is based on Paul's function, but rewritten.
674 ;; Re-create `org-with-limited-levels', but not limited to Org
675 ;; buffers.
676 (let* ((limit-level
677 (and (boundp 'org-inlinetask-min-level)
678 org-inlinetask-min-level
679 (1- org-inlinetask-min-level)))
680 (nstars (and limit-level
681 (if org-odd-levels-only (1- (* limit-level 2))
682 limit-level)))
683 (org-outline-regexp
684 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
685 (count 0)
686 ins-point ref ref-table)
687 (save-excursion
688 ;; 1. Find every footnote reference, extract the definition, and
689 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
690 ;; normalize references.
691 (goto-char (point-min))
692 (while (setq ref (org-footnote-get-next-reference))
693 (let* ((lbl (car ref))
694 (pos (nth 1 ref))
695 ;; When footnote isn't anonymous, check if it's label
696 ;; (REF) is already stored in REF-TABLE. In that case,
697 ;; extract number used to identify it (MARKER). If
698 ;; footnote is unknown, increment the global counter
699 ;; (COUNT) to create an unused identifier.
700 (a (and lbl (assoc lbl ref-table)))
701 (marker (or (nth 1 a) (incf count)))
702 ;; Is the reference inline or pointing to an inline
703 ;; footnote?
704 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
705 ;; Replace footnote reference with [MARKER]. Maybe fill
706 ;; paragraph once done. If SORT-ONLY is non-nil, only move
707 ;; to the end of reference found to avoid matching it twice.
708 (if sort-only (goto-char (nth 2 ref))
709 (delete-region (nth 1 ref) (nth 2 ref))
710 (goto-char (nth 1 ref))
711 (insert (format "[%d]" marker))
712 (and inlinep
713 org-footnote-fill-after-inline-note-extraction
714 (org-fill-paragraph)))
715 ;; Add label (REF), identifier (MARKER), definition (DEF)
716 ;; type (INLINEP) and position (POS) to REF-TABLE if data
717 ;; was unknown.
718 (unless a
719 (let ((def (or (nth 3 ref) ; Inline definition.
720 (nth 3 (org-footnote-get-definition lbl)))))
721 (push (list lbl marker def
722 ;; Reference beginning position is a marker
723 ;; to preserve it during further buffer
724 ;; modifications.
725 inlinep (copy-marker pos)) ref-table)))))
726 ;; 2. Find and remove the footnote section, if any. Also
727 ;; determine where footnotes shall be inserted (INS-POINT).
728 (cond
729 ((and org-footnote-section (derived-mode-p 'org-mode))
730 (goto-char (point-min))
731 (if (re-search-forward
732 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
733 "[ \t]*$") nil t)
734 (delete-region (match-beginning 0) (org-end-of-subtree t t)))
735 ;; A new footnote section is inserted by default at the end of
736 ;; the buffer.
737 (goto-char (point-max))
738 (skip-chars-backward " \r\t\n")
739 (forward-line)
740 (unless (bolp) (newline)))
741 ;; No footnote section set: Footnotes will be added at the end
742 ;; of the section containing their first reference.
743 ((derived-mode-p 'org-mode))
745 ;; Remove any left-over tag in the buffer, if one is set up.
746 (when org-footnote-tag-for-non-org-mode-files
747 (let ((tag (concat "^" (regexp-quote
748 org-footnote-tag-for-non-org-mode-files)
749 "[ \t]*$")))
750 (goto-char (point-min))
751 (while (re-search-forward tag nil t)
752 (replace-match "")
753 (delete-region (point) (progn (forward-line) (point))))))
754 ;; In Message mode, ensure footnotes are inserted before the
755 ;; signature.
756 (if (and (derived-mode-p 'message-mode)
757 (goto-char (point-max))
758 (re-search-backward message-signature-separator nil t))
759 (beginning-of-line)
760 (goto-char (point-max)))))
761 (setq ins-point (point-marker))
762 ;; 3. Clean-up REF-TABLE.
763 (setq ref-table
764 (delq nil
765 (mapcar
766 (lambda (x)
767 (cond
768 ;; When only sorting, ignore inline footnotes.
769 ;; Also clear position marker.
770 ((and sort-only (nth 3 x))
771 (set-marker (nth 4 x) nil) nil)
772 ;; No definition available: provide one.
773 ((not (nth 2 x))
774 (append
775 (list (car x) (nth 1 x)
776 (format "DEFINITION NOT FOUND: %s" (car x)))
777 (nthcdr 3 x)))
778 (t x)))
779 ref-table)))
780 (setq ref-table (nreverse ref-table))
781 ;; 4. Remove left-over definitions in the buffer.
782 (mapc (lambda (x)
783 (unless (nth 3 x) (org-footnote-delete-definitions (car x))))
784 ref-table)
785 ;; 5. Insert the footnotes again in the buffer, at the
786 ;; appropriate spot.
787 (goto-char ins-point)
788 (cond
789 ;; No footnote: exit.
790 ((not ref-table))
791 ;; Cases when footnotes should be inserted in one place.
792 ((or (not (derived-mode-p 'org-mode)) org-footnote-section)
793 ;; Insert again the section title, if any. Ensure that title,
794 ;; or the subsequent footnotes, will be separated by a blank
795 ;; lines from the rest of the document. In an Org buffer,
796 ;; separate section with a blank line, unless explicitly
797 ;; stated in `org-blank-before-new-entry'.
798 (if (not (derived-mode-p 'org-mode))
799 (progn (skip-chars-backward " \t\n\r")
800 (delete-region (point) ins-point)
801 (unless (bolp) (newline))
802 (when org-footnote-tag-for-non-org-mode-files
803 (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
804 (when (and (cdr (assq 'heading org-blank-before-new-entry))
805 (zerop (save-excursion (org-back-over-empty-lines))))
806 (insert "\n"))
807 (insert "* " org-footnote-section "\n"))
808 (set-marker ins-point nil)
809 ;; Insert the footnotes, separated by a blank line.
810 (insert
811 (mapconcat
812 (lambda (x)
813 ;; Clean markers.
814 (set-marker (nth 4 x) nil)
815 (format "\n[%s] %s" (nth (if sort-only 0 1) x) (nth 2 x)))
816 ref-table "\n"))
817 (unless (eobp) (insert "\n\n")))
818 ;; Each footnote definition has to be inserted at the end of
819 ;; the section where its first reference belongs.
821 (mapc
822 (lambda (x)
823 (let ((pos (nth 4 x)))
824 (goto-char pos)
825 ;; Clean marker.
826 (set-marker pos nil))
827 (org-footnote-goto-local-insertion-point)
828 (insert (format "\n[%s] %s\n"
829 (if sort-only (car x) (nth 1 x))
830 (nth 2 x))))
831 ref-table))))))
833 (defun org-footnote-goto-local-insertion-point ()
834 "Find insertion point for footnote, just before next outline heading."
835 (org-with-limited-levels (outline-next-heading))
836 (or (bolp) (newline))
837 (beginning-of-line 0)
838 (while (and (not (bobp)) (= (char-after) ?#))
839 (beginning-of-line 0))
840 (if (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:")) (beginning-of-line 2))
841 (end-of-line 1)
842 (skip-chars-backward "\n\r\t ")
843 (forward-line))
845 (defun org-footnote-delete-references (label)
846 "Delete every reference to footnote LABEL.
847 Return the number of footnotes removed."
848 (save-excursion
849 (goto-char (point-min))
850 (let (ref (nref 0))
851 (while (setq ref (org-footnote-get-next-reference label))
852 (goto-char (nth 1 ref))
853 (delete-region (nth 1 ref) (nth 2 ref))
854 (incf nref))
855 nref)))
857 (defun org-footnote-delete-definitions (label)
858 "Delete every definition of the footnote LABEL.
859 Return the number of footnotes removed."
860 (save-excursion
861 (goto-char (point-min))
862 (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
863 (ndef 0))
864 (while (re-search-forward def-re nil t)
865 (let ((full-def (org-footnote-at-definition-p)))
866 (when full-def
867 ;; Remove the footnote, and all blank lines before it.
868 (goto-char (nth 1 full-def))
869 (skip-chars-backward " \r\t\n")
870 (unless (bolp) (forward-line))
871 (delete-region (point) (nth 2 full-def))
872 (incf ndef))))
873 ndef)))
875 (defun org-footnote-delete (&optional label)
876 "Delete the footnote at point.
877 This will remove the definition (even multiple definitions if they exist)
878 and all references of a footnote label.
880 If LABEL is non-nil, delete that footnote instead."
881 (catch 'done
882 (let* ((nref 0) (ndef 0) x
883 ;; 1. Determine LABEL of footnote at point.
884 (label (cond
885 ;; LABEL is provided as argument.
886 (label)
887 ;; Footnote reference at point. If the footnote is
888 ;; anonymous, delete it and exit instead.
889 ((setq x (org-footnote-at-reference-p))
890 (or (car x)
891 (progn
892 (delete-region (nth 1 x) (nth 2 x))
893 (message "Anonymous footnote removed")
894 (throw 'done t))))
895 ;; Footnote definition at point.
896 ((setq x (org-footnote-at-definition-p))
897 (car x))
898 (t (error "Don't know which footnote to remove")))))
899 ;; 2. Now that LABEL is non-nil, find every reference and every
900 ;; definition, and delete them.
901 (setq nref (org-footnote-delete-references label)
902 ndef (org-footnote-delete-definitions label))
903 ;; 3. Verify consistency of footnotes and notify user.
904 (org-footnote-auto-adjust-maybe)
905 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
906 ndef nref label))))
908 (defun org-footnote-renumber-fn:N ()
909 "Renumber the simple footnotes like fn:17 into a sequence in the document."
910 (interactive)
911 (let (map (n 0))
912 (org-with-wide-buffer
913 (goto-char (point-min))
914 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
915 (save-excursion
916 (goto-char (match-beginning 0))
917 ;; Ensure match is a footnote reference or definition.
918 (when (save-match-data (if (bolp)
919 (org-footnote-at-definition-p)
920 (org-footnote-at-reference-p)))
921 (let ((new-val (or (cdr (assoc (match-string 1) map))
922 (number-to-string (incf n)))))
923 (unless (assoc (match-string 1) map)
924 (push (cons (match-string 1) new-val) map))
925 (replace-match new-val nil nil nil 1))))))))
927 (defun org-footnote-auto-adjust-maybe ()
928 "Renumber and/or sort footnotes according to user settings."
929 (when (memq org-footnote-auto-adjust '(t renumber))
930 (org-footnote-renumber-fn:N))
931 (when (memq org-footnote-auto-adjust '(t sort))
932 (let ((label (car (org-footnote-at-definition-p))))
933 (org-footnote-normalize 'sort)
934 (when label
935 (goto-char (point-min))
936 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
937 nil t)
938 (progn (insert " ")
939 (just-one-space)))))))
941 (provide 'org-footnote)
943 ;; Local variables:
944 ;; generated-autoload-file: "org-loaddefs.el"
945 ;; End:
947 ;;; org-footnote.el ends here