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