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