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