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