3bd5559928fa0a7d8509fbc183098be6a5a4693f
[org-mode/org-jambu.git] / lisp / org-footnote.el
blob3bd5559928fa0a7d8509fbc183098be6a5a4693f
1 ;;; org-footnote.el --- Footnote support in Org and elsewhere
2 ;;
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.5
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; This file contains the code dealing with footnotes in Org-mode.
29 ;; The code can also be used in arbitrary text modes to provide
30 ;; footnotes. Compared to Steven L Baur's footnote.el it provides
31 ;; better support for resuming editing. It is less configurable than
32 ;; Steve's code, though.
34 ;;; Code:
36 (eval-when-compile
37 (require 'cl))
38 (require 'org-macs)
39 (require 'org-compat)
41 (declare-function org-in-commented-line "org" ())
42 (declare-function org-in-regexp "org" (re &optional nlines visually))
43 (declare-function org-mark-ring-push "org" (&optional pos buffer))
44 (declare-function outline-next-heading "outline")
45 (declare-function org-trim "org" (s))
46 (declare-function org-show-context "org" (&optional key))
47 (declare-function org-back-to-heading "org" (&optional invisible-ok))
48 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
49 (declare-function org-in-verbatim-emphasis "org" ())
50 (declare-function org-inside-latex-macro-p "org" ())
51 (declare-function org-id-uuid "org" ())
52 (defvar org-odd-levels-only) ;; defined in org.el
53 (defvar message-signature-separator) ;; defined in message.el
55 (defconst org-footnote-re
56 ;; Only [1]-like footnotes are closed in this regexp, as footnotes
57 ;; from other types might contain square brackets (i.e. links) in
58 ;; their definition.
60 ;; `org-re' is used for regexp compatibility with XEmacs.
61 (org-re (concat "\\[\\(?:"
62 ;; Match inline footnotes.
63 "fn:\\([-_[:word:]]+\\)?:\\|"
64 ;; Match other footnotes.
65 "\\(?:\\([0-9]+\\)\\]\\)\\|"
66 "\\(fn:[-_[:word:]]+\\)"
67 "\\)"))
68 "Regular expression for matching footnotes.")
70 (defconst org-footnote-definition-re
71 (org-re "^\\(\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]\\)")
72 "Regular expression matching the definition of a footnote.")
74 (defgroup org-footnote nil
75 "Footnotes in Org-mode."
76 :tag "Org Footnote"
77 :group 'org)
79 (defcustom org-footnote-section "Footnotes"
80 "Outline heading containing footnote definitions before export.
81 This can be nil, to place footnotes locally at the end of the current
82 outline node. If can also be the name of a special outline heading
83 under which footnotes should be put.
84 This variable defines the place where Org puts the definition
85 automatically, i.e. when creating the footnote, and when sorting the notes.
86 However, by hand you may place definitions *anywhere*.
87 If this is a string, during export, all subtrees starting with this
88 heading will be removed after extracting footnote definitions."
89 :group 'org-footnote
90 :type '(choice
91 (string :tag "Collect footnotes under heading")
92 (const :tag "Define footnotes locally" nil)))
94 (defcustom org-footnote-tag-for-non-org-mode-files "Footnotes:"
95 "Tag marking the beginning of footnote section.
96 The Org-mode footnote engine can be used in arbitrary text files as well
97 as in Org-mode. Outside Org-mode, new footnotes are always placed at
98 the end of the file. When you normalize the notes, any line containing
99 only this tag will be removed, a new one will be inserted at the end
100 of the file, followed by the collected and normalized footnotes."
101 :group 'org-footnote
102 :type 'string)
104 (defcustom org-footnote-define-inline nil
105 "Non-nil means define footnotes inline, at reference location.
106 When nil, footnotes will be defined in a special section near
107 the end of the document. When t, the [fn:label:definition] notation
108 will be used to define the footnote at the reference position."
109 :group 'org-footnote
110 :type 'boolean)
112 (defcustom org-footnote-auto-label t
113 "Non-nil means define automatically new labels for footnotes.
114 Possible values are:
116 nil prompt the user for each label
117 t create unique labels of the form [fn:1], [fn:2], ...
118 confirm like t, but let the user edit the created value. In particular,
119 the label can be removed from the minibuffer, to create
120 an anonymous footnote.
121 random Automatically generate a unique, random label.
122 plain Automatically create plain number labels like [1]"
123 :group 'org-footnote
124 :type '(choice
125 (const :tag "Prompt for label" nil)
126 (const :tag "Create automatic [fn:N]" t)
127 (const :tag "Offer automatic [fn:N] for editing" confirm)
128 (const :tag "Create a random label" random)
129 (const :tag "Create automatic [N]" plain)))
131 (defcustom org-footnote-auto-adjust nil
132 "Non-nil means automatically adjust footnotes after insert/delete.
133 When this is t, after each insertion or deletion of a footnote,
134 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
135 If you want to have just sorting or just renumbering, set this variable
136 to `sort' or `renumber'.
138 The main values of this variable can be set with in-buffer options:
140 #+STARTUP: fnadjust
141 #+STARTUP: nofnadjust"
142 :group 'org-footnote
143 :type '(choice
144 (const :tag "Renumber" renumber)
145 (const :tag "Sort" sort)
146 (const :tag "Renumber and Sort" t)))
148 (defcustom org-footnote-fill-after-inline-note-extraction nil
149 "Non-nil means fill paragraphs after extracting footnotes.
150 When extracting inline footnotes, the lengths of lines can change a lot.
151 When this option is set, paragraphs from which an inline footnote has been
152 extracted will be filled again."
153 :group 'org-footnote
154 :type 'boolean)
156 (defun org-footnote-at-reference-p ()
157 "Is the cursor at a footnote reference?
159 If so, return an list containing its label, beginning and ending
160 positions, and the definition, if local."
161 (when (and (not (or (org-in-commented-line)
162 (org-in-verbatim-emphasis)))
163 (or (org-in-regexp org-footnote-re)
164 (save-excursion (re-search-backward org-footnote-re nil t)))
165 ;; A footnote reference cannot start at bol.
166 (/= (match-beginning 0) (point-at-bol)))
167 (let* ((beg (match-beginning 0))
168 (label (or (match-string 2) (match-string 3)
169 ;; Anonymous footnotes don't have labels
170 (and (match-string 1) (concat "fn:" (match-string 1)))))
171 ;; Inline footnotes don't end at (match-end 0) as
172 ;; `org-footnote-re' stops just after the second colon.
173 ;; Find the real ending with `scan-sexps', so Org doesn't
174 ;; get fooled by unrelated closing square brackets.
175 (end (ignore-errors (scan-sexps beg 1))))
176 ;; Point is really at a reference if it's located before true
177 ;; ending of the footnote and isn't within a LaTeX macro. About
178 ;; that case, some special attention should be paid. Indeed,
179 ;; when two footnotes are side by side, once the first one is
180 ;; changed into LaTeX, the second one might then be considered
181 ;; as an optional argument of the command. To prevent that, we
182 ;; have a look at the `org-protected' property of that LaTeX
183 ;; command.
184 (when (and end (< (point) end)
185 (or (not (org-inside-latex-macro-p))
186 (and (get-text-property (1- beg) 'org-protected)
187 (not (get-text-property beg 'org-protected)))))
188 (list label beg end
189 ;; Definition: ensure this is an inline footnote first.
190 (and (or (not label) (match-string 1))
191 (org-trim (buffer-substring (match-end 0) (1- end)))))))))
193 (defun org-footnote-at-definition-p ()
194 "Is the cursor at a footnote definition?
196 This matches only pure definitions like [1] or [fn:name] at the beginning
197 of a line. It does not match references like [fn:name:definition], where the
198 footnote text is included and defined locally.
200 The return value will be nil if not at a footnote definition, and a list with
201 label, start, end and definition of the footnote otherwise."
202 (save-excursion
203 (end-of-line)
204 (let ((lim (save-excursion (re-search-backward "^\\*+ \\|^[ \t]*$" nil t))))
205 (when (re-search-backward org-footnote-definition-re lim t)
206 (end-of-line)
207 (list (match-string 2)
208 (match-beginning 0)
209 (save-match-data
210 (or (and (re-search-forward
211 (org-re "^[ \t]*$\\|^\\*+ \\|^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
212 nil t)
213 (progn (skip-chars-forward " \t\n") (point-at-bol)))
214 (point-max)))
215 (org-trim (buffer-substring (match-end 0) (point))))))))
217 (defun org-footnote-get-next-reference (&optional label backward limit)
218 "Return complete reference of the next footnote.
220 If LABEL is provided, get the next reference of that footnote. If
221 BACKWARD is non-nil, find previous reference instead. LIMIT is
222 the buffer position bounding the search.
224 Return value is a list like those provided by `org-footnote-at-reference-p'.
225 If no footnote is found, return nil."
226 (save-excursion
227 (let* ((label-fmt (if label (format "\\[%s[]:]" label) org-footnote-re)))
228 (catch 'exit
229 (while t
230 (unless (funcall (if backward #'re-search-backward #'re-search-forward)
231 label-fmt limit t)
232 (throw 'exit nil))
233 (unless backward (backward-char))
234 (let ((ref (org-footnote-at-reference-p)))
235 (when ref (throw 'exit ref))))))))
237 (defun org-footnote-next-reference-or-definition (limit)
238 "Move point to next footnote reference or definition.
240 LIMIT is the buffer position bounding the search.
242 Return value is a list like those provided by
243 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
244 If no footnote is found, return nil."
245 (let* (ref)
246 (catch 'exit
247 (while t
248 (unless (re-search-forward org-footnote-re limit t)
249 (throw 'exit nil))
250 ;; Beware: with [1]-like footnotes point will be just after
251 ;; the closing square bracket.
252 (backward-char)
253 (cond
254 ((setq ref (org-footnote-at-reference-p))
255 (throw 'exit ref))
256 ;; Definition: also grab the last square bracket, only
257 ;; matched in `org-footnote-re' for [1]-like footnotes.
258 ((= (point-at-bol) (match-beginning 0))
259 (let ((end (match-end 0)))
260 (throw 'exit
261 (list nil (match-beginning 0)
262 (if (eq (char-before end) 93) end (1+ end)))))))))))
264 (defun org-footnote-get-definition (label)
265 "Return label, boundaries and definition of the footnote LABEL."
266 (let* ((label (regexp-quote (org-footnote-normalize-label label)))
267 (re (format "^\\[%s\\]\\|.\\[%s:" label label))
268 pos)
269 (save-excursion
270 (when (or (re-search-forward re nil t)
271 (and (goto-char (point-min))
272 (re-search-forward re nil t))
273 (and (progn (widen) t)
274 (goto-char (point-min))
275 (re-search-forward re nil t)))
276 (let ((refp (org-footnote-at-reference-p)))
277 (cond
278 ((and (nth 3 refp) refp))
279 ((org-footnote-at-definition-p))))))))
281 (defun org-footnote-goto-definition (label)
282 "Move point to the definition of the footnote LABEL."
283 (interactive "sLabel: ")
284 (org-mark-ring-push)
285 (let ((def (org-footnote-get-definition label)))
286 (if (not def)
287 (error "Cannot find definition of footnote %s" label)
288 (goto-char (nth 1 def))
289 (looking-at (format "\\[%s\\]\\|\\[%s:" label label))
290 (goto-char (match-end 0))
291 (org-show-context 'link-search)
292 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
294 (defun org-footnote-goto-previous-reference (label)
295 "Find the first closest (to point) reference of footnote with label LABEL."
296 (interactive "sLabel: ")
297 (org-mark-ring-push)
298 (let* ((label (org-footnote-normalize-label label)) ref)
299 (save-excursion
300 (setq ref (or (org-footnote-get-next-reference label t)
301 (org-footnote-get-next-reference label)
302 (save-restriction
303 (widen)
305 (org-footnote-get-next-reference label t)
306 (org-footnote-get-next-reference label))))))
307 (if (not ref)
308 (error "Cannot find reference of footnote %s" label)
309 (goto-char (nth 1 ref))
310 (org-show-context 'link-search))))
312 (defun org-footnote-normalize-label (label)
313 "Return LABEL as an appropriate string."
314 (cond
315 ((numberp label) (number-to-string label))
316 ((equal "" label) nil)
317 ((not (string-match "^[0-9]+$\\|^fn:" label))
318 (concat "fn:" label))
319 (t label)))
321 (defun org-footnote-all-labels (&optional with-defs)
322 "Return list with all defined foot labels used in the buffer.
324 If WITH-DEFS is non-nil, also associate the definition to each
325 label. The function will then return an alist whose key is label
326 and value definition."
327 (let (rtn
328 (push-to-rtn
329 (function
330 ;; Depending on WITH-DEFS, store label or (label . def) of
331 ;; footnote reference/definition given as argument in RTN.
332 (lambda (el)
333 (let ((lbl (car el)))
334 (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
335 (save-excursion
336 (save-restriction
337 (widen)
338 ;; Find all labels found in definitions.
339 (goto-char (point-min))
340 (let (def)
341 (while (re-search-forward org-footnote-definition-re nil t)
342 (when (setq def (org-footnote-at-definition-p))
343 (funcall push-to-rtn def))))
344 ;; Find all labels found in references.
345 (goto-char (point-min))
346 (let (ref)
347 (while (setq ref (org-footnote-get-next-reference))
348 (goto-char (nth 2 ref))
349 (and (car ref) ; ignore anonymous footnotes
350 (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
351 (funcall push-to-rtn ref))))))
352 rtn))
354 (defun org-footnote-unique-label (&optional current)
355 "Return a new unique footnote label.
356 The returns the firsts fn:N labels that is currently not used."
357 (unless current (setq current (org-footnote-all-labels)))
358 (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
359 (cnt 1))
360 (while (member (format fmt cnt) current)
361 (incf cnt))
362 (format fmt cnt)))
364 (defvar org-footnote-label-history nil
365 "History of footnote labels entered in current buffer.")
366 (make-variable-buffer-local 'org-footnote-label-history)
368 (defun org-footnote-new ()
369 "Insert a new footnote.
370 This command prompts for a label. If this is a label referencing an
371 existing label, only insert the label. If the footnote label is empty
372 or new, let the user edit the definition of the footnote."
373 (interactive)
374 (let* ((labels (and (not (equal org-footnote-auto-label 'random))
375 (org-footnote-all-labels)))
376 (propose (org-footnote-unique-label labels))
377 (label
378 (org-footnote-normalize-label
379 (cond
380 ((member org-footnote-auto-label '(t plain))
381 propose)
382 ((equal org-footnote-auto-label 'random)
383 (require 'org-id)
384 (substring (org-id-uuid) 0 8))
386 (completing-read
387 "Label (leave empty for anonymous): "
388 (mapcar 'list labels) nil nil
389 (if (eq org-footnote-auto-label 'confirm) propose nil)
390 'org-footnote-label-history))))))
391 (cond
392 ((not label)
393 (insert "[fn:: ]")
394 (backward-char 1))
395 ((member label labels)
396 (insert "[" label "]")
397 (message "New reference to existing note"))
398 (org-footnote-define-inline
399 (insert "[" label ": ]")
400 (backward-char 1)
401 (org-footnote-auto-adjust-maybe))
403 (insert "[" label "]")
404 (org-footnote-create-definition label)
405 (org-footnote-auto-adjust-maybe)))))
407 (defun org-footnote-create-definition (label)
408 "Start the definition of a footnote with label LABEL."
409 (interactive "sLabel: ")
410 (let ((label (org-footnote-normalize-label label)))
411 (cond
412 ((org-mode-p)
413 ;; No section, put footnote into the current outline node Try to
414 ;; find or make the special node
415 (when org-footnote-section
416 (goto-char (point-min))
417 (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
418 (unless (or (re-search-forward re nil t)
419 (and (progn (widen) t)
420 (re-search-forward re nil t)))
421 (goto-char (point-max))
422 (insert "\n\n* " org-footnote-section "\n"))))
423 ;; Now go to the end of this entry and insert there.
424 (org-footnote-goto-local-insertion-point)
425 (org-show-context 'link-search))
427 (let ((re (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$")))
428 (unless (re-search-forward re nil t)
429 (let ((max (if (and (derived-mode-p 'message-mode)
430 (re-search-forward message-signature-separator nil t))
431 (progn (beginning-of-line) (point))
432 (goto-char (point-max)))))
433 (skip-chars-backward " \t\r\n")
434 (delete-region (point) max)
435 (insert "\n\n")
436 (insert org-footnote-tag-for-non-org-mode-files "\n"))))
437 ;; Skip existing footnotes
438 (while (re-search-forward "^[[:space:]]*\\[[^]]+\\] " nil t)
439 (forward-line))))
440 (insert "\n[" label "] \n")
441 (goto-char (1- (point)))
442 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
444 ;;;###autoload
445 (defun org-footnote-action (&optional special)
446 "Do the right thing for footnotes.
448 When at a footnote reference, jump to the definition.
450 When at a definition, jump to the references if they exist, offer
451 to create them otherwise.
453 When neither at definition or reference, create a new footnote,
454 interactively.
456 With prefix arg SPECIAL, offer additional commands in a menu."
457 (interactive "P")
458 (let (tmp c)
459 (cond
460 (special
461 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
462 (setq c (read-char-exclusive))
463 (cond
464 ((eq c ?s) (org-footnote-normalize 'sort))
465 ((eq c ?r) (org-footnote-renumber-fn:N))
466 ((eq c ?S)
467 (org-footnote-renumber-fn:N)
468 (org-footnote-normalize 'sort))
469 ((eq c ?n) (org-footnote-normalize))
470 ((eq c ?d) (org-footnote-delete))
471 (t (error "No such footnote command %c" c))))
472 ((setq tmp (org-footnote-at-reference-p))
473 (cond
474 ;; Anonymous footnote: move point at the beginning of its
475 ;; definition.
476 ((not (car tmp))
477 (goto-char (nth 1 tmp))
478 (forward-char 5))
479 ;; A definition exists: move to it.
480 ((ignore-errors (org-footnote-goto-definition (car tmp))))
481 ;; No definition exists: offer to create it.
482 ((yes-or-no-p (format "No definition for %s. Create one? " (car tmp)))
483 (org-footnote-create-definition (car tmp)))))
484 ((setq tmp (org-footnote-at-definition-p))
485 (org-footnote-goto-previous-reference (car tmp)))
486 (t (org-footnote-new)))))
488 (defvar org-footnote-insert-pos-for-preprocessor 'point-max
489 "See `org-footnote-normalize'.")
491 ;;;###autoload
492 (defun org-footnote-normalize (&optional sort-only pre-process-p)
493 "Collect the footnotes in various formats and normalize them.
495 This finds the different sorts of footnotes allowed in Org, and
496 normalizes them to the usual [N] format that is understood by the
497 Org-mode exporters.
499 When SORT-ONLY is set, only sort the footnote definitions into the
500 referenced sequence.
502 When PRE-PROCESS-P is non-nil, the default action, is to insert
503 normalized footnotes towards the end of the pre-processing buffer.
504 Some exporters like docbook, odt, etc. expect that footnote
505 definitions be available before any references to them. Such
506 exporters can let bind `org-footnote-insert-pos-for-preprocessor' to
507 symbol 'point-min to achieve the desired behaviour.
509 Additional note on `org-footnote-insert-pos-for-preprocessor':
510 1. This variable has not effect when FOR-PREPROCESSOR is nil.
511 2. This variable (potentially) obviates the need for extra scan
512 of pre-processor buffer as witnessed in
513 `org-export-docbook-get-footnotes'."
514 ;; This is based on Paul's function, but rewritten.
516 ;; Re-create `org-with-limited-levels', but not limited to Org
517 ;; buffers.
518 (let* ((limit-level
519 (and (boundp 'org-inlinetask-min-level)
520 org-inlinetask-min-level
521 (1- org-inlinetask-min-level)))
522 (nstars (and limit-level
523 (if org-odd-levels-only
524 (and limit-level (1- (* limit-level 2)))
525 limit-level)))
526 (outline-regexp
527 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
528 ;; Determine the highest marker used so far.
529 (ref-table (when pre-process-p org-export-footnotes-seen))
530 (count (if (and pre-process-p ref-table)
531 (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
533 ins-point ref)
534 (save-excursion
535 ;; 1. Find every footnote reference, extract the definition, and
536 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
537 ;; normalize references.
538 (goto-char (point-min))
539 (while (setq ref (org-footnote-get-next-reference))
540 (let* ((lbl (car ref))
541 ;; When footnote isn't anonymous, check if it's label
542 ;; (REF) is already stored in REF-TABLE. In that case,
543 ;; extract number used to identify it (MARKER). If
544 ;; footnote is unknown, increment the global counter
545 ;; (COUNT) to create an unused identifier.
546 (a (and lbl (assoc lbl ref-table)))
547 (marker (or (nth 1 a) (incf count)))
548 ;; Is the reference inline or pointing to an inline
549 ;; footnote?
550 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
551 ;; Replace footnote reference with [MARKER]. Maybe fill
552 ;; paragraph once done. If SORT-ONLY is non-nil, only move
553 ;; to the end of reference found to avoid matching it twice.
554 ;; If PRE-PROCESS-P isn't nil, also add `org-footnote'
555 ;; property to it, so it can be easily recognized by
556 ;; exporters.
557 (if sort-only
558 (goto-char (nth 2 ref))
559 (delete-region (nth 1 ref) (nth 2 ref))
560 (goto-char (nth 1 ref))
561 (let ((new-ref (format "[%d]" marker)))
562 (when pre-process-p (org-add-props new-ref '(org-footnote t)))
563 (insert new-ref))
564 (and inlinep
565 org-footnote-fill-after-inline-note-extraction
566 (org-fill-paragraph)))
567 ;; Add label (REF), identifier (MARKER) and definition (DEF)
568 ;; to REF-TABLE if data was unknown.
569 (unless a
570 (let ((def (or (nth 3 ref) ; inline
571 (and pre-process-p
572 (cdr (assoc lbl org-export-footnotes-data)))
573 (nth 3 (org-footnote-get-definition lbl)))))
574 (push (list lbl marker def inlinep) ref-table)))
575 ;; Remove definition of non-inlined footnotes.
576 (unless inlinep (org-footnote-delete-definitions lbl))))
577 ;; 2. Find and remove the footnote section, if any. If we are
578 ;; exporting, insert it again at end of buffer. In a non
579 ;; org-mode file, insert instead
580 ;; `org-footnote-tag-for-non-org-mode-files'.
581 (goto-char (point-min))
582 (cond
583 ((org-mode-p)
584 (if (and org-footnote-section
585 (re-search-forward
586 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
587 "[ \t]*$")
588 nil t))
589 (if pre-process-p
590 (replace-match "")
591 (org-back-to-heading t)
592 (forward-line 1)
593 (setq ins-point (point))
594 (delete-region (point) (org-end-of-subtree t)))
595 (goto-char (point-max))
596 (unless pre-process-p
597 (when org-footnote-section
598 (or (bolp) (insert "\n"))
599 (insert "* " org-footnote-section "\n")
600 (setq ins-point (point))))))
602 (if (re-search-forward
603 (concat "^"
604 (regexp-quote org-footnote-tag-for-non-org-mode-files)
605 "[ \t]*$")
606 nil t)
607 (replace-match ""))
608 (goto-char (point-max))
609 (skip-chars-backward " \t\n\r")
610 (delete-region (point) (point-max))
611 (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n")
612 (setq ins-point (point))))
613 ;; 3. Clean-up REF-TABLE.
614 (setq ref-table
615 (delq nil
616 (mapcar
617 (lambda (x)
618 (cond
619 ;; When only sorting, ignore inline footnotes.
620 ((and sort-only (nth 3 x)) nil)
621 ;; No definition available: provide one.
622 ((not (nth 2 x))
623 (append (butlast x 2)
624 (list (format "DEFINITION NOT FOUND: %s" (car x))
625 (nth 3 x))))
626 (t x)))
627 ref-table)))
628 (setq ref-table (nreverse ref-table))
629 ;; 4. Insert the footnotes again in the buffer, at the
630 ;; appropriate spot.
631 (goto-char (or
632 (and pre-process-p
633 (eq org-footnote-insert-pos-for-preprocessor 'point-min)
634 (point-min))
635 ins-point
636 (point-max)))
637 (cond
638 ((not ref-table)) ; no footnote: exit
639 ;; Cases when footnotes should be inserted together in one place.
640 ((or (not (org-mode-p))
641 org-footnote-section
642 (not sort-only))
643 (insert "\n"
644 (mapconcat (lambda (x) (format "[%s] %s"
645 (nth (if sort-only 0 1) x) (nth 2 x)))
646 ref-table "\n\n")
647 "\n\n")
648 ;; When exporting, add newly insert markers along with their
649 ;; associated definition to `org-export-footnotes-seen'.
650 (when pre-process-p
651 (setq org-export-footnotes-seen ref-table)))
652 ;; Else, insert each definition at the end of the section
653 ;; containing their first reference. Happens only in Org
654 ;; files with no special footnote section, and only when
655 ;; doing sorting.
656 (t (mapc 'org-insert-footnote-reference-near-definition
657 ref-table))))))
659 (defun org-insert-footnote-reference-near-definition (entry)
660 "Find first reference of footnote ENTRY and insert the definition there.
661 ENTRY is (fn-label num-mark definition)."
662 (when (car entry)
663 (goto-char (point-min))
664 (let ((ref (org-footnote-get-next-reference (car entry))))
665 (when ref
666 (goto-char (nth 2 ref))
667 (org-footnote-goto-local-insertion-point)
668 (insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
670 (defun org-footnote-goto-local-insertion-point ()
671 "Find insertion point for footnote, just before next outline heading."
672 (org-with-limited-levels (outline-next-heading))
673 (or (bolp) (newline))
674 (beginning-of-line 0)
675 (while (and (not (bobp)) (= (char-after) ?#))
676 (beginning-of-line 0))
677 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
678 (end-of-line 1)
679 (skip-chars-backward "\n\r\t ")
680 (forward-line))
682 (defun org-footnote-delete-references (label)
683 "Delete every reference to footnote LABEL.
684 Return the number of footnotes removed."
685 (save-excursion
686 (goto-char (point-min))
687 (let (ref (nref 0))
688 (while (setq ref (org-footnote-get-next-reference label))
689 (goto-char (nth 1 ref))
690 (delete-region (nth 1 ref) (nth 2 ref))
691 (incf nref))
692 nref)))
694 (defun org-footnote-delete-definitions (label)
695 "Delete every definition of the footnote LABEL.
696 Return the number of footnotes removed."
697 (save-excursion
698 (goto-char (point-min))
699 (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
700 (ndef 0))
701 (while (re-search-forward def-re nil t)
702 (let ((full-def (org-footnote-at-definition-p)))
703 (delete-region (nth 1 full-def) (nth 2 full-def)))
704 (incf ndef))
705 ndef)))
707 (defun org-footnote-delete (&optional label)
708 "Delete the footnote at point.
709 This will remove the definition (even multiple definitions if they exist)
710 and all references of a footnote label.
712 If LABEL is non-nil, delete that footnote instead."
713 (catch 'done
714 (let* ((nref 0) (ndef 0) x
715 ;; 1. Determine LABEL of footnote at point.
716 (label (cond
717 ;; LABEL is provided as argument.
718 (label)
719 ;; Footnote reference at point. If the footnote is
720 ;; anonymous, delete it and exit instead.
721 ((setq x (org-footnote-at-reference-p))
722 (or (car x)
723 (progn
724 (delete-region (nth 1 x) (nth 2 x))
725 (message "Anonymous footnote removed")
726 (throw 'done t))))
727 ;; Footnote definition at point.
728 ((setq x (org-footnote-at-definition-p))
729 (car x))
730 (t (error "Don't know which footnote to remove")))))
731 ;; 2. Now that LABEL is non-nil, find every reference and every
732 ;; definition, and delete them.
733 (setq nref (org-footnote-delete-references label)
734 ndef (org-footnote-delete-definitions label))
735 ;; 3. Verify consistency of footnotes and notify user.
736 (org-footnote-auto-adjust-maybe)
737 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
738 ndef nref label))))
740 (defun org-footnote-renumber-fn:N ()
741 "Renumber the simple footnotes like fn:17 into a sequence in the document."
742 (interactive)
743 (let (map i (n 0))
744 (save-excursion
745 (save-restriction
746 (widen)
747 (goto-char (point-min))
748 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
749 (setq i (string-to-number (match-string 1)))
750 (when (and (string-match "\\S-" (buffer-substring
751 (point-at-bol) (match-beginning 0)))
752 (not (assq i map)))
753 (push (cons i (number-to-string (incf n))) map)))
754 (goto-char (point-min))
755 (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
756 (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
758 (defun org-footnote-auto-adjust-maybe ()
759 "Renumber and/or sort footnotes according to user settings."
760 (when (memq org-footnote-auto-adjust '(t renumber))
761 (org-footnote-renumber-fn:N))
762 (when (memq org-footnote-auto-adjust '(t sort))
763 (let ((label (car (org-footnote-at-definition-p))))
764 (org-footnote-normalize 'sort)
765 (when label
766 (goto-char (point-min))
767 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
768 nil t)
769 (progn (insert " ")
770 (just-one-space)))))))
772 (provide 'org-footnote)
774 ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
776 ;;; org-footnote.el ends here