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