* org.el (org-archive-location): Minor docstring fix.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org-footnote.el
blob648dd604de4e1749ccd2c7b5008fb1868ed6785c
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 (when (or (re-search-forward re nil t)
332 (and (goto-char (point-min))
333 (re-search-forward re nil t))
334 (and (progn (widen) t)
335 (goto-char (point-min))
336 (re-search-forward re nil t)))
337 (let ((refp (org-footnote-at-reference-p)))
338 (cond
339 ((and (nth 3 refp) refp))
340 ((org-footnote-at-definition-p))))))))
342 (defun org-footnote-goto-definition (label)
343 "Move point to the definition of the footnote LABEL."
344 (interactive "sLabel: ")
345 (org-mark-ring-push)
346 (let ((def (org-footnote-get-definition label)))
347 (if (not def)
348 (error "Cannot find definition of footnote %s" label)
349 (goto-char (nth 1 def))
350 (looking-at (format "\\[%s\\]\\|\\[%s:" label label))
351 (goto-char (match-end 0))
352 (org-show-context 'link-search)
353 (when (org-mode-p)
354 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))))
356 (defun org-footnote-goto-previous-reference (label)
357 "Find the first closest (to point) reference of footnote with label LABEL."
358 (interactive "sLabel: ")
359 (org-mark-ring-push)
360 (let* ((label (org-footnote-normalize-label label)) ref)
361 (save-excursion
362 (setq ref (or (org-footnote-get-next-reference label t)
363 (org-footnote-get-next-reference label)
364 (save-restriction
365 (widen)
367 (org-footnote-get-next-reference label t)
368 (org-footnote-get-next-reference label))))))
369 (if (not ref)
370 (error "Cannot find reference of footnote %s" label)
371 (goto-char (nth 1 ref))
372 (org-show-context 'link-search))))
374 (defun org-footnote-normalize-label (label)
375 "Return LABEL as an appropriate string."
376 (cond
377 ((numberp label) (number-to-string label))
378 ((equal "" label) nil)
379 ((not (string-match "^[0-9]+$\\|^fn:" label))
380 (concat "fn:" label))
381 (t label)))
383 (defun org-footnote-all-labels (&optional with-defs)
384 "Return list with all defined foot labels used in the buffer.
386 If WITH-DEFS is non-nil, also associate the definition to each
387 label. The function will then return an alist whose key is label
388 and value definition."
389 (let* (rtn
390 (push-to-rtn
391 (function
392 ;; Depending on WITH-DEFS, store label or (label . def) of
393 ;; footnote reference/definition given as argument in RTN.
394 (lambda (el)
395 (let ((lbl (car el)))
396 (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
397 (save-excursion
398 (save-restriction
399 (widen)
400 ;; Find all labels found in definitions.
401 (goto-char (point-min))
402 (let (def)
403 (while (re-search-forward org-footnote-definition-re nil t)
404 (when (setq def (org-footnote-at-definition-p))
405 (funcall push-to-rtn def))))
406 ;; Find all labels found in references.
407 (goto-char (point-min))
408 (let (ref)
409 (while (setq ref (org-footnote-get-next-reference))
410 (goto-char (nth 2 ref))
411 (and (car ref) ; ignore anonymous footnotes
412 (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
413 (funcall push-to-rtn ref))))))
414 rtn))
416 (defun org-footnote-unique-label (&optional current)
417 "Return a new unique footnote label.
419 The function returns the first \"fn:N\" or \"N\" label that is
420 currently not used.
422 Optional argument CURRENT is the list of labels active in the
423 buffer."
424 (unless current (setq current (org-footnote-all-labels)))
425 (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
426 (cnt 1))
427 (while (member (format fmt cnt) current)
428 (incf cnt))
429 (format fmt cnt)))
431 (defun org-footnote-new ()
432 "Insert a new footnote.
433 This command prompts for a label. If this is a label referencing an
434 existing label, only insert the label. If the footnote label is empty
435 or new, let the user edit the definition of the footnote."
436 (interactive)
437 (unless (org-footnote-in-valid-context-p)
438 (error "Cannot insert a footnote here"))
439 (let* ((lbls (and (not (equal org-footnote-auto-label 'random))
440 (org-footnote-all-labels)))
441 (propose (org-footnote-unique-label lbls))
442 (label
443 (org-footnote-normalize-label
444 (cond
445 ((member org-footnote-auto-label '(t plain))
446 propose)
447 ((equal org-footnote-auto-label 'random)
448 (require 'org-id)
449 (substring (org-id-uuid) 0 8))
451 (org-icompleting-read
452 "Label (leave empty for anonymous): "
453 (mapcar 'list lbls) nil nil
454 (if (eq org-footnote-auto-label 'confirm) propose nil)))))))
455 (cond
456 ((and label (bolp) (not org-footnote-define-inline))
457 (error "Cannot create a non-inlined footnote at left margin"))
458 ((not label)
459 (insert "[fn:: ]")
460 (backward-char 1))
461 ((member label lbls)
462 (insert "[" label "]")
463 (message "New reference to existing note"))
464 (org-footnote-define-inline
465 (insert "[" label ": ]")
466 (backward-char 1)
467 (org-footnote-auto-adjust-maybe))
469 (insert "[" label "]")
470 (org-footnote-create-definition label)
471 (org-footnote-auto-adjust-maybe)))))
473 (defvar org-blank-before-new-entry nil) ; silence byte-compiler
474 (defun org-footnote-create-definition (label)
475 "Start the definition of a footnote with label LABEL."
476 (interactive "sLabel: ")
477 (let ((label (org-footnote-normalize-label label)))
478 (cond
479 ;; In an Org file.
480 ((org-mode-p)
481 ;; If `org-footnote-section' is defined, find it, or create it
482 ;; at the end of the buffer.
483 (when org-footnote-section
484 (goto-char (point-min))
485 (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
486 (unless (or (re-search-forward re nil t)
487 (and (progn (widen) t)
488 (re-search-forward re nil t)))
489 (goto-char (point-max))
490 (skip-chars-backward " \t\r\n")
491 (unless (bolp) (newline))
492 ;; Insert new section. Separate it from the previous one
493 ;; with a blank line, unless `org-blank-before-new-entry'
494 ;; explicitly says no.
495 (when (and (cdr (assq 'heading org-blank-before-new-entry))
496 (zerop (save-excursion (org-back-over-empty-lines))))
497 (insert "\n"))
498 (insert "* " org-footnote-section "\n"))))
499 ;; Move to the end of this entry (which may be
500 ;; `org-footnote-section' or the current one).
501 (org-footnote-goto-local-insertion-point)
502 (org-show-context 'link-search))
504 ;; In a non-Org file. Search for footnote tag, or create it if
505 ;; specified (at the end of buffer, or before signature if in
506 ;; Message mode). Set point after any definition already there.
507 (let ((tag (and org-footnote-tag-for-non-org-mode-files
508 (concat "^" (regexp-quote
509 org-footnote-tag-for-non-org-mode-files)
510 "[ \t]*$")))
511 (max (if (and (derived-mode-p 'message-mode)
512 (goto-char (point-max))
513 (re-search-backward
514 message-signature-separator nil t))
515 (progn
516 ;; Ensure one blank line separates last
517 ;; footnote from signature.
518 (beginning-of-line)
519 (open-line 2)
520 (point-marker))
521 (point-max-marker))))
522 (goto-char max)
523 ;; Check if the footnote tag is defined but missing. In this
524 ;; case, insert it, before any footnote or one blank line
525 ;; after any previous text.
526 (save-excursion
527 (when (and tag (not (re-search-backward tag nil t)))
528 (skip-chars-backward " \t\r\n")
529 (while (re-search-backward org-footnote-definition-re nil t))
530 (unless (bolp) (newline 2))
531 (insert org-footnote-tag-for-non-org-mode-files "\n\n")))
532 ;; Remove superfluous white space and clear marker.
533 (skip-chars-backward " \t\r\n")
534 (delete-region (point) max)
535 (unless (bolp) (newline))
536 (set-marker max nil))))
537 ;; Insert footnote label.
538 (insert "\n[" label "] ")
539 ;; Only notify user about next possible action when in an Org
540 ;; buffer, as the bindings may have different meanings otherwise.
541 (when (org-mode-p)
542 (message
543 "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
545 ;;;###autoload
546 (defun org-footnote-action (&optional special)
547 "Do the right thing for footnotes.
549 When at a footnote reference, jump to the definition.
551 When at a definition, jump to the references if they exist, offer
552 to create them otherwise.
554 When neither at definition or reference, create a new footnote,
555 interactively.
557 With prefix arg SPECIAL, offer additional commands in a menu."
558 (interactive "P")
559 (let (tmp c)
560 (cond
561 (special
562 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
563 (setq c (read-char-exclusive))
564 (cond
565 ((eq c ?s) (org-footnote-normalize 'sort))
566 ((eq c ?r) (org-footnote-renumber-fn:N))
567 ((eq c ?S)
568 (org-footnote-renumber-fn:N)
569 (org-footnote-normalize 'sort))
570 ((eq c ?n) (org-footnote-normalize))
571 ((eq c ?d) (org-footnote-delete))
572 (t (error "No such footnote command %c" c))))
573 ((setq tmp (org-footnote-at-reference-p))
574 (cond
575 ;; Anonymous footnote: move point at the beginning of its
576 ;; definition.
577 ((not (car tmp))
578 (goto-char (nth 1 tmp))
579 (forward-char 5))
580 ;; A definition exists: move to it.
581 ((ignore-errors (org-footnote-goto-definition (car tmp))))
582 ;; No definition exists: offer to create it.
583 ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
584 (org-footnote-create-definition (car tmp)))))
585 ((setq tmp (org-footnote-at-definition-p))
586 (org-footnote-goto-previous-reference (car tmp)))
587 (t (org-footnote-new)))))
589 (defvar org-footnote-insert-pos-for-preprocessor 'point-max
590 "See `org-footnote-normalize'.")
592 (defvar org-export-footnotes-seen nil) ; silence byte-compiler
593 (defvar org-export-footnotes-data nil) ; silence byte-compiler
595 ;;;###autoload
596 (defun org-footnote-normalize (&optional sort-only export-props)
597 "Collect the footnotes in various formats and normalize them.
599 This finds the different sorts of footnotes allowed in Org, and
600 normalizes them to the usual [N] format that is understood by the
601 Org-mode exporters.
603 When SORT-ONLY is set, only sort the footnote definitions into the
604 referenced sequence.
606 If Org is amidst an export process, EXPORT-PROPS will hold the
607 export properties of the buffer.
609 When EXPORT-PROPS is non-nil, the default action is to insert
610 normalized footnotes towards the end of the pre-processing
611 buffer. Some exporters (docbook, odt...) expect footnote
612 definitions to be available before any references to them. Such
613 exporters can let bind `org-footnote-insert-pos-for-preprocessor'
614 to symbol `point-min' to achieve the desired behaviour.
616 Additional note on `org-footnote-insert-pos-for-preprocessor':
617 1. This variable has not effect when FOR-PREPROCESSOR is nil.
618 2. This variable (potentially) obviates the need for extra scan
619 of pre-processor buffer as witnessed in
620 `org-export-docbook-get-footnotes'."
621 ;; This is based on Paul's function, but rewritten.
623 ;; Re-create `org-with-limited-levels', but not limited to Org
624 ;; buffers.
625 (let* ((limit-level
626 (and (boundp 'org-inlinetask-min-level)
627 org-inlinetask-min-level
628 (1- org-inlinetask-min-level)))
629 (nstars (and limit-level
630 (if org-odd-levels-only
631 (and limit-level (1- (* limit-level 2)))
632 limit-level)))
633 (org-outline-regexp
634 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
635 ;; Determine the highest marker used so far.
636 (ref-table (when export-props org-export-footnotes-seen))
637 (count (if (and export-props ref-table)
638 (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
640 ins-point ref)
641 (save-excursion
642 ;; 1. Find every footnote reference, extract the definition, and
643 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
644 ;; normalize references.
645 (goto-char (point-min))
646 (while (setq ref (org-footnote-get-next-reference))
647 (let* ((lbl (car ref))
648 ;; When footnote isn't anonymous, check if it's label
649 ;; (REF) is already stored in REF-TABLE. In that case,
650 ;; extract number used to identify it (MARKER). If
651 ;; footnote is unknown, increment the global counter
652 ;; (COUNT) to create an unused identifier.
653 (a (and lbl (assoc lbl ref-table)))
654 (marker (or (nth 1 a) (incf count)))
655 ;; Is the reference inline or pointing to an inline
656 ;; footnote?
657 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
658 ;; Replace footnote reference with [MARKER]. Maybe fill
659 ;; paragraph once done. If SORT-ONLY is non-nil, only move
660 ;; to the end of reference found to avoid matching it twice.
661 ;; If EXPORT-PROPS isn't nil, also add `org-footnote'
662 ;; property to it, so it can be easily recognized by
663 ;; exporters.
664 (if sort-only
665 (goto-char (nth 2 ref))
666 (delete-region (nth 1 ref) (nth 2 ref))
667 (goto-char (nth 1 ref))
668 (let ((new-ref (format "[%d]" marker)))
669 (when export-props (org-add-props new-ref '(org-footnote t)))
670 (insert new-ref))
671 (and inlinep
672 org-footnote-fill-after-inline-note-extraction
673 (org-fill-paragraph)))
674 ;; Add label (REF), identifier (MARKER), definition (DEF)
675 ;; and type (INLINEP) to REF-TABLE if data was unknown.
676 (unless a
677 (let ((def (or (nth 3 ref) ; inline
678 (and export-props
679 (cdr (assoc lbl org-export-footnotes-data)))
680 (nth 3 (org-footnote-get-definition lbl)))))
681 (push (list lbl marker
682 ;; When exporting, each definition goes
683 ;; through `org-export-preprocess-string' so
684 ;; it is ready to insert in the
685 ;; backend-specific buffer.
686 (if (and export-props def)
687 (let ((parameters
688 (org-combine-plists
689 export-props
690 '(:todo-keywords t :tags t :priority t))))
691 (org-export-preprocess-string def parameters))
692 def)
693 inlinep) ref-table)))))
694 ;; 2. Find and remove the footnote section, if any. Also
695 ;; determine where footnotes shall be inserted (INS-POINT).
696 (goto-char (point-min))
697 (cond
698 ((and org-footnote-section
699 (org-mode-p)
700 (re-search-forward
701 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
702 "[ \t]*$")
703 nil t))
704 (delete-region (match-beginning 0) (org-end-of-subtree t)))
705 ((org-mode-p)
706 (goto-char (point-max))
707 (unless (bolp) (newline)))
709 ;; Remove any left-over tag in the buffer, if one is set up.
710 (when org-footnote-tag-for-non-org-mode-files
711 (let ((tag (concat "^" (regexp-quote
712 org-footnote-tag-for-non-org-mode-files)
713 "[ \t]*$")))
714 (while (re-search-forward tag nil t)
715 (replace-match "")
716 (delete-region (point) (progn (forward-line) (point))))))
717 ;; In Message mode, ensure footnotes are inserted before the
718 ;; signature.
719 (if (and (derived-mode-p 'message-mode)
720 (goto-char (point-max))
721 (re-search-backward message-signature-separator nil t))
722 (beginning-of-line)
723 (goto-char (point-max)))))
724 ;; During export, `org-footnote-insert-pos-for-preprocessor' has
725 ;; precedence over previously found position.
726 (setq ins-point
727 (copy-marker
728 (if (and export-props
729 (eq org-footnote-insert-pos-for-preprocessor 'point-min))
730 (point-min)
731 (point))))
732 ;; 3. Clean-up REF-TABLE.
733 (setq ref-table
734 (delq nil
735 (mapcar
736 (lambda (x)
737 (cond
738 ;; When only sorting, ignore inline footnotes.
739 ((and sort-only (nth 3 x)) nil)
740 ;; No definition available: provide one.
741 ((not (nth 2 x))
742 (append (butlast x 2)
743 (list (format "DEFINITION NOT FOUND: %s" (car x))
744 (nth 3 x))))
745 (t x)))
746 ref-table)))
747 (setq ref-table (nreverse ref-table))
748 ;; 4. Remove left-over definitions in the buffer.
749 (mapc (lambda (x) (unless (nth 3 x)
750 (org-footnote-delete-definitions (car x))))
751 ref-table)
752 ;; 5. Insert the footnotes again in the buffer, at the
753 ;; appropriate spot.
754 (goto-char ins-point)
755 (cond
756 ;; No footnote: exit.
757 ((not ref-table))
758 ;; Cases when footnotes should be inserted in one place.
759 ((or (not (org-mode-p))
760 org-footnote-section
761 (not sort-only))
762 ;; Insert again the section title, if any. Ensure that title,
763 ;; or the subsequent footnotes, will be separated by a blank
764 ;; lines from the rest of the document. In an Org buffer,
765 ;; separate section with a blank line, unless explicitly
766 ;; stated in `org-blank-before-new-entry'.
767 (cond
768 ((not (org-mode-p))
769 (skip-chars-backward " \t\n\r")
770 (delete-region (point) ins-point)
771 (unless (bolp) (newline))
772 ;; Keep one blank line between footnotes and signature.
773 (when (and (derived-mode-p 'message-mode)
774 (save-excursion
775 (re-search-forward message-signature-separator nil t)))
776 (open-line 2))
777 (when org-footnote-tag-for-non-org-mode-files
778 (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
779 ((and org-footnote-section (not export-props))
780 (when (and (cdr (assq 'heading org-blank-before-new-entry))
781 (zerop (save-excursion (org-back-over-empty-lines))))
782 (insert "\n"))
783 (insert "* " org-footnote-section "\n")))
784 (set-marker ins-point nil)
785 ;; Insert the footnotes, separated by a blank line.
786 (insert (mapconcat (lambda (x) (format "\n[%s] %s"
787 (nth (if sort-only 0 1) x) (nth 2 x)))
788 ref-table "\n"))
789 ;; When exporting, add newly inserted markers along with their
790 ;; associated definition to `org-export-footnotes-seen'.
791 (when export-props
792 (setq org-export-footnotes-seen ref-table)))
793 ;; Else, insert each definition at the end of the section
794 ;; containing their first reference. Happens only in Org files
795 ;; with no special footnote section, and only when doing
796 ;; sorting.
797 (t (mapc 'org-insert-footnote-reference-near-definition
798 ref-table))))))
800 (defun org-insert-footnote-reference-near-definition (entry)
801 "Find first reference of footnote ENTRY and insert the definition there.
802 ENTRY is (fn-label num-mark definition)."
803 (when (car entry)
804 (goto-char (point-min))
805 (let ((ref (org-footnote-get-next-reference (car entry))))
806 (when ref
807 (goto-char (nth 2 ref))
808 (org-footnote-goto-local-insertion-point)
809 (insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
811 (defun org-footnote-goto-local-insertion-point ()
812 "Find insertion point for footnote, just before next outline heading."
813 (org-with-limited-levels (outline-next-heading))
814 (or (bolp) (newline))
815 (beginning-of-line 0)
816 (while (and (not (bobp)) (= (char-after) ?#))
817 (beginning-of-line 0))
818 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
819 (end-of-line 1)
820 (skip-chars-backward "\n\r\t ")
821 (forward-line))
823 (defun org-footnote-delete-references (label)
824 "Delete every reference to footnote LABEL.
825 Return the number of footnotes removed."
826 (save-excursion
827 (goto-char (point-min))
828 (let (ref (nref 0))
829 (while (setq ref (org-footnote-get-next-reference label))
830 (goto-char (nth 1 ref))
831 (delete-region (nth 1 ref) (nth 2 ref))
832 (incf nref))
833 nref)))
835 (defun org-footnote-delete-definitions (label)
836 "Delete every definition of the footnote LABEL.
837 Return the number of footnotes removed."
838 (save-excursion
839 (goto-char (point-min))
840 (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
841 (ndef 0))
842 (while (re-search-forward def-re nil t)
843 (let ((full-def (org-footnote-at-definition-p)))
844 (delete-region (nth 1 full-def) (nth 2 full-def)))
845 (incf ndef))
846 ndef)))
848 (defun org-footnote-delete (&optional label)
849 "Delete the footnote at point.
850 This will remove the definition (even multiple definitions if they exist)
851 and all references of a footnote label.
853 If LABEL is non-nil, delete that footnote instead."
854 (catch 'done
855 (let* ((nref 0) (ndef 0) x
856 ;; 1. Determine LABEL of footnote at point.
857 (label (cond
858 ;; LABEL is provided as argument.
859 (label)
860 ;; Footnote reference at point. If the footnote is
861 ;; anonymous, delete it and exit instead.
862 ((setq x (org-footnote-at-reference-p))
863 (or (car x)
864 (progn
865 (delete-region (nth 1 x) (nth 2 x))
866 (message "Anonymous footnote removed")
867 (throw 'done t))))
868 ;; Footnote definition at point.
869 ((setq x (org-footnote-at-definition-p))
870 (car x))
871 (t (error "Don't know which footnote to remove")))))
872 ;; 2. Now that LABEL is non-nil, find every reference and every
873 ;; definition, and delete them.
874 (setq nref (org-footnote-delete-references label)
875 ndef (org-footnote-delete-definitions label))
876 ;; 3. Verify consistency of footnotes and notify user.
877 (org-footnote-auto-adjust-maybe)
878 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
879 ndef nref label))))
881 (defun org-footnote-renumber-fn:N ()
882 "Renumber the simple footnotes like fn:17 into a sequence in the document."
883 (interactive)
884 (let (map i (n 0))
885 (save-excursion
886 (save-restriction
887 (widen)
888 (goto-char (point-min))
889 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
890 (setq i (string-to-number (match-string 1)))
891 (when (and (string-match "\\S-" (buffer-substring
892 (point-at-bol) (match-beginning 0)))
893 (not (assq i map)))
894 (push (cons i (number-to-string (incf n))) map)))
895 (goto-char (point-min))
896 (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
897 (replace-match (concat "\\1"
898 (cdr (assq (string-to-number (match-string 2))
899 map))
900 "\\3")))))))
902 (defun org-footnote-auto-adjust-maybe ()
903 "Renumber and/or sort footnotes according to user settings."
904 (when (memq org-footnote-auto-adjust '(t renumber))
905 (org-footnote-renumber-fn:N))
906 (when (memq org-footnote-auto-adjust '(t sort))
907 (let ((label (car (org-footnote-at-definition-p))))
908 (org-footnote-normalize 'sort)
909 (when label
910 (goto-char (point-min))
911 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
912 nil t)
913 (progn (insert " ")
914 (just-one-space)))))))
916 (provide 'org-footnote)
918 ;;; org-footnote.el ends here