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