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