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