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