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