org-footnote.el: fix a few compiler warnings.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org-footnote.el
blob7e4cb06936c6c629d734358a84ca03f509e91ac3
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 LaTeX macro. About
180 ;; that case, some special attention should be paid. Indeed,
181 ;; when two footnotes are side by side, once the first one is
182 ;; changed into LaTeX, the second one might then be considered
183 ;; as an optional argument of the command. To prevent that, we
184 ;; have a look at the `org-protected' property of that LaTeX
185 ;; command.
186 (when (and end (< (point) end)
187 (or (not (org-inside-latex-macro-p))
188 (and (get-text-property (1- beg) 'org-protected)
189 (not (get-text-property beg 'org-protected)))))
190 (list label beg end
191 ;; Definition: ensure this is an inline footnote first.
192 (and (or (not label) (match-string 1))
193 (org-trim (buffer-substring (match-end 0) (1- end)))))))))
195 (defun org-footnote-at-definition-p ()
196 "Is the cursor at a footnote definition?
198 This matches only pure definitions like [1] or [fn:name] at the beginning
199 of a line. It does not match references like [fn:name:definition], where the
200 footnote text is included and defined locally.
202 The return value will be nil if not at a footnote definition, and a list with
203 label, start, end and definition of the footnote otherwise."
204 (save-excursion
205 (end-of-line)
206 (let ((lim (save-excursion (re-search-backward "^\\*+ \\|^[ \t]*$" nil t))))
207 (when (re-search-backward org-footnote-definition-re lim t)
208 (end-of-line)
209 (list (match-string 2)
210 (match-beginning 0)
211 (save-match-data
212 (or (and (re-search-forward
213 (org-re "^[ \t]*$\\|^\\*+ \\|^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
214 nil t)
215 (progn (skip-chars-forward " \t\n") (point-at-bol)))
216 (point-max)))
217 (org-trim (buffer-substring (match-end 0) (point))))))))
219 (defun org-footnote-get-next-reference (&optional label backward limit)
220 "Return complete reference of the next footnote.
222 If LABEL is provided, get the next reference of that footnote. If
223 BACKWARD is non-nil, find previous reference instead. LIMIT is
224 the buffer position bounding the search.
226 Return value is a list like those provided by `org-footnote-at-reference-p'.
227 If no footnote is found, return nil."
228 (save-excursion
229 (let* ((label-fmt (if label (format "\\[%s[]:]" label) org-footnote-re)))
230 (catch 'exit
231 (while t
232 (unless (funcall (if backward #'re-search-backward #'re-search-forward)
233 label-fmt limit t)
234 (throw 'exit nil))
235 (unless backward (backward-char))
236 (let ((ref (org-footnote-at-reference-p)))
237 (when ref (throw 'exit ref))))))))
239 (defun org-footnote-next-reference-or-definition (limit)
240 "Move point to next footnote reference or definition.
242 LIMIT is the buffer position bounding the search.
244 Return value is a list like those provided by
245 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
246 If no footnote is found, return nil."
247 (let* (ref)
248 (catch 'exit
249 (while t
250 (unless (re-search-forward org-footnote-re limit t)
251 (throw 'exit nil))
252 ;; Beware: with [1]-like footnotes point will be just after
253 ;; the closing square bracket.
254 (backward-char)
255 (cond
256 ((setq ref (org-footnote-at-reference-p))
257 (throw 'exit ref))
258 ;; Definition: also grab the last square bracket, only
259 ;; matched in `org-footnote-re' for [1]-like footnotes.
260 ((= (point-at-bol) (match-beginning 0))
261 (let ((end (match-end 0)))
262 (throw 'exit
263 (list nil (match-beginning 0)
264 (if (eq (char-before end) 93) end (1+ end)))))))))))
266 (defun org-footnote-get-definition (label)
267 "Return label, boundaries and definition of the footnote LABEL."
268 (let* ((label (regexp-quote (org-footnote-normalize-label label)))
269 (re (format "^\\[%s\\]\\|.\\[%s:" label label))
270 pos)
271 (save-excursion
272 (when (or (re-search-forward re nil t)
273 (and (goto-char (point-min))
274 (re-search-forward re nil t))
275 (and (progn (widen) t)
276 (goto-char (point-min))
277 (re-search-forward re nil t)))
278 (let ((refp (org-footnote-at-reference-p)))
279 (cond
280 ((and (nth 3 refp) refp))
281 ((org-footnote-at-definition-p))))))))
283 (defun org-footnote-goto-definition (label)
284 "Move point to the definition of the footnote LABEL."
285 (interactive "sLabel: ")
286 (org-mark-ring-push)
287 (let ((def (org-footnote-get-definition label)))
288 (if (not def)
289 (error "Cannot find definition of footnote %s" label)
290 (goto-char (nth 1 def))
291 (looking-at (format "\\[%s\\]\\|\\[%s:" label label))
292 (goto-char (match-end 0))
293 (org-show-context 'link-search)
294 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
296 (defun org-footnote-goto-previous-reference (label)
297 "Find the first closest (to point) reference of footnote with label LABEL."
298 (interactive "sLabel: ")
299 (org-mark-ring-push)
300 (let* ((label (org-footnote-normalize-label label)) ref)
301 (save-excursion
302 (setq ref (or (org-footnote-get-next-reference label t)
303 (org-footnote-get-next-reference label)
304 (save-restriction
305 (widen)
307 (org-footnote-get-next-reference label t)
308 (org-footnote-get-next-reference label))))))
309 (if (not ref)
310 (error "Cannot find reference of footnote %s" label)
311 (goto-char (nth 1 ref))
312 (org-show-context 'link-search))))
314 (defun org-footnote-normalize-label (label)
315 "Return LABEL as an appropriate string."
316 (cond
317 ((numberp label) (number-to-string label))
318 ((equal "" label) nil)
319 ((not (string-match "^[0-9]+$\\|^fn:" label))
320 (concat "fn:" label))
321 (t label)))
323 (defun org-footnote-all-labels (&optional with-defs)
324 "Return list with all defined foot labels used in the buffer.
326 If WITH-DEFS is non-nil, also associate the definition to each
327 label. The function will then return an alist whose key is label
328 and value definition."
329 (let* (rtn
330 (push-to-rtn
331 (function
332 ;; Depending on WITH-DEFS, store label or (label . def) of
333 ;; footnote reference/definition given as argument in RTN.
334 (lambda (el)
335 (let ((lbl (car el)))
336 (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
337 (save-excursion
338 (save-restriction
339 (widen)
340 ;; Find all labels found in definitions.
341 (goto-char (point-min))
342 (let (def)
343 (while (re-search-forward org-footnote-definition-re nil t)
344 (when (setq def (org-footnote-at-definition-p))
345 (funcall push-to-rtn def))))
346 ;; Find all labels found in references.
347 (goto-char (point-min))
348 (let (ref)
349 (while (setq ref (org-footnote-get-next-reference))
350 (goto-char (nth 2 ref))
351 (and (car ref) ; ignore anonymous footnotes
352 (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
353 (funcall push-to-rtn ref))))))
354 rtn))
356 (defun org-footnote-unique-label (&optional current)
357 "Return a new unique footnote label.
358 The returns the firsts fn:N labels that is currently not used."
359 (unless current (setq current (org-footnote-all-labels)))
360 (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
361 (cnt 1))
362 (while (member (format fmt cnt) current)
363 (incf cnt))
364 (format fmt cnt)))
366 (defvar org-footnote-label-history nil
367 "History of footnote labels entered in current buffer.")
368 (make-variable-buffer-local 'org-footnote-label-history)
370 (defun org-footnote-new ()
371 "Insert a new footnote.
372 This command prompts for a label. If this is a label referencing an
373 existing label, only insert the label. If the footnote label is empty
374 or new, let the user edit the definition of the footnote."
375 (interactive)
376 (let* ((labels (and (not (equal org-footnote-auto-label 'random))
377 (org-footnote-all-labels)))
378 (propose (org-footnote-unique-label labels))
379 (label
380 (org-footnote-normalize-label
381 (cond
382 ((member org-footnote-auto-label '(t plain))
383 propose)
384 ((equal org-footnote-auto-label 'random)
385 (require 'org-id)
386 (substring (org-id-uuid) 0 8))
388 (completing-read
389 "Label (leave empty for anonymous): "
390 (mapcar 'list labels) nil nil
391 (if (eq org-footnote-auto-label 'confirm) propose nil)
392 'org-footnote-label-history))))))
393 (cond
394 ((not label)
395 (insert "[fn:: ]")
396 (backward-char 1))
397 ((member label labels)
398 (insert "[" label "]")
399 (message "New reference to existing note"))
400 (org-footnote-define-inline
401 (insert "[" label ": ]")
402 (backward-char 1)
403 (org-footnote-auto-adjust-maybe))
405 (insert "[" label "]")
406 (org-footnote-create-definition label)
407 (org-footnote-auto-adjust-maybe)))))
409 (defun org-footnote-create-definition (label)
410 "Start the definition of a footnote with label LABEL."
411 (interactive "sLabel: ")
412 (let ((label (org-footnote-normalize-label label)))
413 (cond
414 ((org-mode-p)
415 ;; No section, put footnote into the current outline node Try to
416 ;; find or make the special node
417 (when org-footnote-section
418 (goto-char (point-min))
419 (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
420 (unless (or (re-search-forward re nil t)
421 (and (progn (widen) t)
422 (re-search-forward re nil t)))
423 (goto-char (point-max))
424 (insert "\n\n* " org-footnote-section "\n"))))
425 ;; Now go to the end of this entry and insert there.
426 (org-footnote-goto-local-insertion-point)
427 (org-show-context 'link-search))
429 (let ((re (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$")))
430 (unless (re-search-forward re nil t)
431 (let ((max (if (and (derived-mode-p 'message-mode)
432 (re-search-forward message-signature-separator nil t))
433 (progn (beginning-of-line) (point))
434 (goto-char (point-max)))))
435 (skip-chars-backward " \t\r\n")
436 (delete-region (point) max)
437 (insert "\n\n")
438 (insert org-footnote-tag-for-non-org-mode-files "\n"))))
439 ;; Skip existing footnotes
440 (while (re-search-forward "^[[:space:]]*\\[[^]]+\\] " nil t)
441 (forward-line))))
442 (insert "\n[" label "] \n")
443 (goto-char (1- (point)))
444 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
446 ;;;###autoload
447 (defun org-footnote-action (&optional special)
448 "Do the right thing for footnotes.
450 When at a footnote reference, jump to the definition.
452 When at a definition, jump to the references if they exist, offer
453 to create them otherwise.
455 When neither at definition or reference, create a new footnote,
456 interactively.
458 With prefix arg SPECIAL, offer additional commands in a menu."
459 (interactive "P")
460 (let (tmp c)
461 (cond
462 (special
463 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
464 (setq c (read-char-exclusive))
465 (cond
466 ((eq c ?s) (org-footnote-normalize 'sort))
467 ((eq c ?r) (org-footnote-renumber-fn:N))
468 ((eq c ?S)
469 (org-footnote-renumber-fn:N)
470 (org-footnote-normalize 'sort))
471 ((eq c ?n) (org-footnote-normalize))
472 ((eq c ?d) (org-footnote-delete))
473 (t (error "No such footnote command %c" c))))
474 ((setq tmp (org-footnote-at-reference-p))
475 (cond
476 ;; Anonymous footnote: move point at the beginning of its
477 ;; definition.
478 ((not (car tmp))
479 (goto-char (nth 1 tmp))
480 (forward-char 5))
481 ;; A definition exists: move to it.
482 ((ignore-errors (org-footnote-goto-definition (car tmp))))
483 ;; No definition exists: offer to create it.
484 ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
485 (org-footnote-create-definition (car tmp)))))
486 ((setq tmp (org-footnote-at-definition-p))
487 (org-footnote-goto-previous-reference (car tmp)))
488 (t (org-footnote-new)))))
490 (defvar org-footnote-insert-pos-for-preprocessor 'point-max
491 "See `org-footnote-normalize'.")
493 (defvar org-export-footnotes-seen nil) ; silence byte-compiler
494 (defvar org-export-footnotes-data nil) ; silence byte-compiler
496 ;;;###autoload
497 (defun org-footnote-normalize (&optional sort-only pre-process-p)
498 "Collect the footnotes in various formats and normalize them.
500 This finds the different sorts of footnotes allowed in Org, and
501 normalizes them to the usual [N] format that is understood by the
502 Org-mode exporters.
504 When SORT-ONLY is set, only sort the footnote definitions into the
505 referenced sequence.
507 When PRE-PROCESS-P is non-nil, the default action, is to insert
508 normalized footnotes towards the end of the pre-processing buffer.
509 Some exporters like docbook, odt, etc. expect that footnote
510 definitions be available before any references to them. Such
511 exporters can let bind `org-footnote-insert-pos-for-preprocessor' to
512 symbol 'point-min to achieve the desired behaviour.
514 Additional note on `org-footnote-insert-pos-for-preprocessor':
515 1. This variable has not effect when FOR-PREPROCESSOR is nil.
516 2. This variable (potentially) obviates the need for extra scan
517 of pre-processor buffer as witnessed in
518 `org-export-docbook-get-footnotes'."
519 ;; This is based on Paul's function, but rewritten.
521 ;; Re-create `org-with-limited-levels', but not limited to Org
522 ;; buffers.
523 (let* ((limit-level
524 (and (boundp 'org-inlinetask-min-level)
525 org-inlinetask-min-level
526 (1- org-inlinetask-min-level)))
527 (nstars (and limit-level
528 (if org-odd-levels-only
529 (and limit-level (1- (* limit-level 2)))
530 limit-level)))
531 (outline-regexp
532 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
533 ;; Determine the highest marker used so far.
534 (ref-table (when pre-process-p org-export-footnotes-seen))
535 (count (if (and pre-process-p ref-table)
536 (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
538 ins-point ref)
539 (save-excursion
540 ;; 1. Find every footnote reference, extract the definition, and
541 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
542 ;; normalize references.
543 (goto-char (point-min))
544 (while (setq ref (org-footnote-get-next-reference))
545 (let* ((lbl (car ref))
546 ;; When footnote isn't anonymous, check if it's label
547 ;; (REF) is already stored in REF-TABLE. In that case,
548 ;; extract number used to identify it (MARKER). If
549 ;; footnote is unknown, increment the global counter
550 ;; (COUNT) to create an unused identifier.
551 (a (and lbl (assoc lbl ref-table)))
552 (marker (or (nth 1 a) (incf count)))
553 ;; Is the reference inline or pointing to an inline
554 ;; footnote?
555 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
556 ;; Replace footnote reference with [MARKER]. Maybe fill
557 ;; paragraph once done. If SORT-ONLY is non-nil, only move
558 ;; to the end of reference found to avoid matching it twice.
559 ;; If PRE-PROCESS-P isn't nil, also add `org-footnote'
560 ;; property to it, so it can be easily recognized by
561 ;; exporters.
562 (if sort-only
563 (goto-char (nth 2 ref))
564 (delete-region (nth 1 ref) (nth 2 ref))
565 (goto-char (nth 1 ref))
566 (let ((new-ref (format "[%d]" marker)))
567 (when pre-process-p (org-add-props new-ref '(org-footnote t)))
568 (insert new-ref))
569 (and inlinep
570 org-footnote-fill-after-inline-note-extraction
571 (org-fill-paragraph)))
572 ;; Add label (REF), identifier (MARKER) and definition (DEF)
573 ;; to REF-TABLE if data was unknown.
574 (unless a
575 (let ((def (or (nth 3 ref) ; inline
576 (and pre-process-p
577 (cdr (assoc lbl org-export-footnotes-data)))
578 (nth 3 (org-footnote-get-definition lbl)))))
579 (push (list lbl marker def inlinep) ref-table)))
580 ;; Remove definition of non-inlined footnotes.
581 (unless inlinep (org-footnote-delete-definitions lbl))))
582 ;; 2. Find and remove the footnote section, if any. If we are
583 ;; exporting, insert it again at end of buffer. In a non
584 ;; org-mode file, insert instead
585 ;; `org-footnote-tag-for-non-org-mode-files'.
586 (goto-char (point-min))
587 (cond
588 ((org-mode-p)
589 (if (and org-footnote-section
590 (re-search-forward
591 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
592 "[ \t]*$")
593 nil t))
594 (if pre-process-p
595 (replace-match "")
596 (org-back-to-heading t)
597 (forward-line 1)
598 (setq ins-point (point))
599 (delete-region (point) (org-end-of-subtree t)))
600 (goto-char (point-max))
601 (unless pre-process-p
602 (when org-footnote-section
603 (or (bolp) (insert "\n"))
604 (insert "* " org-footnote-section "\n")
605 (setq ins-point (point))))))
607 (if (re-search-forward
608 (concat "^"
609 (regexp-quote org-footnote-tag-for-non-org-mode-files)
610 "[ \t]*$")
611 nil t)
612 (replace-match ""))
613 (goto-char (point-max))
614 (skip-chars-backward " \t\n\r")
615 (delete-region (point) (point-max))
616 (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n")
617 (setq ins-point (point))))
618 ;; 3. Clean-up REF-TABLE.
619 (setq ref-table
620 (delq nil
621 (mapcar
622 (lambda (x)
623 (cond
624 ;; When only sorting, ignore inline footnotes.
625 ((and sort-only (nth 3 x)) nil)
626 ;; No definition available: provide one.
627 ((not (nth 2 x))
628 (append (butlast x 2)
629 (list (format "DEFINITION NOT FOUND: %s" (car x))
630 (nth 3 x))))
631 (t x)))
632 ref-table)))
633 (setq ref-table (nreverse ref-table))
634 ;; 4. Insert the footnotes again in the buffer, at the
635 ;; appropriate spot.
636 (goto-char (or
637 (and pre-process-p
638 (eq org-footnote-insert-pos-for-preprocessor 'point-min)
639 (point-min))
640 ins-point
641 (point-max)))
642 (cond
643 ((not ref-table)) ; no footnote: exit
644 ;; Cases when footnotes should be inserted together in one place.
645 ((or (not (org-mode-p))
646 org-footnote-section
647 (not sort-only))
648 (insert "\n"
649 (mapconcat (lambda (x) (format "[%s] %s"
650 (nth (if sort-only 0 1) x) (nth 2 x)))
651 ref-table "\n\n")
652 "\n\n")
653 ;; When exporting, add newly insert markers along with their
654 ;; associated definition to `org-export-footnotes-seen'.
655 (when pre-process-p
656 (setq org-export-footnotes-seen ref-table)))
657 ;; Else, insert each definition at the end of the section
658 ;; containing their first reference. Happens only in Org
659 ;; files with no special footnote section, and only when
660 ;; doing sorting.
661 (t (mapc 'org-insert-footnote-reference-near-definition
662 ref-table))))))
664 (defun org-insert-footnote-reference-near-definition (entry)
665 "Find first reference of footnote ENTRY and insert the definition there.
666 ENTRY is (fn-label num-mark definition)."
667 (when (car entry)
668 (goto-char (point-min))
669 (let ((ref (org-footnote-get-next-reference (car entry))))
670 (when ref
671 (goto-char (nth 2 ref))
672 (org-footnote-goto-local-insertion-point)
673 (insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
675 (defun org-footnote-goto-local-insertion-point ()
676 "Find insertion point for footnote, just before next outline heading."
677 (org-with-limited-levels (outline-next-heading))
678 (or (bolp) (newline))
679 (beginning-of-line 0)
680 (while (and (not (bobp)) (= (char-after) ?#))
681 (beginning-of-line 0))
682 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
683 (end-of-line 1)
684 (skip-chars-backward "\n\r\t ")
685 (forward-line))
687 (defun org-footnote-delete-references (label)
688 "Delete every reference to footnote LABEL.
689 Return the number of footnotes removed."
690 (save-excursion
691 (goto-char (point-min))
692 (let (ref (nref 0))
693 (while (setq ref (org-footnote-get-next-reference label))
694 (goto-char (nth 1 ref))
695 (delete-region (nth 1 ref) (nth 2 ref))
696 (incf nref))
697 nref)))
699 (defun org-footnote-delete-definitions (label)
700 "Delete every definition of the footnote LABEL.
701 Return the number of footnotes removed."
702 (save-excursion
703 (goto-char (point-min))
704 (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
705 (ndef 0))
706 (while (re-search-forward def-re nil t)
707 (let ((full-def (org-footnote-at-definition-p)))
708 (delete-region (nth 1 full-def) (nth 2 full-def)))
709 (incf ndef))
710 ndef)))
712 (defun org-footnote-delete (&optional label)
713 "Delete the footnote at point.
714 This will remove the definition (even multiple definitions if they exist)
715 and all references of a footnote label.
717 If LABEL is non-nil, delete that footnote instead."
718 (catch 'done
719 (let* ((nref 0) (ndef 0) x
720 ;; 1. Determine LABEL of footnote at point.
721 (label (cond
722 ;; LABEL is provided as argument.
723 (label)
724 ;; Footnote reference at point. If the footnote is
725 ;; anonymous, delete it and exit instead.
726 ((setq x (org-footnote-at-reference-p))
727 (or (car x)
728 (progn
729 (delete-region (nth 1 x) (nth 2 x))
730 (message "Anonymous footnote removed")
731 (throw 'done t))))
732 ;; Footnote definition at point.
733 ((setq x (org-footnote-at-definition-p))
734 (car x))
735 (t (error "Don't know which footnote to remove")))))
736 ;; 2. Now that LABEL is non-nil, find every reference and every
737 ;; definition, and delete them.
738 (setq nref (org-footnote-delete-references label)
739 ndef (org-footnote-delete-definitions label))
740 ;; 3. Verify consistency of footnotes and notify user.
741 (org-footnote-auto-adjust-maybe)
742 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
743 ndef nref label))))
745 (defun org-footnote-renumber-fn:N ()
746 "Renumber the simple footnotes like fn:17 into a sequence in the document."
747 (interactive)
748 (let (map i (n 0))
749 (save-excursion
750 (save-restriction
751 (widen)
752 (goto-char (point-min))
753 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
754 (setq i (string-to-number (match-string 1)))
755 (when (and (string-match "\\S-" (buffer-substring
756 (point-at-bol) (match-beginning 0)))
757 (not (assq i map)))
758 (push (cons i (number-to-string (incf n))) map)))
759 (goto-char (point-min))
760 (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
761 (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
763 (defun org-footnote-auto-adjust-maybe ()
764 "Renumber and/or sort footnotes according to user settings."
765 (when (memq org-footnote-auto-adjust '(t renumber))
766 (org-footnote-renumber-fn:N))
767 (when (memq org-footnote-auto-adjust '(t sort))
768 (let ((label (car (org-footnote-at-definition-p))))
769 (org-footnote-normalize 'sort)
770 (when label
771 (goto-char (point-min))
772 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
773 nil t)
774 (progn (insert " ")
775 (just-one-space)))))))
777 (provide 'org-footnote)
779 ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
781 ;;; org-footnote.el ends here