org.el (org-todo): When changing from one state to the same state, throw a more accur...
[org-mode.git] / lisp / org-footnote.el
blobd1f67e4d83f067a56133c172e500c3fbe614d65f
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 (if (not (org-footnote-in-valid-context-p))
454 (org-footnote-action '(4))
455 (let* ((lbls (and (not (equal org-footnote-auto-label 'random))
456 (org-footnote-all-labels)))
457 (propose (and (not (equal org-footnote-auto-label 'random))
458 (org-footnote-unique-label lbls)))
459 (label
460 (org-footnote-normalize-label
461 (cond
462 ((member org-footnote-auto-label '(t plain))
463 propose)
464 ((equal org-footnote-auto-label 'random)
465 (require 'org-id)
466 (substring (org-id-uuid) 0 8))
468 (org-icompleting-read
469 "Label (leave empty for anonymous): "
470 (mapcar 'list lbls) nil nil
471 (if (eq org-footnote-auto-label 'confirm) propose nil)))))))
472 (cond
473 ((bolp) (error "Cannot create a footnote reference at left margin"))
474 ((not label)
475 (insert "[fn:: ]")
476 (backward-char 1))
477 ((member label lbls)
478 (insert "[" label "]")
479 (message "New reference to existing note"))
480 (org-footnote-define-inline
481 (insert "[" label ": ]")
482 (backward-char 1)
483 (org-footnote-auto-adjust-maybe))
485 (insert "[" label "]")
486 (org-footnote-create-definition label)
487 (org-footnote-auto-adjust-maybe))))))
489 (defvar org-blank-before-new-entry) ; silence byte-compiler
490 (defun org-footnote-create-definition (label)
491 "Start the definition of a footnote with label LABEL."
492 (interactive "sLabel: ")
493 (let ((label (org-footnote-normalize-label label))
494 electric-indent-mode) ;; Prevent wrong indentation
495 (cond
496 ;; In an Org file.
497 ((derived-mode-p 'org-mode)
498 ;; If `org-footnote-section' is defined, find it, or create it
499 ;; at the end of the buffer.
500 (when org-footnote-section
501 (goto-char (point-min))
502 (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
503 (unless (or (re-search-forward re nil t)
504 (and (progn (widen) t)
505 (re-search-forward re nil t)))
506 (goto-char (point-max))
507 (skip-chars-backward " \t\r\n")
508 (unless (bolp) (newline))
509 ;; Insert new section. Separate it from the previous one
510 ;; with a blank line, unless `org-blank-before-new-entry'
511 ;; explicitly says no.
512 (when (and (cdr (assq 'heading org-blank-before-new-entry))
513 (zerop (save-excursion (org-back-over-empty-lines))))
514 (insert "\n"))
515 (insert "* " org-footnote-section "\n"))))
516 ;; Move to the end of this entry (which may be
517 ;; `org-footnote-section' or the current one).
518 (org-footnote-goto-local-insertion-point)
519 (org-show-context 'link-search))
521 ;; In a non-Org file. Search for footnote tag, or create it if
522 ;; specified (at the end of buffer, or before signature if in
523 ;; Message mode). Set point after any definition already there.
524 (let ((tag (and org-footnote-tag-for-non-org-mode-files
525 (concat "^" (regexp-quote
526 org-footnote-tag-for-non-org-mode-files)
527 "[ \t]*$")))
528 (max (if (and (derived-mode-p 'message-mode)
529 (goto-char (point-max))
530 (re-search-backward
531 message-signature-separator nil t))
532 (progn
533 ;; Ensure one blank line separates last
534 ;; footnote from signature.
535 (beginning-of-line)
536 (open-line 2)
537 (point-marker))
538 (point-max-marker))))
539 (set-marker-insertion-type max t)
540 (goto-char max)
541 ;; Check if the footnote tag is defined but missing. In this
542 ;; case, insert it, before any footnote or one blank line
543 ;; after any previous text.
544 (when (and tag (not (re-search-backward tag nil t)))
545 (skip-chars-backward " \t\r\n")
546 (while (re-search-backward org-footnote-definition-re nil t))
547 (unless (bolp) (newline 2))
548 (insert org-footnote-tag-for-non-org-mode-files "\n\n"))
549 ;; Remove superfluous white space and clear marker.
550 (goto-char max)
551 (skip-chars-backward " \t\r\n")
552 (delete-region (point) max)
553 (unless (bolp) (newline))
554 (set-marker max nil))))
555 ;; Insert footnote label.
556 (when (zerop (org-back-over-empty-lines)) (newline))
557 (insert "[" label "] \n")
558 (backward-char)
559 ;; Only notify user about next possible action when in an Org
560 ;; buffer, as the bindings may have different meanings otherwise.
561 (when (derived-mode-p 'org-mode)
562 (message
563 "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
565 ;;;###autoload
566 (defun org-footnote-action (&optional special)
567 "Do the right thing for footnotes.
569 When at a footnote reference, jump to the definition.
571 When at a definition, jump to the references if they exist, offer
572 to create them otherwise.
574 When neither at definition or reference, create a new footnote,
575 interactively.
577 With prefix arg SPECIAL, offer additional commands in a menu."
578 (interactive "P")
579 (let (tmp c)
580 (cond
581 (special
582 (message "Footnotes: [s]ort, [r]enumber fn:N, [S]=r+s, ->[n]umeric, [d]elete, [i]inline")
583 (setq c (read-char-exclusive))
584 (cond
585 ((eq c ?i) (org-footnote-inline-footnotes))
586 ((eq c ?s) (org-footnote-normalize 'sort))
587 ((eq c ?r) (org-footnote-renumber-fn:N))
588 ((eq c ?S)
589 (org-footnote-renumber-fn:N)
590 (org-footnote-normalize 'sort))
591 ((eq c ?n) (org-footnote-normalize))
592 ((eq c ?d) (org-footnote-delete))
593 (t (error "No such footnote command %c" c))))
594 ((setq tmp (org-footnote-at-reference-p))
595 (cond
596 ;; Anonymous footnote: move point at the beginning of its
597 ;; definition.
598 ((not (car tmp))
599 (goto-char (nth 1 tmp))
600 (forward-char 5))
601 ;; A definition exists: move to it.
602 ((ignore-errors (org-footnote-goto-definition (car tmp))))
603 ;; No definition exists: offer to create it.
604 ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
605 (org-footnote-create-definition (car tmp)))))
606 ((setq tmp (org-footnote-at-definition-p))
607 (org-footnote-goto-previous-reference (car tmp)))
608 (t (org-footnote-new)))))
610 ;;;###autoload
611 (defun org-footnote-normalize (&optional sort-only)
612 "Collect the footnotes in various formats and normalize them.
614 This finds the different sorts of footnotes allowed in Org, and
615 normalizes them to the usual [N] format.
617 When SORT-ONLY is set, only sort the footnote definitions into the
618 referenced sequence."
619 ;; This is based on Paul's function, but rewritten.
621 ;; Re-create `org-with-limited-levels', but not limited to Org
622 ;; buffers.
623 (let* ((limit-level
624 (and (boundp 'org-inlinetask-min-level)
625 org-inlinetask-min-level
626 (1- org-inlinetask-min-level)))
627 (nstars (and limit-level
628 (if org-odd-levels-only (1- (* limit-level 2))
629 limit-level)))
630 (org-outline-regexp
631 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
632 (count 0)
633 ins-point ref ref-table)
634 (save-excursion
635 ;; 1. Find every footnote reference, extract the definition, and
636 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
637 ;; normalize references.
638 (goto-char (point-min))
639 (while (setq ref (org-footnote-get-next-reference))
640 (let* ((lbl (car ref))
641 (pos (nth 1 ref))
642 ;; When footnote isn't anonymous, check if it's label
643 ;; (REF) is already stored in REF-TABLE. In that case,
644 ;; extract number used to identify it (MARKER). If
645 ;; footnote is unknown, increment the global counter
646 ;; (COUNT) to create an unused identifier.
647 (a (and lbl (assoc lbl ref-table)))
648 (marker (or (nth 1 a) (incf count)))
649 ;; Is the reference inline or pointing to an inline
650 ;; footnote?
651 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
652 ;; Replace footnote reference with [MARKER]. Maybe fill
653 ;; paragraph once done. If SORT-ONLY is non-nil, only move
654 ;; to the end of reference found to avoid matching it twice.
655 (if sort-only (goto-char (nth 2 ref))
656 (delete-region (nth 1 ref) (nth 2 ref))
657 (goto-char (nth 1 ref))
658 (insert (format "[%d]" marker))
659 (and inlinep
660 org-footnote-fill-after-inline-note-extraction
661 (org-fill-paragraph)))
662 ;; Add label (REF), identifier (MARKER), definition (DEF)
663 ;; type (INLINEP) and position (POS) to REF-TABLE if data
664 ;; was unknown.
665 (unless a
666 (let ((def (or (nth 3 ref) ; Inline definition.
667 (nth 3 (org-footnote-get-definition lbl)))))
668 (push (list lbl marker def
669 ;; Reference beginning position is a marker
670 ;; to preserve it during further buffer
671 ;; modifications.
672 inlinep (copy-marker pos)) ref-table)))))
673 ;; 2. Find and remove the footnote section, if any. Also
674 ;; determine where footnotes shall be inserted (INS-POINT).
675 (cond
676 ((and org-footnote-section (derived-mode-p 'org-mode))
677 (goto-char (point-min))
678 (if (re-search-forward
679 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
680 "[ \t]*$") nil t)
681 (delete-region (match-beginning 0) (org-end-of-subtree t t)))
682 ;; A new footnote section is inserted by default at the end of
683 ;; the buffer.
684 (goto-char (point-max))
685 (skip-chars-backward " \r\t\n")
686 (forward-line)
687 (unless (bolp) (newline)))
688 ;; No footnote section set: Footnotes will be added at the end
689 ;; of the section containing their first reference.
690 ((derived-mode-p 'org-mode))
692 ;; Remove any left-over tag in the buffer, if one is set up.
693 (when org-footnote-tag-for-non-org-mode-files
694 (let ((tag (concat "^" (regexp-quote
695 org-footnote-tag-for-non-org-mode-files)
696 "[ \t]*$")))
697 (goto-char (point-min))
698 (while (re-search-forward tag nil t)
699 (replace-match "")
700 (delete-region (point) (progn (forward-line) (point))))))
701 ;; In Message mode, ensure footnotes are inserted before the
702 ;; signature.
703 (if (and (derived-mode-p 'message-mode)
704 (goto-char (point-max))
705 (re-search-backward message-signature-separator nil t))
706 (beginning-of-line)
707 (goto-char (point-max)))))
708 (setq ins-point (point-marker))
709 ;; 3. Clean-up REF-TABLE.
710 (setq ref-table
711 (delq nil
712 (mapcar
713 (lambda (x)
714 (cond
715 ;; When only sorting, ignore inline footnotes.
716 ;; Also clear position marker.
717 ((and sort-only (nth 3 x))
718 (set-marker (nth 4 x) nil) nil)
719 ;; No definition available: provide one.
720 ((not (nth 2 x))
721 (append
722 (list (car x) (nth 1 x)
723 (format "DEFINITION NOT FOUND: %s" (car x)))
724 (nthcdr 3 x)))
725 (t x)))
726 ref-table)))
727 (setq ref-table (nreverse ref-table))
728 ;; 4. Remove left-over definitions in the buffer.
729 (mapc (lambda (x)
730 (unless (nth 3 x) (org-footnote-delete-definitions (car x))))
731 ref-table)
732 ;; 5. Insert the footnotes again in the buffer, at the
733 ;; appropriate spot.
734 (goto-char ins-point)
735 (cond
736 ;; No footnote: exit.
737 ((not ref-table))
738 ;; Cases when footnotes should be inserted in one place.
739 ((or (not (derived-mode-p 'org-mode)) org-footnote-section)
740 ;; Insert again the section title, if any. Ensure that title,
741 ;; or the subsequent footnotes, will be separated by a blank
742 ;; lines from the rest of the document. In an Org buffer,
743 ;; separate section with a blank line, unless explicitly
744 ;; stated in `org-blank-before-new-entry'.
745 (if (not (derived-mode-p 'org-mode))
746 (progn (skip-chars-backward " \t\n\r")
747 (delete-region (point) ins-point)
748 (unless (bolp) (newline))
749 (when org-footnote-tag-for-non-org-mode-files
750 (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
751 (when (and (cdr (assq 'heading org-blank-before-new-entry))
752 (zerop (save-excursion (org-back-over-empty-lines))))
753 (insert "\n"))
754 (insert "* " org-footnote-section "\n"))
755 (set-marker ins-point nil)
756 ;; Insert the footnotes, separated by a blank line.
757 (insert
758 (mapconcat
759 (lambda (x)
760 ;; Clean markers.
761 (set-marker (nth 4 x) nil)
762 (format "\n[%s] %s" (nth (if sort-only 0 1) x) (nth 2 x)))
763 ref-table "\n"))
764 (unless (eobp) (insert "\n\n")))
765 ;; Each footnote definition has to be inserted at the end of
766 ;; the section where its first reference belongs.
768 (mapc
769 (lambda (x)
770 (let ((pos (nth 4 x)))
771 (goto-char pos)
772 ;; Clean marker.
773 (set-marker pos nil))
774 (org-footnote-goto-local-insertion-point)
775 (insert (format "\n[%s] %s\n"
776 (if sort-only (car x) (nth 1 x))
777 (nth 2 x))))
778 ref-table))))))
780 (defun org-footnote-goto-local-insertion-point ()
781 "Find insertion point for footnote, just before next outline heading."
782 (org-with-limited-levels (outline-next-heading))
783 (or (bolp) (newline))
784 (beginning-of-line 0)
785 (while (and (not (bobp)) (= (char-after) ?#))
786 (beginning-of-line 0))
787 (if (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:")) (beginning-of-line 2))
788 (end-of-line 1)
789 (skip-chars-backward "\n\r\t ")
790 (forward-line))
792 (defun org-footnote-delete-references (label)
793 "Delete every reference to footnote LABEL.
794 Return the number of footnotes removed."
795 (save-excursion
796 (goto-char (point-min))
797 (let (ref (nref 0))
798 (while (setq ref (org-footnote-get-next-reference label))
799 (goto-char (nth 1 ref))
800 (delete-region (nth 1 ref) (nth 2 ref))
801 (incf nref))
802 nref)))
804 (defun org-footnote-delete-definitions (label)
805 "Delete every definition of the footnote LABEL.
806 Return the number of footnotes removed."
807 (save-excursion
808 (goto-char (point-min))
809 (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
810 (ndef 0))
811 (while (re-search-forward def-re nil t)
812 (let ((full-def (org-footnote-at-definition-p)))
813 (when full-def
814 ;; Remove the footnote, and all blank lines before it.
815 (goto-char (nth 1 full-def))
816 (skip-chars-backward " \r\t\n")
817 (unless (bolp) (forward-line))
818 (delete-region (point) (nth 2 full-def))
819 (incf ndef))))
820 ndef)))
822 (defun org-footnote-delete (&optional label)
823 "Delete the footnote at point.
824 This will remove the definition (even multiple definitions if they exist)
825 and all references of a footnote label.
827 If LABEL is non-nil, delete that footnote instead."
828 (catch 'done
829 (let* ((nref 0) (ndef 0) x
830 ;; 1. Determine LABEL of footnote at point.
831 (label (cond
832 ;; LABEL is provided as argument.
833 (label)
834 ;; Footnote reference at point. If the footnote is
835 ;; anonymous, delete it and exit instead.
836 ((setq x (org-footnote-at-reference-p))
837 (or (car x)
838 (progn
839 (delete-region (nth 1 x) (nth 2 x))
840 (message "Anonymous footnote removed")
841 (throw 'done t))))
842 ;; Footnote definition at point.
843 ((setq x (org-footnote-at-definition-p))
844 (car x))
845 (t (error "Don't know which footnote to remove")))))
846 ;; 2. Now that LABEL is non-nil, find every reference and every
847 ;; definition, and delete them.
848 (setq nref (org-footnote-delete-references label)
849 ndef (org-footnote-delete-definitions label))
850 ;; 3. Verify consistency of footnotes and notify user.
851 (org-footnote-auto-adjust-maybe)
852 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
853 ndef nref label))))
855 (defun org-footnote-renumber-fn:N ()
856 "Renumber the simple footnotes like fn:17 into a sequence in the document."
857 (interactive)
858 (let (map (n 0))
859 (org-with-wide-buffer
860 (goto-char (point-min))
861 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
862 (save-excursion
863 (goto-char (match-beginning 0))
864 ;; Ensure match is a footnote reference or definition.
865 (when (save-match-data (if (bolp)
866 (org-footnote-at-definition-p)
867 (org-footnote-at-reference-p)))
868 (let ((new-val (or (cdr (assoc (match-string 1) map))
869 (number-to-string (incf n)))))
870 (unless (assoc (match-string 1) map)
871 (push (cons (match-string 1) new-val) map))
872 (replace-match new-val nil nil nil 1))))))))
874 (defun org-footnote-inline-footnotes ()
875 "Convert external footnotes into inline ones."
876 (interactive)
877 (org-with-wide-buffer
878 (goto-char (point-min))
879 (while (re-search-forward (concat org-footnote-re "\\]") nil t)
880 (let ((fn (match-string 0)) fnd-end repl)
881 (save-excursion
882 (save-match-data
883 (when (and (re-search-forward (regexp-quote fn) nil t)
884 (eq (car (org-element-at-point)) 'footnote-definition))
885 (beginning-of-line)
886 (setq fnd-end (save-excursion (org-forward-element) (point)))
887 (setq repl (org-trim
888 (replace-regexp-in-string
889 (concat "\n\\|" org-footnote-re "\\]")
890 " " (buffer-substring (point) fnd-end))))
891 (delete-region (point) fnd-end))))
892 (replace-match (format "[fn::%s]" repl))))
893 (goto-char (point-min))
894 ;; Delete the * Footnotes heading
895 (when (re-search-forward (concat org-outline-regexp-bol org-footnote-section) nil t)
896 (replace-match ""))))
898 (defun org-footnote-auto-adjust-maybe ()
899 "Renumber and/or sort footnotes according to user settings."
900 (when (memq org-footnote-auto-adjust '(t renumber))
901 (org-footnote-renumber-fn:N))
902 (when (memq org-footnote-auto-adjust '(t sort))
903 (let ((label (car (org-footnote-at-definition-p))))
904 (org-footnote-normalize 'sort)
905 (when label
906 (goto-char (point-min))
907 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
908 nil t)
909 (progn (insert " ")
910 (just-one-space)))))))
912 (provide 'org-footnote)
914 ;; Local variables:
915 ;; generated-autoload-file: "org-loaddefs.el"
916 ;; End:
918 ;;; org-footnote.el ends here