org: forward declare functions
[org-mode/org-tableheadings.git] / lisp / org-footnote.el
blob2438fba671793e77dd72e6786b53df3c1f133bd3
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 if possible.
577 With prefix arg SPECIAL, or when no footnote can be created,
578 offer additional commands in a menu."
579 (interactive "P")
580 (let* ((context (and (not special) (org-element-context)))
581 (type (org-element-type context)))
582 (cond
583 ((eq type 'footnote-reference)
584 (let ((label (org-element-property :label context)))
585 (cond
586 ;; Anonymous footnote: move point at the beginning of its
587 ;; definition.
588 ((not label)
589 (goto-char (org-element-property :contents-begin context)))
590 ;; A definition exists: move to it.
591 ((ignore-errors (org-footnote-goto-definition label)))
592 ;; No definition exists: offer to create it.
593 ((yes-or-no-p (format "No definition for %s. Create one? " label))
594 (org-footnote-create-definition label)))))
595 ((eq type 'footnote-definition)
596 (org-footnote-goto-previous-reference
597 (org-element-property :label context)))
598 ((or special
599 (zerop (current-column))
600 (not (org-footnote-in-valid-context-p)))
601 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
602 (let ((c (read-char-exclusive)))
603 (cond
604 ((eq c ?s) (org-footnote-normalize 'sort))
605 ((eq c ?r) (org-footnote-renumber-fn:N))
606 ((eq c ?S)
607 (org-footnote-renumber-fn:N)
608 (org-footnote-normalize 'sort))
609 ((eq c ?n) (org-footnote-normalize))
610 ((eq c ?d) (org-footnote-delete))
611 (t (error "No such footnote command %c" c)))))
612 (t (org-footnote-new)))))
614 ;;;###autoload
615 (defun org-footnote-normalize (&optional sort-only)
616 "Collect the footnotes in various formats and normalize them.
618 This finds the different sorts of footnotes allowed in Org, and
619 normalizes them to the usual [N] format.
621 When SORT-ONLY is set, only sort the footnote definitions into the
622 referenced sequence."
623 ;; This is based on Paul's function, but rewritten.
625 ;; Re-create `org-with-limited-levels', but not limited to Org
626 ;; buffers.
627 (let* ((limit-level
628 (and (boundp 'org-inlinetask-min-level)
629 org-inlinetask-min-level
630 (1- org-inlinetask-min-level)))
631 (nstars (and limit-level
632 (if org-odd-levels-only (1- (* limit-level 2))
633 limit-level)))
634 (org-outline-regexp
635 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
636 (count 0)
637 ins-point ref ref-table)
638 (save-excursion
639 ;; 1. Find every footnote reference, extract the definition, and
640 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
641 ;; normalize references.
642 (goto-char (point-min))
643 (while (setq ref (org-footnote-get-next-reference))
644 (let* ((lbl (car ref))
645 (pos (nth 1 ref))
646 ;; When footnote isn't anonymous, check if it's label
647 ;; (REF) is already stored in REF-TABLE. In that case,
648 ;; extract number used to identify it (MARKER). If
649 ;; footnote is unknown, increment the global counter
650 ;; (COUNT) to create an unused identifier.
651 (a (and lbl (assoc lbl ref-table)))
652 (marker (or (nth 1 a) (incf count)))
653 ;; Is the reference inline or pointing to an inline
654 ;; footnote?
655 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
656 ;; Replace footnote reference with [MARKER]. Maybe fill
657 ;; paragraph once done. If SORT-ONLY is non-nil, only move
658 ;; to the end of reference found to avoid matching it twice.
659 (if sort-only (goto-char (nth 2 ref))
660 (delete-region (nth 1 ref) (nth 2 ref))
661 (goto-char (nth 1 ref))
662 (insert (format "[%d]" marker))
663 (and inlinep
664 org-footnote-fill-after-inline-note-extraction
665 (org-fill-paragraph)))
666 ;; Add label (REF), identifier (MARKER), definition (DEF)
667 ;; type (INLINEP) and position (POS) to REF-TABLE if data
668 ;; was unknown.
669 (unless a
670 (let ((def (or (nth 3 ref) ; Inline definition.
671 (nth 3 (org-footnote-get-definition lbl)))))
672 (push (list lbl marker def
673 ;; Reference beginning position is a marker
674 ;; to preserve it during further buffer
675 ;; modifications.
676 inlinep (copy-marker pos)) ref-table)))))
677 ;; 2. Find and remove the footnote section, if any. Also
678 ;; determine where footnotes shall be inserted (INS-POINT).
679 (cond
680 ((and org-footnote-section (derived-mode-p 'org-mode))
681 (goto-char (point-min))
682 (if (re-search-forward
683 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
684 "[ \t]*$") nil t)
685 (delete-region (match-beginning 0) (org-end-of-subtree t t)))
686 ;; A new footnote section is inserted by default at the end of
687 ;; the buffer.
688 (goto-char (point-max))
689 (skip-chars-backward " \r\t\n")
690 (forward-line)
691 (unless (bolp) (newline)))
692 ;; No footnote section set: Footnotes will be added at the end
693 ;; of the section containing their first reference.
694 ((derived-mode-p 'org-mode))
696 ;; Remove any left-over tag in the buffer, if one is set up.
697 (when org-footnote-tag-for-non-org-mode-files
698 (let ((tag (concat "^" (regexp-quote
699 org-footnote-tag-for-non-org-mode-files)
700 "[ \t]*$")))
701 (goto-char (point-min))
702 (while (re-search-forward tag nil t)
703 (replace-match "")
704 (delete-region (point) (progn (forward-line) (point))))))
705 ;; In Message mode, ensure footnotes are inserted before the
706 ;; signature.
707 (if (and (derived-mode-p 'message-mode)
708 (goto-char (point-max))
709 (re-search-backward message-signature-separator nil t))
710 (beginning-of-line)
711 (goto-char (point-max)))))
712 (setq ins-point (point-marker))
713 ;; 3. Clean-up REF-TABLE.
714 (setq ref-table
715 (delq nil
716 (mapcar
717 (lambda (x)
718 (cond
719 ;; When only sorting, ignore inline footnotes.
720 ;; Also clear position marker.
721 ((and sort-only (nth 3 x))
722 (set-marker (nth 4 x) nil) nil)
723 ;; No definition available: provide one.
724 ((not (nth 2 x))
725 (append
726 (list (car x) (nth 1 x)
727 (format "DEFINITION NOT FOUND: %s" (car x)))
728 (nthcdr 3 x)))
729 (t x)))
730 ref-table)))
731 (setq ref-table (nreverse ref-table))
732 ;; 4. Remove left-over definitions in the buffer.
733 (mapc (lambda (x)
734 (unless (nth 3 x) (org-footnote-delete-definitions (car x))))
735 ref-table)
736 ;; 5. Insert the footnotes again in the buffer, at the
737 ;; appropriate spot.
738 (goto-char ins-point)
739 (cond
740 ;; No footnote: exit.
741 ((not ref-table))
742 ;; Cases when footnotes should be inserted in one place.
743 ((or (not (derived-mode-p 'org-mode)) org-footnote-section)
744 ;; Insert again the section title, if any. Ensure that title,
745 ;; or the subsequent footnotes, will be separated by a blank
746 ;; lines from the rest of the document. In an Org buffer,
747 ;; separate section with a blank line, unless explicitly
748 ;; stated in `org-blank-before-new-entry'.
749 (if (not (derived-mode-p 'org-mode))
750 (progn (skip-chars-backward " \t\n\r")
751 (delete-region (point) ins-point)
752 (unless (bolp) (newline))
753 (when org-footnote-tag-for-non-org-mode-files
754 (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
755 (when (and (cdr (assq 'heading org-blank-before-new-entry))
756 (zerop (save-excursion (org-back-over-empty-lines))))
757 (insert "\n"))
758 (insert "* " org-footnote-section "\n"))
759 (set-marker ins-point nil)
760 ;; Insert the footnotes, separated by a blank line.
761 (insert
762 (mapconcat
763 (lambda (x)
764 ;; Clean markers.
765 (set-marker (nth 4 x) nil)
766 (format "\n[%s] %s" (nth (if sort-only 0 1) x) (nth 2 x)))
767 ref-table "\n"))
768 (unless (eobp) (insert "\n\n")))
769 ;; Each footnote definition has to be inserted at the end of
770 ;; the section where its first reference belongs.
772 (mapc
773 (lambda (x)
774 (let ((pos (nth 4 x)))
775 (goto-char pos)
776 ;; Clean marker.
777 (set-marker pos nil))
778 (org-footnote-goto-local-insertion-point)
779 (insert (format "\n[%s] %s\n"
780 (if sort-only (car x) (nth 1 x))
781 (nth 2 x))))
782 ref-table))))))
784 (defun org-footnote-goto-local-insertion-point ()
785 "Find insertion point for footnote, just before next outline heading."
786 (org-with-limited-levels (outline-next-heading))
787 (or (bolp) (newline))
788 (beginning-of-line 0)
789 (while (and (not (bobp)) (= (char-after) ?#))
790 (beginning-of-line 0))
791 (if (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:")) (beginning-of-line 2))
792 (end-of-line 1)
793 (skip-chars-backward "\n\r\t ")
794 (forward-line))
796 (defun org-footnote-delete-references (label)
797 "Delete every reference to footnote LABEL.
798 Return the number of footnotes removed."
799 (save-excursion
800 (goto-char (point-min))
801 (let (ref (nref 0))
802 (while (setq ref (org-footnote-get-next-reference label))
803 (goto-char (nth 1 ref))
804 (delete-region (nth 1 ref) (nth 2 ref))
805 (incf nref))
806 nref)))
808 (defun org-footnote-delete-definitions (label)
809 "Delete every definition of the footnote LABEL.
810 Return the number of footnotes removed."
811 (save-excursion
812 (goto-char (point-min))
813 (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
814 (ndef 0))
815 (while (re-search-forward def-re nil t)
816 (let ((full-def (org-footnote-at-definition-p)))
817 (when full-def
818 ;; Remove the footnote, and all blank lines before it.
819 (goto-char (nth 1 full-def))
820 (skip-chars-backward " \r\t\n")
821 (unless (bolp) (forward-line))
822 (delete-region (point) (nth 2 full-def))
823 (incf ndef))))
824 ndef)))
826 (defun org-footnote-delete (&optional label)
827 "Delete the footnote at point.
828 This will remove the definition (even multiple definitions if they exist)
829 and all references of a footnote label.
831 If LABEL is non-nil, delete that footnote instead."
832 (catch 'done
833 (let* ((nref 0) (ndef 0) x
834 ;; 1. Determine LABEL of footnote at point.
835 (label (cond
836 ;; LABEL is provided as argument.
837 (label)
838 ;; Footnote reference at point. If the footnote is
839 ;; anonymous, delete it and exit instead.
840 ((setq x (org-footnote-at-reference-p))
841 (or (car x)
842 (progn
843 (delete-region (nth 1 x) (nth 2 x))
844 (message "Anonymous footnote removed")
845 (throw 'done t))))
846 ;; Footnote definition at point.
847 ((setq x (org-footnote-at-definition-p))
848 (car x))
849 (t (error "Don't know which footnote to remove")))))
850 ;; 2. Now that LABEL is non-nil, find every reference and every
851 ;; definition, and delete them.
852 (setq nref (org-footnote-delete-references label)
853 ndef (org-footnote-delete-definitions label))
854 ;; 3. Verify consistency of footnotes and notify user.
855 (org-footnote-auto-adjust-maybe)
856 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
857 ndef nref label))))
859 (defun org-footnote-renumber-fn:N ()
860 "Renumber the simple footnotes like fn:17 into a sequence in the document."
861 (interactive)
862 (let (map (n 0))
863 (org-with-wide-buffer
864 (goto-char (point-min))
865 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
866 (save-excursion
867 (goto-char (match-beginning 0))
868 ;; Ensure match is a footnote reference or definition.
869 (when (save-match-data (if (bolp)
870 (org-footnote-at-definition-p)
871 (org-footnote-at-reference-p)))
872 (let ((new-val (or (cdr (assoc (match-string 1) map))
873 (number-to-string (incf n)))))
874 (unless (assoc (match-string 1) map)
875 (push (cons (match-string 1) new-val) map))
876 (replace-match new-val nil nil nil 1))))))))
878 (defun org-footnote-auto-adjust-maybe ()
879 "Renumber and/or sort footnotes according to user settings."
880 (when (memq org-footnote-auto-adjust '(t renumber))
881 (org-footnote-renumber-fn:N))
882 (when (memq org-footnote-auto-adjust '(t sort))
883 (let ((label (car (org-footnote-at-definition-p))))
884 (org-footnote-normalize 'sort)
885 (when label
886 (goto-char (point-min))
887 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
888 nil t)
889 (progn (insert " ")
890 (just-one-space)))))))
892 (provide 'org-footnote)
894 ;; Local variables:
895 ;; generated-autoload-file: "org-loaddefs.el"
896 ;; End:
898 ;;; org-footnote.el ends here