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