org-footnote.el: silence byte-compiler.
[org-mode.git] / lisp / org-footnote.el
blob5df9fbfb8d2c1ab290b76ae61ead8f3e9c265886
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.
418 The function returns the first \"fn:N\" or \"N\" label that is
419 currently not used."
420 (unless current (setq current (org-footnote-all-labels)))
421 (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
422 (cnt 1))
423 (while (member (format fmt cnt) current)
424 (incf cnt))
425 (format fmt cnt)))
427 (defun org-footnote-new ()
428 "Insert a new footnote.
429 This command prompts for a label. If this is a label referencing an
430 existing label, only insert the label. If the footnote label is empty
431 or new, let the user edit the definition of the footnote."
432 (interactive)
433 (unless (org-footnote-in-valid-context-p)
434 (error "Cannot insert a footnote here"))
435 (let* ((lbls (and (not (equal org-footnote-auto-label 'random))
436 (org-footnote-all-labels)))
437 (propose (org-footnote-unique-label lbls))
438 (label
439 (org-footnote-normalize-label
440 (cond
441 ((member org-footnote-auto-label '(t plain))
442 propose)
443 ((equal org-footnote-auto-label 'random)
444 (require 'org-id)
445 (substring (org-id-uuid) 0 8))
447 (org-icompleting-read
448 "Label (leave empty for anonymous): "
449 (mapcar 'list lbls) nil nil
450 (if (eq org-footnote-auto-label 'confirm) propose nil)))))))
451 (cond
452 ((and label (bolp) (not org-footnote-define-inline))
453 (error "Cannot create a non-inlined footnote at left margin"))
454 ((not label)
455 (insert "[fn:: ]")
456 (backward-char 1))
457 ((member label lbls)
458 (insert "[" label "]")
459 (message "New reference to existing note"))
460 (org-footnote-define-inline
461 (insert "[" label ": ]")
462 (backward-char 1)
463 (org-footnote-auto-adjust-maybe))
465 (insert "[" label "]")
466 (org-footnote-create-definition label)
467 (org-footnote-auto-adjust-maybe)))))
469 (defvar org-blank-before-new-entry nil) ; silence byte-compiler
470 (defun org-footnote-create-definition (label)
471 "Start the definition of a footnote with label LABEL."
472 (interactive "sLabel: ")
473 (let ((label (org-footnote-normalize-label label)))
474 (cond
475 ;; In an Org file.
476 ((org-mode-p)
477 ;; If `org-footnote-section' is defined, find it, or create it
478 ;; at the end of the buffer.
479 (when org-footnote-section
480 (goto-char (point-min))
481 (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
482 (unless (or (re-search-forward re nil t)
483 (and (progn (widen) t)
484 (re-search-forward re nil t)))
485 (goto-char (point-max))
486 (skip-chars-backward " \t\r\n")
487 (unless (bolp) (newline))
488 ;; Insert new section. Separate it from the previous one
489 ;; with a blank line, unless `org-blank-before-new-entry'
490 ;; explicitly says no.
491 (when (and (cdr (assq 'heading org-blank-before-new-entry))
492 (zerop (save-excursion (org-back-over-empty-lines))))
493 (insert "\n"))
494 (insert "* " org-footnote-section "\n"))))
495 ;; Move to the end of this entry (which may be
496 ;; `org-footnote-section' or the current one).
497 (org-footnote-goto-local-insertion-point)
498 (org-show-context 'link-search))
500 ;; In a non-Org file. Search for footnote tag, or create it if
501 ;; specified (at the end of buffer, or before signature if in
502 ;; Message mode). Set point after any definition already there.
503 (let ((tag (and org-footnote-tag-for-non-org-mode-files
504 (concat "^" (regexp-quote
505 org-footnote-tag-for-non-org-mode-files)
506 "[ \t]*$")))
507 (max (if (and (derived-mode-p 'message-mode)
508 (goto-char (point-max))
509 (re-search-backward
510 message-signature-separator nil t))
511 (progn
512 ;; Ensure one blank line separates last
513 ;; footnote from signature.
514 (beginning-of-line)
515 (open-line 2)
516 (point-marker))
517 (point-max-marker))))
518 (goto-char max)
519 ;; Check if the footnote tag is defined but missing. In this
520 ;; case, insert it, before any footnote or one blank line
521 ;; after any previous text.
522 (save-excursion
523 (when (and tag (not (re-search-backward tag nil t)))
524 (skip-chars-backward " \t\r\n")
525 (while (re-search-backward org-footnote-definition-re nil t))
526 (unless (bolp) (newline 2))
527 (insert org-footnote-tag-for-non-org-mode-files "\n\n")))
528 ;; Remove superfluous white space and clear marker.
529 (skip-chars-backward " \t\r\n")
530 (delete-region (point) max)
531 (unless (bolp) (newline))
532 (set-marker max nil))))
533 ;; Insert footnote label.
534 (insert "\n[" label "] ")
535 ;; Only notify user about next possible action when in an Org
536 ;; buffer, as the bindings may have different meanings otherwise.
537 (when (org-mode-p)
538 (message
539 "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
541 ;;;###autoload
542 (defun org-footnote-action (&optional special)
543 "Do the right thing for footnotes.
545 When at a footnote reference, jump to the definition.
547 When at a definition, jump to the references if they exist, offer
548 to create them otherwise.
550 When neither at definition or reference, create a new footnote,
551 interactively.
553 With prefix arg SPECIAL, offer additional commands in a menu."
554 (interactive "P")
555 (let (tmp c)
556 (cond
557 (special
558 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
559 (setq c (read-char-exclusive))
560 (cond
561 ((eq c ?s) (org-footnote-normalize 'sort))
562 ((eq c ?r) (org-footnote-renumber-fn:N))
563 ((eq c ?S)
564 (org-footnote-renumber-fn:N)
565 (org-footnote-normalize 'sort))
566 ((eq c ?n) (org-footnote-normalize))
567 ((eq c ?d) (org-footnote-delete))
568 (t (error "No such footnote command %c" c))))
569 ((setq tmp (org-footnote-at-reference-p))
570 (cond
571 ;; Anonymous footnote: move point at the beginning of its
572 ;; definition.
573 ((not (car tmp))
574 (goto-char (nth 1 tmp))
575 (forward-char 5))
576 ;; A definition exists: move to it.
577 ((ignore-errors (org-footnote-goto-definition (car tmp))))
578 ;; No definition exists: offer to create it.
579 ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
580 (org-footnote-create-definition (car tmp)))))
581 ((setq tmp (org-footnote-at-definition-p))
582 (org-footnote-goto-previous-reference (car tmp)))
583 (t (org-footnote-new)))))
585 (defvar org-footnote-insert-pos-for-preprocessor 'point-max
586 "See `org-footnote-normalize'.")
588 (defvar org-export-footnotes-seen nil) ; silence byte-compiler
589 (defvar org-export-footnotes-data nil) ; silence byte-compiler
591 ;;;###autoload
592 (defun org-footnote-normalize (&optional sort-only export-props)
593 "Collect the footnotes in various formats and normalize them.
595 This finds the different sorts of footnotes allowed in Org, and
596 normalizes them to the usual [N] format that is understood by the
597 Org-mode exporters.
599 When SORT-ONLY is set, only sort the footnote definitions into the
600 referenced sequence.
602 If Org is amidst an export process, EXPORT-PROPS will hold the
603 export properties of the buffer.
605 When EXPORT-PROPS is non-nil, the default action is to insert
606 normalized footnotes towards the end of the pre-processing buffer.
607 Some exporters like docbook, odt, etc. expect that footnote
608 definitions be available before any references to them. Such
609 exporters can let bind `org-footnote-insert-pos-for-preprocessor' to
610 symbol 'point-min to achieve the desired behaviour.
612 Additional note on `org-footnote-insert-pos-for-preprocessor':
613 1. This variable has not effect when FOR-PREPROCESSOR is nil.
614 2. This variable (potentially) obviates the need for extra scan
615 of pre-processor buffer as witnessed in
616 `org-export-docbook-get-footnotes'."
617 ;; This is based on Paul's function, but rewritten.
619 ;; Re-create `org-with-limited-levels', but not limited to Org
620 ;; buffers.
621 (let* ((limit-level
622 (and (boundp 'org-inlinetask-min-level)
623 org-inlinetask-min-level
624 (1- org-inlinetask-min-level)))
625 (nstars (and limit-level
626 (if org-odd-levels-only
627 (and limit-level (1- (* limit-level 2)))
628 limit-level)))
629 (org-outline-regexp
630 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
631 ;; Determine the highest marker used so far.
632 (ref-table (when export-props org-export-footnotes-seen))
633 (count (if (and export-props ref-table)
634 (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
636 ins-point ref)
637 (save-excursion
638 ;; 1. Find every footnote reference, extract the definition, and
639 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
640 ;; normalize references.
641 (goto-char (point-min))
642 (while (setq ref (org-footnote-get-next-reference))
643 (let* ((lbl (car ref))
644 ;; When footnote isn't anonymous, check if it's label
645 ;; (REF) is already stored in REF-TABLE. In that case,
646 ;; extract number used to identify it (MARKER). If
647 ;; footnote is unknown, increment the global counter
648 ;; (COUNT) to create an unused identifier.
649 (a (and lbl (assoc lbl ref-table)))
650 (marker (or (nth 1 a) (incf count)))
651 ;; Is the reference inline or pointing to an inline
652 ;; footnote?
653 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
654 ;; Replace footnote reference with [MARKER]. Maybe fill
655 ;; paragraph once done. If SORT-ONLY is non-nil, only move
656 ;; to the end of reference found to avoid matching it twice.
657 ;; If EXPORT-PROPS isn't nil, also add `org-footnote'
658 ;; property to it, so it can be easily recognized by
659 ;; exporters.
660 (if sort-only
661 (goto-char (nth 2 ref))
662 (delete-region (nth 1 ref) (nth 2 ref))
663 (goto-char (nth 1 ref))
664 (let ((new-ref (format "[%d]" marker)))
665 (when export-props (org-add-props new-ref '(org-footnote t)))
666 (insert new-ref))
667 (and inlinep
668 org-footnote-fill-after-inline-note-extraction
669 (org-fill-paragraph)))
670 ;; Add label (REF), identifier (MARKER) and definition (DEF)
671 ;; to REF-TABLE if data was unknown.
672 (unless a
673 (let ((def (or (nth 3 ref) ; inline
674 (and export-props
675 (cdr (assoc lbl org-export-footnotes-data)))
676 (nth 3 (org-footnote-get-definition lbl)))))
677 (push (list lbl marker
678 ;; When exporting, each definition goes
679 ;; through `org-export-preprocess-string' so
680 ;; it is ready to insert in the
681 ;; backend-specific buffer.
682 (if (and export-props def)
683 (let ((parameters
684 (org-combine-plists
685 export-props
686 '(:todo-keywords t :tags t :priority t))))
687 (org-export-preprocess-string def parameters))
688 def)
689 inlinep) ref-table)))
690 ;; Remove definition of non-inlined footnotes.
691 (unless inlinep (org-footnote-delete-definitions lbl))))
692 ;; 2. Find and remove the footnote section, if any. Also
693 ;; determine where footnotes shall be inserted (INS-POINT).
694 (goto-char (point-min))
695 (cond
696 ((org-mode-p)
697 (if (and org-footnote-section
698 (re-search-forward
699 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
700 "[ \t]*$")
701 nil t))
702 (progn
703 (setq ins-point (match-beginning 0))
704 (delete-region (match-beginning 0) (org-end-of-subtree t)))
705 ;; Remove superfluous blank lines at the end of buffer.
706 (goto-char (point-max))
707 (skip-chars-backward " \r\t\n")
708 (delete-region (point) (point-max))
709 (unless (bolp) (newline))
710 (setq ins-point (point))))
712 ;; Remove any left-over tag in the buffer, if one is set up.
713 (when org-footnote-tag-for-non-org-mode-files
714 (let ((tag (concat "^" (regexp-quote
715 org-footnote-tag-for-non-org-mode-files)
716 "[ \t]*$")))
717 (while (re-search-forward tag nil t)
718 (replace-match "")
719 (delete-region (point) (progn (forward-line) (point))))))
720 ;; In Message mode, ensure footnotes are inserted before the
721 ;; signature.
722 (let ((pt-max (if (and (derived-mode-p 'message-mode)
723 (goto-char (point-max))
724 (re-search-backward
725 message-signature-separator nil t))
726 (progn
727 ;; Ensure one blank line separates last
728 ;; footnote from signature.
729 (beginning-of-line)
730 (open-line 2)
731 (point))
732 (point-max))))
733 (goto-char pt-max)
734 (skip-chars-backward " \t\n\r")
735 (delete-region (point) pt-max))
736 (unless (bolp) (newline))
737 (setq ins-point (point))))
738 ;; 3. Clean-up REF-TABLE.
739 (setq ref-table
740 (delq nil
741 (mapcar
742 (lambda (x)
743 (cond
744 ;; When only sorting, ignore inline footnotes.
745 ((and sort-only (nth 3 x)) nil)
746 ;; No definition available: provide one.
747 ((not (nth 2 x))
748 (append (butlast x 2)
749 (list (format "DEFINITION NOT FOUND: %s" (car x))
750 (nth 3 x))))
751 (t x)))
752 ref-table)))
753 (setq ref-table (nreverse ref-table))
754 ;; 4. Insert the footnotes again in the buffer, at the
755 ;; appropriate spot.
756 (goto-char (or
757 (and export-props
758 (eq org-footnote-insert-pos-for-preprocessor 'point-min)
759 (point-min))
760 ins-point
761 (point-max)))
762 (cond
763 ;; No footnote: exit.
764 ((not ref-table))
765 ;; Cases when footnotes should be inserted in one place.
766 ((or (not (org-mode-p))
767 org-footnote-section
768 (not sort-only))
769 ;; Insert again the section title, if any. Ensure that title,
770 ;; or the subsequent footnotes, will be separated by a blank
771 ;; lines from the rest of the document. In an Org buffer,
772 ;; separate section with a blank line, unless explicitly
773 ;; stated in `org-blank-before-new-entry'.
774 (cond
775 ((not (org-mode-p))
776 (unless (bolp) (newline))
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 (unless (bolp) (newline))
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 ;; 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