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