org-indent.el: tiny docstring fix.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org-footnote.el
blob41ac50e7c57c86e5c9268bfc82ff6e0d0a8ecb0d
1 ;;; org-footnote.el --- Footnote support in Org and elsewhere
2 ;;
3 ;; Copyright (C) 2009, 2010 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 ;; Version: 7.5
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; This file contains the code dealing with footnotes in Org-mode.
29 ;; The code can also be used in arbitrary text modes to provide
30 ;; footnotes. Compared to Steven L Baur's footnote.el it provides
31 ;; better support for resuming editing. It is less configurable than
32 ;; Steve's code, though.
34 ;;; Code:
36 (eval-when-compile
37 (require 'cl))
38 (require 'org-macs)
39 (require 'org-compat)
41 (declare-function org-in-commented-line "org" ())
42 (declare-function org-in-regexp "org" (re &optional nlines visually))
43 (declare-function org-mark-ring-push "org" (&optional pos buffer))
44 (declare-function outline-next-heading "outline")
45 (declare-function org-trim "org" (s))
46 (declare-function org-show-context "org" (&optional key))
47 (declare-function org-back-to-heading "org" (&optional invisible-ok))
48 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
49 (declare-function org-in-verbatim-emphasis "org" ())
50 (declare-function org-inside-latex-macro-p "org" ())
51 (declare-function org-id-uuid "org" ())
52 (declare-function org-fill-paragraph "org" (&optional justify))
53 (defvar org-odd-levels-only) ;; defined in org.el
54 (defvar message-signature-separator) ;; defined in message.el
56 (defconst org-footnote-re
57 ;; Only [1]-like footnotes are closed in this regexp, as footnotes
58 ;; from other types might contain square brackets (i.e. links) in
59 ;; their definition.
61 ;; `org-re' is used for regexp compatibility with XEmacs.
62 (org-re (concat "\\[\\(?:"
63 ;; Match inline footnotes.
64 "fn:\\([-_[:word:]]+\\)?:\\|"
65 ;; Match other footnotes.
66 "\\(?:\\([0-9]+\\)\\]\\)\\|"
67 "\\(fn:[-_[:word:]]+\\)"
68 "\\)"))
69 "Regular expression for matching footnotes.")
71 (defconst org-footnote-definition-re
72 (org-re "^\\(\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]\\)")
73 "Regular expression matching the definition of a footnote.")
75 (defgroup org-footnote nil
76 "Footnotes in Org-mode."
77 :tag "Org Footnote"
78 :group 'org)
80 (defcustom org-footnote-section "Footnotes"
81 "Outline heading containing footnote definitions before export.
82 This can be nil, to place footnotes locally at the end of the current
83 outline node. If can also be the name of a special outline heading
84 under which footnotes should be put.
85 This variable defines the place where Org puts the definition
86 automatically, i.e. when creating the footnote, and when sorting the notes.
87 However, by hand you may place definitions *anywhere*.
88 If this is a string, during export, all subtrees starting with this
89 heading will be removed after extracting footnote definitions."
90 :group 'org-footnote
91 :type '(choice
92 (string :tag "Collect footnotes under heading")
93 (const :tag "Define footnotes locally" nil)))
95 (defcustom org-footnote-tag-for-non-org-mode-files "Footnotes:"
96 "Tag marking the beginning of footnote section.
97 The Org-mode footnote engine can be used in arbitrary text files as well
98 as in Org-mode. Outside Org-mode, new footnotes are always placed at
99 the end of the file. When you normalize the notes, any line containing
100 only this tag will be removed, a new one will be inserted at the end
101 of the file, followed by the collected and normalized footnotes."
102 :group 'org-footnote
103 :type 'string)
105 (defcustom org-footnote-define-inline nil
106 "Non-nil means define footnotes inline, at reference location.
107 When nil, footnotes will be defined in a special section near
108 the end of the document. When t, the [fn:label:definition] notation
109 will be used to define the footnote at the reference position."
110 :group 'org-footnote
111 :type 'boolean)
113 (defcustom org-footnote-auto-label t
114 "Non-nil means define automatically new labels for footnotes.
115 Possible values are:
117 nil prompt the user for each label
118 t create unique labels of the form [fn:1], [fn:2], ...
119 confirm like t, but let the user edit the created value. In particular,
120 the label can be removed from the minibuffer, to create
121 an anonymous footnote.
122 random Automatically generate a unique, random label.
123 plain Automatically create plain number labels like [1]"
124 :group 'org-footnote
125 :type '(choice
126 (const :tag "Prompt for label" nil)
127 (const :tag "Create automatic [fn:N]" t)
128 (const :tag "Offer automatic [fn:N] for editing" confirm)
129 (const :tag "Create a random label" random)
130 (const :tag "Create automatic [N]" plain)))
132 (defcustom org-footnote-auto-adjust nil
133 "Non-nil means automatically adjust footnotes after insert/delete.
134 When this is t, after each insertion or deletion of a footnote,
135 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
136 If you want to have just sorting or just renumbering, set this variable
137 to `sort' or `renumber'.
139 The main values of this variable can be set with in-buffer options:
141 #+STARTUP: fnadjust
142 #+STARTUP: nofnadjust"
143 :group 'org-footnote
144 :type '(choice
145 (const :tag "Renumber" renumber)
146 (const :tag "Sort" sort)
147 (const :tag "Renumber and Sort" t)))
149 (defcustom org-footnote-fill-after-inline-note-extraction nil
150 "Non-nil means fill paragraphs after extracting footnotes.
151 When extracting inline footnotes, the lengths of lines can change a lot.
152 When this option is set, paragraphs from which an inline footnote has been
153 extracted will be filled again."
154 :group 'org-footnote
155 :type 'boolean)
157 (defun org-footnote-at-reference-p ()
158 "Is the cursor at a footnote reference?
160 If so, return an list containing its label, beginning and ending
161 positions, and the definition, if local."
162 (when (and (not (or (org-in-commented-line)
163 (org-in-verbatim-emphasis)))
164 (or (looking-at org-footnote-re)
165 (org-in-regexp org-footnote-re)
166 (save-excursion (re-search-backward org-footnote-re nil t)))
167 ;; A footnote reference cannot start at bol.
168 (/= (match-beginning 0) (point-at-bol)))
169 (let* ((beg (match-beginning 0))
170 (label (or (match-string 2) (match-string 3)
171 ;; Anonymous footnotes don't have labels
172 (and (match-string 1) (concat "fn:" (match-string 1)))))
173 ;; Inline footnotes don't end at (match-end 0) as
174 ;; `org-footnote-re' stops just after the second colon.
175 ;; Find the real ending with `scan-sexps', so Org doesn't
176 ;; get fooled by unrelated closing square brackets.
177 (end (ignore-errors (scan-sexps beg 1))))
178 ;; Point is really at a reference if it's located before true
179 ;; ending of the footnote and isn't within a link or a LaTeX
180 ;; macro. About that case, some special attention should be
181 ;; paid. Indeed, when two footnotes are side by side, once the
182 ;; first one is changed into LaTeX, the second one might then be
183 ;; considered as an optional argument of the command. To
184 ;; prevent that, we have a look at the `org-protected' property
185 ;; of that LaTeX command.
186 (when (and end (< (point) end)
187 (not (save-excursion
188 (goto-char beg)
189 (let ((linkp
190 (save-match-data
191 (org-in-regexp org-bracket-link-regexp))))
192 (and linkp (< (point) (cdr linkp))))))
193 (or (not (org-inside-latex-macro-p))
194 (and (get-text-property (1- beg) 'org-protected)
195 (not (get-text-property beg 'org-protected)))))
196 (list label beg end
197 ;; Definition: ensure this is an inline footnote first.
198 (and (or (not label) (match-string 1))
199 (org-trim (buffer-substring (match-end 0) (1- end)))))))))
201 (defun org-footnote-at-definition-p ()
202 "Is the cursor at a footnote definition?
204 This matches only pure definitions like [1] or [fn:name] at the beginning
205 of a line. It does not match references like [fn:name:definition], where the
206 footnote text is included and defined locally.
208 The return value will be nil if not at a footnote definition, and a list with
209 label, start, end and definition of the footnote otherwise."
210 (save-excursion
211 (end-of-line)
212 (let ((lim (save-excursion (re-search-backward "^\\*+ \\|^[ \t]*$" nil t))))
213 (when (re-search-backward org-footnote-definition-re lim t)
214 (end-of-line)
215 (list (match-string 2)
216 (match-beginning 0)
217 (save-match-data
218 (or (and (re-search-forward
219 (org-re "^[ \t]*$\\|^\\*+ \\|^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
220 nil t)
221 (progn (skip-chars-forward " \t\n") (point-at-bol)))
222 (point-max)))
223 (org-trim (buffer-substring (match-end 0) (point))))))))
225 (defun org-footnote-get-next-reference (&optional label backward limit)
226 "Return complete reference of the next footnote.
228 If LABEL is provided, get the next reference of that footnote. If
229 BACKWARD is non-nil, find previous reference instead. LIMIT is
230 the buffer position bounding the search.
232 Return value is a list like those provided by `org-footnote-at-reference-p'.
233 If no footnote is found, return nil."
234 (save-excursion
235 (let* ((label-fmt (if label (format "\\[%s[]:]" label) org-footnote-re)))
236 (catch 'exit
237 (while t
238 (unless (funcall (if backward #'re-search-backward #'re-search-forward)
239 label-fmt limit t)
240 (throw 'exit nil))
241 (unless backward (backward-char))
242 (let ((ref (org-footnote-at-reference-p)))
243 (when ref (throw 'exit ref))))))))
245 (defun org-footnote-next-reference-or-definition (limit)
246 "Move point to next footnote reference or definition.
248 LIMIT is the buffer position bounding the search.
250 Return value is a list like those provided by
251 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
252 If no footnote is found, return nil."
253 (let* (ref)
254 (catch 'exit
255 (while t
256 (unless (re-search-forward org-footnote-re limit t)
257 (throw 'exit nil))
258 ;; Beware: with [1]-like footnotes point will be just after
259 ;; the closing square bracket.
260 (backward-char)
261 (cond
262 ((setq ref (org-footnote-at-reference-p))
263 (throw 'exit ref))
264 ;; Definition: also grab the last square bracket, only
265 ;; matched in `org-footnote-re' for [1]-like footnotes.
266 ((save-match-data (org-footnote-at-definition-p))
267 (let ((end (match-end 0)))
268 (throw 'exit
269 (list nil (match-beginning 0)
270 (if (eq (char-before end) 93) end (1+ end)))))))))))
272 (defun org-footnote-get-definition (label)
273 "Return label, boundaries and definition of the footnote LABEL."
274 (let* ((label (regexp-quote (org-footnote-normalize-label label)))
275 (re (format "^\\[%s\\]\\|.\\[%s:" label label))
276 pos)
277 (save-excursion
278 (when (or (re-search-forward re nil t)
279 (and (goto-char (point-min))
280 (re-search-forward re nil t))
281 (and (progn (widen) t)
282 (goto-char (point-min))
283 (re-search-forward re nil t)))
284 (let ((refp (org-footnote-at-reference-p)))
285 (cond
286 ((and (nth 3 refp) refp))
287 ((org-footnote-at-definition-p))))))))
289 (defun org-footnote-goto-definition (label)
290 "Move point to the definition of the footnote LABEL."
291 (interactive "sLabel: ")
292 (org-mark-ring-push)
293 (let ((def (org-footnote-get-definition label)))
294 (if (not def)
295 (error "Cannot find definition of footnote %s" label)
296 (goto-char (nth 1 def))
297 (looking-at (format "\\[%s\\]\\|\\[%s:" label label))
298 (goto-char (match-end 0))
299 (org-show-context 'link-search)
300 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
302 (defun org-footnote-goto-previous-reference (label)
303 "Find the first closest (to point) reference of footnote with label LABEL."
304 (interactive "sLabel: ")
305 (org-mark-ring-push)
306 (let* ((label (org-footnote-normalize-label label)) ref)
307 (save-excursion
308 (setq ref (or (org-footnote-get-next-reference label t)
309 (org-footnote-get-next-reference label)
310 (save-restriction
311 (widen)
313 (org-footnote-get-next-reference label t)
314 (org-footnote-get-next-reference label))))))
315 (if (not ref)
316 (error "Cannot find reference of footnote %s" label)
317 (goto-char (nth 1 ref))
318 (org-show-context 'link-search))))
320 (defun org-footnote-normalize-label (label)
321 "Return LABEL as an appropriate string."
322 (cond
323 ((numberp label) (number-to-string label))
324 ((equal "" label) nil)
325 ((not (string-match "^[0-9]+$\\|^fn:" label))
326 (concat "fn:" label))
327 (t label)))
329 (defun org-footnote-all-labels (&optional with-defs)
330 "Return list with all defined foot labels used in the buffer.
332 If WITH-DEFS is non-nil, also associate the definition to each
333 label. The function will then return an alist whose key is label
334 and value definition."
335 (let* (rtn
336 (push-to-rtn
337 (function
338 ;; Depending on WITH-DEFS, store label or (label . def) of
339 ;; footnote reference/definition given as argument in RTN.
340 (lambda (el)
341 (let ((lbl (car el)))
342 (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
343 (save-excursion
344 (save-restriction
345 (widen)
346 ;; Find all labels found in definitions.
347 (goto-char (point-min))
348 (let (def)
349 (while (re-search-forward org-footnote-definition-re nil t)
350 (when (setq def (org-footnote-at-definition-p))
351 (funcall push-to-rtn def))))
352 ;; Find all labels found in references.
353 (goto-char (point-min))
354 (let (ref)
355 (while (setq ref (org-footnote-get-next-reference))
356 (goto-char (nth 2 ref))
357 (and (car ref) ; ignore anonymous footnotes
358 (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
359 (funcall push-to-rtn ref))))))
360 rtn))
362 (defun org-footnote-unique-label (&optional current)
363 "Return a new unique footnote label.
364 The returns the firsts fn:N labels that is currently not used."
365 (unless current (setq current (org-footnote-all-labels)))
366 (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
367 (cnt 1))
368 (while (member (format fmt cnt) current)
369 (incf cnt))
370 (format fmt cnt)))
372 (defvar org-footnote-label-history nil
373 "History of footnote labels entered in current buffer.")
374 (make-variable-buffer-local 'org-footnote-label-history)
376 (defun org-footnote-new ()
377 "Insert a new footnote.
378 This command prompts for a label. If this is a label referencing an
379 existing label, only insert the label. If the footnote label is empty
380 or new, let the user edit the definition of the footnote."
381 (interactive)
382 (let* ((labels (and (not (equal org-footnote-auto-label 'random))
383 (org-footnote-all-labels)))
384 (propose (org-footnote-unique-label labels))
385 (label
386 (org-footnote-normalize-label
387 (cond
388 ((member org-footnote-auto-label '(t plain))
389 propose)
390 ((equal org-footnote-auto-label 'random)
391 (require 'org-id)
392 (substring (org-id-uuid) 0 8))
394 (completing-read
395 "Label (leave empty for anonymous): "
396 (mapcar 'list labels) nil nil
397 (if (eq org-footnote-auto-label 'confirm) propose nil)
398 'org-footnote-label-history))))))
399 (cond
400 ((not label)
401 (insert "[fn:: ]")
402 (backward-char 1))
403 ((member label labels)
404 (insert "[" label "]")
405 (message "New reference to existing note"))
406 (org-footnote-define-inline
407 (insert "[" label ": ]")
408 (backward-char 1)
409 (org-footnote-auto-adjust-maybe))
411 (insert "[" label "]")
412 (org-footnote-create-definition label)
413 (org-footnote-auto-adjust-maybe)))))
415 (defun org-footnote-create-definition (label)
416 "Start the definition of a footnote with label LABEL."
417 (interactive "sLabel: ")
418 (let ((label (org-footnote-normalize-label label)))
419 (cond
420 ((org-mode-p)
421 ;; No section, put footnote into the current outline node Try to
422 ;; find or make the special node
423 (when org-footnote-section
424 (goto-char (point-min))
425 (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
426 (unless (or (re-search-forward re nil t)
427 (and (progn (widen) t)
428 (re-search-forward re nil t)))
429 (goto-char (point-max))
430 (insert "\n\n* " org-footnote-section "\n"))))
431 ;; Now go to the end of this entry and insert there.
432 (org-footnote-goto-local-insertion-point)
433 (org-show-context 'link-search))
435 (let ((re (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$")))
436 (unless (re-search-forward re nil t)
437 (let ((max (if (and (derived-mode-p 'message-mode)
438 (re-search-forward message-signature-separator nil t))
439 (progn (beginning-of-line) (point))
440 (goto-char (point-max)))))
441 (skip-chars-backward " \t\r\n")
442 (delete-region (point) max)
443 (insert "\n\n")
444 (insert org-footnote-tag-for-non-org-mode-files "\n"))))
445 ;; Skip existing footnotes
446 (while (re-search-forward "^[[:space:]]*\\[[^]]+\\] " nil t)
447 (forward-line))))
448 (insert "\n[" label "] \n")
449 (goto-char (1- (point)))
450 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
452 ;;;###autoload
453 (defun org-footnote-action (&optional special)
454 "Do the right thing for footnotes.
456 When at a footnote reference, jump to the definition.
458 When at a definition, jump to the references if they exist, offer
459 to create them otherwise.
461 When neither at definition or reference, create a new footnote,
462 interactively.
464 With prefix arg SPECIAL, offer additional commands in a menu."
465 (interactive "P")
466 (let (tmp c)
467 (cond
468 (special
469 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
470 (setq c (read-char-exclusive))
471 (cond
472 ((eq c ?s) (org-footnote-normalize 'sort))
473 ((eq c ?r) (org-footnote-renumber-fn:N))
474 ((eq c ?S)
475 (org-footnote-renumber-fn:N)
476 (org-footnote-normalize 'sort))
477 ((eq c ?n) (org-footnote-normalize))
478 ((eq c ?d) (org-footnote-delete))
479 (t (error "No such footnote command %c" c))))
480 ((setq tmp (org-footnote-at-reference-p))
481 (cond
482 ;; Anonymous footnote: move point at the beginning of its
483 ;; definition.
484 ((not (car tmp))
485 (goto-char (nth 1 tmp))
486 (forward-char 5))
487 ;; A definition exists: move to it.
488 ((ignore-errors (org-footnote-goto-definition (car tmp))))
489 ;; No definition exists: offer to create it.
490 ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
491 (org-footnote-create-definition (car tmp)))))
492 ((setq tmp (org-footnote-at-definition-p))
493 (org-footnote-goto-previous-reference (car tmp)))
494 (t (org-footnote-new)))))
496 (defvar org-footnote-insert-pos-for-preprocessor 'point-max
497 "See `org-footnote-normalize'.")
499 (defvar org-export-footnotes-seen nil) ; silence byte-compiler
500 (defvar org-export-footnotes-data nil) ; silence byte-compiler
502 ;;;###autoload
503 (defun org-footnote-normalize (&optional sort-only pre-process-p)
504 "Collect the footnotes in various formats and normalize them.
506 This finds the different sorts of footnotes allowed in Org, and
507 normalizes them to the usual [N] format that is understood by the
508 Org-mode exporters.
510 When SORT-ONLY is set, only sort the footnote definitions into the
511 referenced sequence.
513 When PRE-PROCESS-P is non-nil, the default action, is to insert
514 normalized footnotes towards the end of the pre-processing buffer.
515 Some exporters like docbook, odt, etc. expect that footnote
516 definitions be available before any references to them. Such
517 exporters can let bind `org-footnote-insert-pos-for-preprocessor' to
518 symbol 'point-min to achieve the desired behaviour.
520 Additional note on `org-footnote-insert-pos-for-preprocessor':
521 1. This variable has not effect when FOR-PREPROCESSOR is nil.
522 2. This variable (potentially) obviates the need for extra scan
523 of pre-processor buffer as witnessed in
524 `org-export-docbook-get-footnotes'."
525 ;; This is based on Paul's function, but rewritten.
527 ;; Re-create `org-with-limited-levels', but not limited to Org
528 ;; buffers.
529 (let* ((limit-level
530 (and (boundp 'org-inlinetask-min-level)
531 org-inlinetask-min-level
532 (1- org-inlinetask-min-level)))
533 (nstars (and limit-level
534 (if org-odd-levels-only
535 (and limit-level (1- (* limit-level 2)))
536 limit-level)))
537 (outline-regexp
538 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
539 ;; Determine the highest marker used so far.
540 (ref-table (when pre-process-p org-export-footnotes-seen))
541 (count (if (and pre-process-p ref-table)
542 (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
544 ins-point ref)
545 (save-excursion
546 ;; 1. Find every footnote reference, extract the definition, and
547 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
548 ;; normalize references.
549 (goto-char (point-min))
550 (while (setq ref (org-footnote-get-next-reference))
551 (let* ((lbl (car ref))
552 ;; When footnote isn't anonymous, check if it's label
553 ;; (REF) is already stored in REF-TABLE. In that case,
554 ;; extract number used to identify it (MARKER). If
555 ;; footnote is unknown, increment the global counter
556 ;; (COUNT) to create an unused identifier.
557 (a (and lbl (assoc lbl ref-table)))
558 (marker (or (nth 1 a) (incf count)))
559 ;; Is the reference inline or pointing to an inline
560 ;; footnote?
561 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
562 ;; Replace footnote reference with [MARKER]. Maybe fill
563 ;; paragraph once done. If SORT-ONLY is non-nil, only move
564 ;; to the end of reference found to avoid matching it twice.
565 ;; If PRE-PROCESS-P isn't nil, also add `org-footnote'
566 ;; property to it, so it can be easily recognized by
567 ;; exporters.
568 (if sort-only
569 (goto-char (nth 2 ref))
570 (delete-region (nth 1 ref) (nth 2 ref))
571 (goto-char (nth 1 ref))
572 (let ((new-ref (format "[%d]" marker)))
573 (when pre-process-p (org-add-props new-ref '(org-footnote t)))
574 (insert new-ref))
575 (and inlinep
576 org-footnote-fill-after-inline-note-extraction
577 (org-fill-paragraph)))
578 ;; Add label (REF), identifier (MARKER) and definition (DEF)
579 ;; to REF-TABLE if data was unknown.
580 (unless a
581 (let ((def (or (nth 3 ref) ; inline
582 (and pre-process-p
583 (cdr (assoc lbl org-export-footnotes-data)))
584 (nth 3 (org-footnote-get-definition lbl)))))
585 (push (list lbl marker def inlinep) ref-table)))
586 ;; Remove definition of non-inlined footnotes.
587 (unless inlinep (org-footnote-delete-definitions lbl))))
588 ;; 2. Find and remove the footnote section, if any. If we are
589 ;; exporting, insert it again at end of buffer. In a non
590 ;; org-mode file, insert instead
591 ;; `org-footnote-tag-for-non-org-mode-files'.
592 (goto-char (point-min))
593 (cond
594 ((org-mode-p)
595 (if (and org-footnote-section
596 (re-search-forward
597 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
598 "[ \t]*$")
599 nil t))
600 (if pre-process-p
601 (replace-match "")
602 (org-back-to-heading t)
603 (forward-line 1)
604 (setq ins-point (point))
605 (delete-region (point) (org-end-of-subtree t)))
606 (goto-char (point-max))
607 (unless pre-process-p
608 (when org-footnote-section
609 (or (bolp) (insert "\n"))
610 (insert "* " org-footnote-section "\n")
611 (setq ins-point (point))))))
613 (if (re-search-forward
614 (concat "^"
615 (regexp-quote org-footnote-tag-for-non-org-mode-files)
616 "[ \t]*$")
617 nil t)
618 (replace-match ""))
619 (goto-char (point-max))
620 (skip-chars-backward " \t\n\r")
621 (delete-region (point) (point-max))
622 (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n")
623 (setq ins-point (point))))
624 ;; 3. Clean-up REF-TABLE.
625 (setq ref-table
626 (delq nil
627 (mapcar
628 (lambda (x)
629 (cond
630 ;; When only sorting, ignore inline footnotes.
631 ((and sort-only (nth 3 x)) nil)
632 ;; No definition available: provide one.
633 ((not (nth 2 x))
634 (append (butlast x 2)
635 (list (format "DEFINITION NOT FOUND: %s" (car x))
636 (nth 3 x))))
637 (t x)))
638 ref-table)))
639 (setq ref-table (nreverse ref-table))
640 ;; 4. Insert the footnotes again in the buffer, at the
641 ;; appropriate spot.
642 (goto-char (or
643 (and pre-process-p
644 (eq org-footnote-insert-pos-for-preprocessor 'point-min)
645 (point-min))
646 ins-point
647 (point-max)))
648 (cond
649 ((not ref-table)) ; no footnote: exit
650 ;; Cases when footnotes should be inserted together in one place.
651 ((or (not (org-mode-p))
652 org-footnote-section
653 (not sort-only))
654 (insert "\n"
655 (mapconcat (lambda (x) (format "[%s] %s"
656 (nth (if sort-only 0 1) x) (nth 2 x)))
657 ref-table "\n\n")
658 "\n\n")
659 ;; When exporting, add newly insert markers along with their
660 ;; associated definition to `org-export-footnotes-seen'.
661 (when pre-process-p
662 (setq org-export-footnotes-seen ref-table)))
663 ;; Else, insert each definition at the end of the section
664 ;; containing their first reference. Happens only in Org
665 ;; files with no special footnote section, and only when
666 ;; doing sorting.
667 (t (mapc 'org-insert-footnote-reference-near-definition
668 ref-table))))))
670 (defun org-insert-footnote-reference-near-definition (entry)
671 "Find first reference of footnote ENTRY and insert the definition there.
672 ENTRY is (fn-label num-mark definition)."
673 (when (car entry)
674 (goto-char (point-min))
675 (let ((ref (org-footnote-get-next-reference (car entry))))
676 (when ref
677 (goto-char (nth 2 ref))
678 (org-footnote-goto-local-insertion-point)
679 (insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
681 (defun org-footnote-goto-local-insertion-point ()
682 "Find insertion point for footnote, just before next outline heading."
683 (org-with-limited-levels (outline-next-heading))
684 (or (bolp) (newline))
685 (beginning-of-line 0)
686 (while (and (not (bobp)) (= (char-after) ?#))
687 (beginning-of-line 0))
688 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
689 (end-of-line 1)
690 (skip-chars-backward "\n\r\t ")
691 (forward-line))
693 (defun org-footnote-delete-references (label)
694 "Delete every reference to footnote LABEL.
695 Return the number of footnotes removed."
696 (save-excursion
697 (goto-char (point-min))
698 (let (ref (nref 0))
699 (while (setq ref (org-footnote-get-next-reference label))
700 (goto-char (nth 1 ref))
701 (delete-region (nth 1 ref) (nth 2 ref))
702 (incf nref))
703 nref)))
705 (defun org-footnote-delete-definitions (label)
706 "Delete every definition of the footnote LABEL.
707 Return the number of footnotes removed."
708 (save-excursion
709 (goto-char (point-min))
710 (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
711 (ndef 0))
712 (while (re-search-forward def-re nil t)
713 (let ((full-def (org-footnote-at-definition-p)))
714 (delete-region (nth 1 full-def) (nth 2 full-def)))
715 (incf ndef))
716 ndef)))
718 (defun org-footnote-delete (&optional label)
719 "Delete the footnote at point.
720 This will remove the definition (even multiple definitions if they exist)
721 and all references of a footnote label.
723 If LABEL is non-nil, delete that footnote instead."
724 (catch 'done
725 (let* ((nref 0) (ndef 0) x
726 ;; 1. Determine LABEL of footnote at point.
727 (label (cond
728 ;; LABEL is provided as argument.
729 (label)
730 ;; Footnote reference at point. If the footnote is
731 ;; anonymous, delete it and exit instead.
732 ((setq x (org-footnote-at-reference-p))
733 (or (car x)
734 (progn
735 (delete-region (nth 1 x) (nth 2 x))
736 (message "Anonymous footnote removed")
737 (throw 'done t))))
738 ;; Footnote definition at point.
739 ((setq x (org-footnote-at-definition-p))
740 (car x))
741 (t (error "Don't know which footnote to remove")))))
742 ;; 2. Now that LABEL is non-nil, find every reference and every
743 ;; definition, and delete them.
744 (setq nref (org-footnote-delete-references label)
745 ndef (org-footnote-delete-definitions label))
746 ;; 3. Verify consistency of footnotes and notify user.
747 (org-footnote-auto-adjust-maybe)
748 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
749 ndef nref label))))
751 (defun org-footnote-renumber-fn:N ()
752 "Renumber the simple footnotes like fn:17 into a sequence in the document."
753 (interactive)
754 (let (map i (n 0))
755 (save-excursion
756 (save-restriction
757 (widen)
758 (goto-char (point-min))
759 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
760 (setq i (string-to-number (match-string 1)))
761 (when (and (string-match "\\S-" (buffer-substring
762 (point-at-bol) (match-beginning 0)))
763 (not (assq i map)))
764 (push (cons i (number-to-string (incf n))) map)))
765 (goto-char (point-min))
766 (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
767 (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
769 (defun org-footnote-auto-adjust-maybe ()
770 "Renumber and/or sort footnotes according to user settings."
771 (when (memq org-footnote-auto-adjust '(t renumber))
772 (org-footnote-renumber-fn:N))
773 (when (memq org-footnote-auto-adjust '(t sort))
774 (let ((label (car (org-footnote-at-definition-p))))
775 (org-footnote-normalize 'sort)
776 (when label
777 (goto-char (point-min))
778 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
779 nil t)
780 (progn (insert " ")
781 (just-one-space)))))))
783 (provide 'org-footnote)
785 ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
787 ;;; org-footnote.el ends here