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