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