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