org-pcomplete: Update copyright year
[org-mode.git] / lisp / org-footnote.el
blob2b04e00c620dd6183be089c8f80f155b95e59066
1 ;;; org-footnote.el --- Footnote support in Org and elsewhere
2 ;;
3 ;; Copyright (C) 2009-2015 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 ;;
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;; Commentary:
27 ;; This file contains the code dealing with footnotes in Org-mode.
28 ;; The code can also be used in arbitrary text modes to provide
29 ;; footnotes. Compared to Steven L Baur's footnote.el it provides
30 ;; better support for resuming editing. It is less configurable than
31 ;; Steve's code, though.
33 ;;; Code:
35 (eval-when-compile
36 (require 'cl))
37 (require 'org-macs)
38 (require 'org-compat)
40 (declare-function message-point-in-header-p "message" ())
41 (declare-function org-back-over-empty-lines "org" ())
42 (declare-function org-back-to-heading "org" (&optional invisible-ok))
43 (declare-function org-combine-plists "org" (&rest plists))
44 (declare-function org-element-context "org-element" (&optional element))
45 (declare-function org-element-property "org-element" (property element))
46 (declare-function org-element-type "org-element" (element))
47 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
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-at-comment-p "org" ())
53 (declare-function org-in-regexp "org" (re &optional nlines visually))
54 (declare-function org-in-verbatim-emphasis "org" ())
55 (declare-function org-inside-LaTeX-fragment-p "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 org-skip-whitespace "org" ())
61 (declare-function outline-next-heading "outline")
62 (declare-function org-skip-whitespace "org" ())
64 (defvar org-outline-regexp-bol) ; defined in org.el
65 (defvar org-odd-levels-only) ; defined in org.el
66 (defvar org-bracket-link-regexp) ; defined in org.el
67 (defvar message-cite-prefix-regexp) ; defined in message.el
68 (defvar message-signature-separator) ; defined in message.el
70 (defconst org-footnote-re
71 ;; Only [1]-like footnotes are closed in this regexp, as footnotes
72 ;; from other types might contain square brackets (i.e. links) in
73 ;; their definition.
75 ;; `org-re' is used for regexp compatibility with XEmacs.
76 (concat "\\[\\(?:"
77 ;; Match inline footnotes.
78 (org-re "fn:\\([-_[:word:]]+\\)?:\\|")
79 ;; Match other footnotes.
80 "\\(?:\\([0-9]+\\)\\]\\)\\|"
81 (org-re "\\(fn:[-_[:word:]]+\\)")
82 "\\)")
83 "Regular expression for matching footnotes.")
85 (defconst org-footnote-definition-re
86 (org-re "^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
87 "Regular expression matching the definition of a footnote.")
89 (defconst org-footnote-forbidden-blocks
90 '("ascii" "beamer" "comment" "example" "html" "latex" "odt" "src")
91 "Names of blocks where footnotes are not allowed.")
93 (defgroup org-footnote nil
94 "Footnotes in Org-mode."
95 :tag "Org Footnote"
96 :group 'org)
98 (defcustom org-footnote-section "Footnotes"
99 "Outline heading containing footnote definitions.
101 This can be nil, to place footnotes locally at the end of the
102 current outline node. If can also be the name of a special
103 outline heading under which footnotes should be put.
105 This variable defines the place where Org puts the definition
106 automatically, i.e. when creating the footnote, and when sorting
107 the notes. However, by hand you may place definitions
108 *anywhere*.
110 If this is a string, during export, all subtrees starting with
111 this heading will be ignored.
113 If you don't use the customize interface to change this variable,
114 you will need to run the following command after the change:
116 \\[universal-argument] \\[org-element-cache-reset]"
117 :group 'org-footnote
118 :initialize 'custom-initialize-default
119 :set (lambda (var val)
120 (set var val)
121 (when (fboundp 'org-element-cache-reset)
122 (org-element-cache-reset 'all)))
123 :type '(choice
124 (string :tag "Collect footnotes under heading")
125 (const :tag "Define footnotes locally" nil)))
127 (defcustom org-footnote-tag-for-non-org-mode-files "Footnotes:"
128 "Tag marking the beginning of footnote section.
129 The Org footnote engine can be used in arbitrary text files as well
130 as in Org-mode. Outside Org mode, new footnotes are always placed at
131 the end of the file. When you normalize the notes, any line containing
132 only this tag will be removed, a new one will be inserted at the end
133 of the file, followed by the collected and normalized footnotes.
135 If you don't want any tag in such buffers, set this variable to nil."
136 :group 'org-footnote
137 :type '(choice
138 (string :tag "Collect footnotes under tag")
139 (const :tag "Don't use a tag" nil)))
141 (defcustom org-footnote-define-inline nil
142 "Non-nil means define footnotes inline, at reference location.
143 When nil, footnotes will be defined in a special section near
144 the end of the document. When t, the [fn:label:definition] notation
145 will be used to define the footnote at the reference position."
146 :group 'org-footnote
147 :type 'boolean)
149 (defcustom org-footnote-auto-label t
150 "Non-nil means define automatically new labels for footnotes.
151 Possible values are:
153 nil Prompt the user for each label.
154 t Create unique labels of the form [fn:1], [fn:2], etc.
155 confirm Like t, but let the user edit the created value.
156 The label can be removed from the minibuffer to create
157 an anonymous footnote.
158 random Automatically generate a unique, random label.
159 plain Automatically create plain number labels like [1]."
160 :group 'org-footnote
161 :type '(choice
162 (const :tag "Prompt for label" nil)
163 (const :tag "Create automatic [fn:N]" t)
164 (const :tag "Offer automatic [fn:N] for editing" confirm)
165 (const :tag "Create a random label" random)
166 (const :tag "Create automatic [N]" plain)))
168 (defcustom org-footnote-auto-adjust nil
169 "Non-nil means automatically adjust footnotes after insert/delete.
170 When this is t, after each insertion or deletion of a footnote,
171 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
172 If you want to have just sorting or just renumbering, set this variable
173 to `sort' or `renumber'.
175 The main values of this variable can be set with in-buffer options:
177 #+STARTUP: fnadjust
178 #+STARTUP: nofnadjust"
179 :group 'org-footnote
180 :type '(choice
181 (const :tag "No adjustment" nil)
182 (const :tag "Renumber" renumber)
183 (const :tag "Sort" sort)
184 (const :tag "Renumber and Sort" t)))
186 (defcustom org-footnote-fill-after-inline-note-extraction nil
187 "Non-nil means fill paragraphs after extracting footnotes.
188 When extracting inline footnotes, the lengths of lines can change a lot.
189 When this option is set, paragraphs from which an inline footnote has been
190 extracted will be filled again."
191 :group 'org-footnote
192 :type 'boolean)
194 (defun org-footnote-in-valid-context-p ()
195 "Is point in a context where footnotes are allowed?"
196 (save-match-data
197 (not (or (org-at-comment-p)
198 (org-inside-LaTeX-fragment-p)
199 ;; Avoid literal example.
200 (org-in-verbatim-emphasis)
201 (save-excursion
202 (beginning-of-line)
203 (looking-at "[ \t]*:[ \t]+"))
204 ;; Avoid cited text and headers in message-mode.
205 (and (derived-mode-p 'message-mode)
206 (or (save-excursion
207 (beginning-of-line)
208 (looking-at message-cite-prefix-regexp))
209 (message-point-in-header-p)))
210 ;; Avoid forbidden blocks.
211 (org-in-block-p org-footnote-forbidden-blocks)))))
213 (defun org-footnote-at-reference-p ()
214 "Is the cursor at a footnote reference?
216 If so, return a list containing its label, beginning and ending
217 positions, and the definition, when inlined."
218 (when (and (org-footnote-in-valid-context-p)
219 (or (looking-at org-footnote-re)
220 (org-in-regexp org-footnote-re)
221 (save-excursion (re-search-backward org-footnote-re nil t)))
222 (/= (match-beginning 0) (point-at-bol)))
223 (let* ((beg (match-beginning 0))
224 (label (or (org-match-string-no-properties 2)
225 (org-match-string-no-properties 3)
226 ;; Anonymous footnotes don't have labels
227 (and (match-string 1)
228 (concat "fn:" (org-match-string-no-properties 1)))))
229 ;; Inline footnotes don't end at (match-end 0) as
230 ;; `org-footnote-re' stops just after the second colon.
231 ;; Find the real ending with `scan-sexps', so Org doesn't
232 ;; get fooled by unrelated closing square brackets.
233 (end (ignore-errors (scan-sexps beg 1))))
234 ;; Point is really at a reference if it's located before true
235 ;; ending of the footnote.
236 (when (and end (< (point) end)
237 ;; Verify match isn't a part of a link.
238 (not (save-excursion
239 (goto-char beg)
240 (let ((linkp
241 (save-match-data
242 (org-in-regexp org-bracket-link-regexp))))
243 (and linkp (< (point) (cdr linkp))))))
244 ;; Verify point doesn't belong to a LaTeX macro.
245 (not (org-inside-latex-macro-p)))
246 (list label beg end
247 ;; Definition: ensure this is an inline footnote first.
248 (and (or (not label) (match-string 1))
249 (org-trim (buffer-substring-no-properties
250 (match-end 0) (1- end)))))))))
252 (defun org-footnote-at-definition-p ()
253 "Is point within a footnote definition?
255 This matches only pure definitions like [1] or [fn:name] at the
256 beginning of a line. It does not match references like
257 \[fn:name:definition], where the footnote text is included and
258 defined locally.
260 The return value will be nil if not at a footnote definition, and
261 a list with label, start, end and definition of the footnote
262 otherwise."
263 (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
264 (save-excursion
265 (end-of-line)
266 ;; Footnotes definitions are separated by new headlines, another
267 ;; footnote definition or 2 blank lines.
268 (let ((lim (save-excursion
269 (re-search-backward
270 (concat org-outline-regexp-bol
271 "\\|^\\([ \t]*\n\\)\\{2,\\}") nil t))))
272 (when (re-search-backward org-footnote-definition-re lim t)
273 (let ((label (org-match-string-no-properties 1))
274 (beg (match-beginning 0))
275 (beg-def (match-end 0))
276 ;; In message-mode, do not search after signature.
277 (end (let ((bound (and (derived-mode-p 'message-mode)
278 (save-excursion
279 (goto-char (point-max))
280 (re-search-backward
281 message-signature-separator nil t)))))
282 (if (progn
283 (end-of-line)
284 (re-search-forward
285 (concat org-outline-regexp-bol "\\|"
286 org-footnote-definition-re "\\|"
287 "^\\([ \t]*\n\\)\\{2,\\}") bound 'move))
288 (match-beginning 0)
289 (point)))))
290 (list label beg end
291 (org-trim (buffer-substring-no-properties beg-def end)))))))))
293 (defun org-footnote-get-next-reference (&optional label backward limit)
294 "Return complete reference of the next footnote.
296 If LABEL is provided, get the next reference of that footnote. If
297 BACKWARD is non-nil, find previous reference instead. LIMIT is
298 the buffer position bounding the search.
300 Return value is a list like those provided by `org-footnote-at-reference-p'.
301 If no footnote is found, return nil."
302 (save-excursion
303 (let* ((label-fmt (if label (format "\\[%s[]:]" label) org-footnote-re)))
304 (catch 'exit
305 (while t
306 (unless (funcall (if backward #'re-search-backward #'re-search-forward)
307 label-fmt limit t)
308 (throw 'exit nil))
309 (unless backward (backward-char))
310 (let ((ref (org-footnote-at-reference-p)))
311 (when ref (throw 'exit ref))))))))
313 (defun org-footnote-next-reference-or-definition (limit)
314 "Move point to next footnote reference or definition.
316 LIMIT is the buffer position bounding the search.
318 Return value is a list like those provided by
319 `org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
320 If no footnote is found, return nil."
321 (let* (ref (origin (point)))
322 (catch 'exit
323 (while t
324 (unless (re-search-forward org-footnote-re limit t)
325 (goto-char origin)
326 (throw 'exit nil))
327 ;; Beware: with [1]-like footnotes point will be just after
328 ;; the closing square bracket.
329 (backward-char)
330 (cond
331 ((setq ref (org-footnote-at-reference-p))
332 (throw 'exit ref))
333 ;; Definition: also grab the last square bracket, only
334 ;; matched in `org-footnote-re' for [1]-like footnotes.
335 ((save-match-data (org-footnote-at-definition-p))
336 (let ((end (match-end 0)))
337 (throw 'exit
338 (list nil (match-beginning 0)
339 (if (eq (char-before end) 93) end (1+ end)))))))))))
341 (defun org-footnote-get-definition (label)
342 "Return label, boundaries and definition of the footnote LABEL."
343 (let* ((label (regexp-quote (org-footnote-normalize-label label)))
344 (re (format "^\\[%s\\]\\|.\\[%s:" label label))
345 pos)
346 (save-excursion
347 (save-restriction
348 (when (or (re-search-forward re nil t)
349 (and (goto-char (point-min))
350 (re-search-forward re nil t))
351 (and (progn (widen) t)
352 (goto-char (point-min))
353 (re-search-forward re nil t)))
354 (let ((refp (org-footnote-at-reference-p)))
355 (cond
356 ((and (nth 3 refp) refp))
357 ((org-footnote-at-definition-p)))))))))
359 (defun org-footnote-goto-definition (label)
360 "Move point to the definition of the footnote LABEL.
361 Return a non-nil value when a definition has been found."
362 (interactive "sLabel: ")
363 (org-mark-ring-push)
364 (let ((def (org-footnote-get-definition label)))
365 (if (not def)
366 (error "Cannot find definition of footnote %s" label)
367 (goto-char (nth 1 def))
368 (looking-at (format "\\[%s\\]\\|\\[%s:" label label))
369 (goto-char (match-end 0))
370 (org-show-context 'link-search)
371 (when (derived-mode-p 'org-mode)
372 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))
373 t)))
375 (defun org-footnote-goto-previous-reference (label)
376 "Find the first closest (to point) reference of footnote with label LABEL."
377 (interactive "sLabel: ")
378 (org-mark-ring-push)
379 (let* ((label (org-footnote-normalize-label label)) ref)
380 (save-excursion
381 (setq ref (or (org-footnote-get-next-reference label t)
382 (org-footnote-get-next-reference label)
383 (save-restriction
384 (widen)
386 (org-footnote-get-next-reference label t)
387 (org-footnote-get-next-reference label))))))
388 (if (not ref)
389 (error "Cannot find reference of footnote %s" label)
390 (goto-char (nth 1 ref))
391 (org-show-context 'link-search))))
393 (defun org-footnote-normalize-label (label)
394 "Return LABEL as an appropriate string."
395 (cond
396 ((numberp label) (number-to-string label))
397 ((equal "" label) nil)
398 ((not (string-match "^[0-9]+$\\|^fn:" label))
399 (concat "fn:" label))
400 (t label)))
402 (defun org-footnote-all-labels (&optional with-defs)
403 "Return list with all defined foot labels used in the buffer.
405 If WITH-DEFS is non-nil, also associate the definition to each
406 label. The function will then return an alist whose key is label
407 and value definition."
408 (let* (rtn
409 (push-to-rtn
410 (function
411 ;; Depending on WITH-DEFS, store label or (label . def) of
412 ;; footnote reference/definition given as argument in RTN.
413 (lambda (el)
414 (let ((lbl (car el)))
415 (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
416 (save-excursion
417 (save-restriction
418 (widen)
419 ;; Find all labels found in definitions.
420 (goto-char (point-min))
421 (let (def)
422 (while (re-search-forward org-footnote-definition-re nil t)
423 (when (setq def (org-footnote-at-definition-p))
424 (funcall push-to-rtn def))))
425 ;; Find all labels found in references.
426 (goto-char (point-min))
427 (let (ref)
428 (while (setq ref (org-footnote-get-next-reference))
429 (goto-char (nth 2 ref))
430 (and (car ref) ; ignore anonymous footnotes
431 (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
432 (funcall push-to-rtn ref))))))
433 rtn))
435 (defun org-footnote-unique-label (&optional current)
436 "Return a new unique footnote label.
438 The function returns the first \"fn:N\" or \"N\" label that is
439 currently not used.
441 Optional argument CURRENT is the list of labels active in the
442 buffer."
443 (unless current (setq current (org-footnote-all-labels)))
444 (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
445 (cnt 1))
446 (while (member (format fmt cnt) current)
447 (incf cnt))
448 (format fmt cnt)))
450 (defun org-footnote--allow-reference-p ()
451 "Non-nil when a footnote reference can be inserted at point."
452 ;; XXX: This is similar to `org-footnote-in-valid-context-p' but
453 ;; more accurate and usually faster, except in some corner cases.
454 ;; It may replace it after doing proper benchmarks as it would be
455 ;; used in fontification.
456 (unless (bolp)
457 (let* ((context (org-element-context))
458 (type (org-element-type context)))
459 (cond
460 ;; No footnote reference in attributes.
461 ((let ((post (org-element-property :post-affiliated context)))
462 (and post (< (point) post)))
463 nil)
464 ;; Paragraphs and blank lines at top of document are fine.
465 ((memq type '(nil paragraph)))
466 ;; So are contents of verse blocks.
467 ((eq type 'verse-block)
468 (and (>= (point) (org-element-property :contents-begin context))
469 (< (point) (org-element-property :contents-end context))))
470 ;; In an headline or inlinetask, point must be either on the
471 ;; heading itself or on the blank lines below.
472 ((memq type '(headline inlinetask))
473 (or (not (org-at-heading-p))
474 (and (save-excursion (beginning-of-line)
475 (and (let ((case-fold-search t))
476 (not (looking-at "\\*+ END[ \t]*$")))
477 (looking-at org-complex-heading-regexp)))
478 (match-beginning 4)
479 (>= (point) (match-beginning 4))
480 (or (not (match-beginning 5))
481 (< (point) (match-beginning 5))))))
482 ;; White spaces after an object or blank lines after an element
483 ;; are OK.
484 ((>= (point)
485 (save-excursion (goto-char (org-element-property :end context))
486 (skip-chars-backward " \r\t\n")
487 (if (memq type org-element-all-objects) (point)
488 (1+ (line-beginning-position 2))))))
489 ;; Other elements are invalid.
490 ((memq type org-element-all-elements) nil)
491 ;; Just before object is fine.
492 ((= (point) (org-element-property :begin context)))
493 ;; Within recursive object too, but not in a link.
494 ((eq type 'link) nil)
495 ((let ((cbeg (org-element-property :contents-begin context))
496 (cend (org-element-property :contents-end context)))
497 (and cbeg (>= (point) cbeg) (<= (point) cend))))))))
499 (defun org-footnote-new ()
500 "Insert a new footnote.
501 This command prompts for a label. If this is a label referencing an
502 existing label, only insert the label. If the footnote label is empty
503 or new, let the user edit the definition of the footnote."
504 (interactive)
505 (unless (org-footnote--allow-reference-p)
506 (user-error "Cannot insert a footnote here"))
507 (let* ((all (org-footnote-all-labels))
508 (label
509 (org-footnote-normalize-label
510 (if (eq org-footnote-auto-label 'random)
511 (format "fn:%x" (random #x100000000))
512 (let ((propose (org-footnote-unique-label all)))
513 (if (memq org-footnote-auto-label '(t plain)) propose
514 (org-icompleting-read
515 "Label (leave empty for anonymous): "
516 (mapcar #'list all) nil nil
517 (and (eq org-footnote-auto-label 'confirm) propose))))))))
518 (cond ((not label)
519 (insert "[fn:: ]")
520 (backward-char 1))
521 ((member label all)
522 (insert "[" label "]")
523 (message "New reference to existing note"))
524 (org-footnote-define-inline
525 (insert "[" label ": ]")
526 (backward-char 1)
527 (org-footnote-auto-adjust-maybe))
529 (insert "[" label "]")
530 (org-footnote-create-definition label)
531 (org-footnote-auto-adjust-maybe)))))
533 (defvar org-blank-before-new-entry) ; silence byte-compiler
534 (defun org-footnote-create-definition (label)
535 "Start the definition of a footnote with label LABEL."
536 (interactive "sLabel: ")
537 (let ((label (org-footnote-normalize-label label))
538 electric-indent-mode) ;; Prevent wrong indentation
539 (cond
540 ;; In an Org file.
541 ((derived-mode-p 'org-mode)
542 ;; If `org-footnote-section' is defined, find it, or create it
543 ;; at the end of the buffer.
544 (when org-footnote-section
545 (goto-char (point-min))
546 (let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
547 (unless (or (re-search-forward re nil t)
548 (and (progn (widen) t)
549 (re-search-forward re nil t)))
550 (goto-char (point-max))
551 (skip-chars-backward " \t\r\n")
552 (unless (bolp) (newline))
553 ;; Insert new section. Separate it from the previous one
554 ;; with a blank line, unless `org-blank-before-new-entry'
555 ;; explicitly says no.
556 (when (and (cdr (assq 'heading org-blank-before-new-entry))
557 (zerop (save-excursion (org-back-over-empty-lines))))
558 (insert "\n"))
559 (insert "* " org-footnote-section "\n"))))
560 ;; Move to the end of this entry (which may be
561 ;; `org-footnote-section' or the current one).
562 (org-footnote-goto-local-insertion-point)
563 (org-show-context 'link-search))
565 ;; In a non-Org file. Search for footnote tag, or create it if
566 ;; specified (at the end of buffer, or before signature if in
567 ;; Message mode). Set point after any definition already there.
568 (let ((tag (and org-footnote-tag-for-non-org-mode-files
569 (concat "^" (regexp-quote
570 org-footnote-tag-for-non-org-mode-files)
571 "[ \t]*$")))
572 (max (if (and (derived-mode-p 'message-mode)
573 (goto-char (point-max))
574 (re-search-backward
575 message-signature-separator nil t))
576 (progn
577 ;; Ensure one blank line separates last
578 ;; footnote from signature.
579 (beginning-of-line)
580 (open-line 2)
581 (point-marker))
582 (point-max-marker))))
583 (set-marker-insertion-type max t)
584 (goto-char max)
585 ;; Check if the footnote tag is defined but missing. In this
586 ;; case, insert it, before any footnote or one blank line
587 ;; after any previous text.
588 (when (and tag (not (re-search-backward tag nil t)))
589 (skip-chars-backward " \t\r\n")
590 (while (re-search-backward org-footnote-definition-re nil t))
591 (unless (bolp) (newline 2))
592 (insert org-footnote-tag-for-non-org-mode-files "\n\n"))
593 ;; Remove superfluous white space and clear marker.
594 (goto-char max)
595 (skip-chars-backward " \t\r\n")
596 (delete-region (point) max)
597 (unless (bolp) (newline))
598 (set-marker max nil))))
599 ;; Insert footnote label.
600 (when (zerop (org-back-over-empty-lines)) (newline))
601 (insert "[" label "] \n")
602 (backward-char)
603 ;; Only notify user about next possible action when in an Org
604 ;; buffer, as the bindings may have different meanings otherwise.
605 (when (derived-mode-p 'org-mode)
606 (message
607 "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
609 ;;;###autoload
610 (defun org-footnote-action (&optional special)
611 "Do the right thing for footnotes.
613 When at a footnote reference, jump to the definition.
615 When at a definition, jump to the references if they exist, offer
616 to create them otherwise.
618 When neither at definition or reference, create a new footnote,
619 interactively if possible.
621 With prefix arg SPECIAL, or when no footnote can be created,
622 offer additional commands in a menu."
623 (interactive "P")
624 (let* ((context (and (not special) (org-element-context)))
625 (type (org-element-type context)))
626 (cond
627 ((eq type 'footnote-reference)
628 (let ((label (org-element-property :label context)))
629 (cond
630 ;; Anonymous footnote: move point at the beginning of its
631 ;; definition.
632 ((not label)
633 (goto-char (org-element-property :contents-begin context)))
634 ;; A definition exists: move to it.
635 ((ignore-errors (org-footnote-goto-definition label)))
636 ;; No definition exists: offer to create it.
637 ((yes-or-no-p (format "No definition for %s. Create one? " label))
638 (org-footnote-create-definition label)))))
639 ((eq type 'footnote-definition)
640 (org-footnote-goto-previous-reference
641 (org-element-property :label context)))
642 ((or special
643 (zerop (current-column))
644 (not (org-footnote-in-valid-context-p)))
645 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
646 (let ((c (read-char-exclusive)))
647 (cond
648 ((eq c ?s) (org-footnote-normalize 'sort))
649 ((eq c ?r) (org-footnote-renumber-fn:N))
650 ((eq c ?S)
651 (org-footnote-renumber-fn:N)
652 (org-footnote-normalize 'sort))
653 ((eq c ?n) (org-footnote-normalize))
654 ((eq c ?d) (org-footnote-delete))
655 (t (error "No such footnote command %c" c)))))
656 (t (org-footnote-new)))))
658 ;;;###autoload
659 (defun org-footnote-normalize (&optional sort-only)
660 "Collect the footnotes in various formats and normalize them.
662 This finds the different sorts of footnotes allowed in Org, and
663 normalizes them to the usual [N] format.
665 When SORT-ONLY is set, only sort the footnote definitions into the
666 referenced sequence."
667 ;; This is based on Paul's function, but rewritten.
669 ;; Re-create `org-with-limited-levels', but not limited to Org
670 ;; buffers.
671 (let* ((limit-level
672 (and (boundp 'org-inlinetask-min-level)
673 org-inlinetask-min-level
674 (1- org-inlinetask-min-level)))
675 (nstars (and limit-level
676 (if org-odd-levels-only (1- (* limit-level 2))
677 limit-level)))
678 (org-outline-regexp
679 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
680 (count 0)
681 ins-point ref ref-table)
682 (save-excursion
683 ;; 1. Find every footnote reference, extract the definition, and
684 ;; collect that data in REF-TABLE. If SORT-ONLY is nil, also
685 ;; normalize references.
686 (goto-char (point-min))
687 (while (setq ref (org-footnote-get-next-reference))
688 (let* ((lbl (car ref))
689 (pos (nth 1 ref))
690 ;; When footnote isn't anonymous, check if it's label
691 ;; (REF) is already stored in REF-TABLE. In that case,
692 ;; extract number used to identify it (MARKER). If
693 ;; footnote is unknown, increment the global counter
694 ;; (COUNT) to create an unused identifier.
695 (a (and lbl (assoc lbl ref-table)))
696 (marker (or (nth 1 a) (incf count)))
697 ;; Is the reference inline or pointing to an inline
698 ;; footnote?
699 (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
700 ;; Replace footnote reference with [MARKER]. Maybe fill
701 ;; paragraph once done. If SORT-ONLY is non-nil, only move
702 ;; to the end of reference found to avoid matching it twice.
703 (if sort-only (goto-char (nth 2 ref))
704 (delete-region (nth 1 ref) (nth 2 ref))
705 (goto-char (nth 1 ref))
706 (insert (format "[%d]" marker))
707 (and inlinep
708 org-footnote-fill-after-inline-note-extraction
709 (org-fill-paragraph)))
710 ;; Add label (REF), identifier (MARKER), definition (DEF)
711 ;; type (INLINEP) and position (POS) to REF-TABLE if data
712 ;; was unknown.
713 (unless a
714 (let ((def (or (nth 3 ref) ; Inline definition.
715 (nth 3 (org-footnote-get-definition lbl)))))
716 (push (list lbl marker def
717 ;; Reference beginning position is a marker
718 ;; to preserve it during further buffer
719 ;; modifications.
720 inlinep (copy-marker pos)) ref-table)))))
721 ;; 2. Find and remove the footnote section, if any. Also
722 ;; determine where footnotes shall be inserted (INS-POINT).
723 (cond
724 ((and org-footnote-section (derived-mode-p 'org-mode))
725 (goto-char (point-min))
726 (if (re-search-forward
727 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
728 "[ \t]*$") nil t)
729 (delete-region (match-beginning 0) (org-end-of-subtree t t)))
730 ;; A new footnote section is inserted by default at the end of
731 ;; the buffer.
732 (goto-char (point-max))
733 (skip-chars-backward " \r\t\n")
734 (forward-line)
735 (unless (bolp) (newline)))
736 ;; No footnote section set: Footnotes will be added at the end
737 ;; of the section containing their first reference.
738 ((derived-mode-p 'org-mode))
740 ;; Remove any left-over tag in the buffer, if one is set up.
741 (when org-footnote-tag-for-non-org-mode-files
742 (let ((tag (concat "^" (regexp-quote
743 org-footnote-tag-for-non-org-mode-files)
744 "[ \t]*$")))
745 (goto-char (point-min))
746 (while (re-search-forward tag nil t)
747 (replace-match "")
748 (delete-region (point) (progn (forward-line) (point))))))
749 ;; In Message mode, ensure footnotes are inserted before the
750 ;; signature.
751 (if (and (derived-mode-p 'message-mode)
752 (goto-char (point-max))
753 (re-search-backward message-signature-separator nil t))
754 (beginning-of-line)
755 (goto-char (point-max)))))
756 (setq ins-point (point-marker))
757 ;; 3. Clean-up REF-TABLE.
758 (setq ref-table
759 (delq nil
760 (mapcar
761 (lambda (x)
762 (cond
763 ;; When only sorting, ignore inline footnotes.
764 ;; Also clear position marker.
765 ((and sort-only (nth 3 x))
766 (set-marker (nth 4 x) nil) nil)
767 ;; No definition available: provide one.
768 ((not (nth 2 x))
769 (append
770 (list (car x) (nth 1 x)
771 (format "DEFINITION NOT FOUND: %s" (car x)))
772 (nthcdr 3 x)))
773 (t x)))
774 ref-table)))
775 (setq ref-table (nreverse ref-table))
776 ;; 4. Remove left-over definitions in the buffer.
777 (mapc (lambda (x)
778 (unless (nth 3 x) (org-footnote-delete-definitions (car x))))
779 ref-table)
780 ;; 5. Insert the footnotes again in the buffer, at the
781 ;; appropriate spot.
782 (goto-char ins-point)
783 (cond
784 ;; No footnote: exit.
785 ((not ref-table))
786 ;; Cases when footnotes should be inserted in one place.
787 ((or (not (derived-mode-p 'org-mode)) org-footnote-section)
788 ;; Insert again the section title, if any. Ensure that title,
789 ;; or the subsequent footnotes, will be separated by a blank
790 ;; lines from the rest of the document. In an Org buffer,
791 ;; separate section with a blank line, unless explicitly
792 ;; stated in `org-blank-before-new-entry'.
793 (if (not (derived-mode-p 'org-mode))
794 (progn (skip-chars-backward " \t\n\r")
795 (delete-region (point) ins-point)
796 (unless (bolp) (newline))
797 (when org-footnote-tag-for-non-org-mode-files
798 (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
799 (when (and (cdr (assq 'heading org-blank-before-new-entry))
800 (zerop (save-excursion (org-back-over-empty-lines))))
801 (insert "\n"))
802 (insert "* " org-footnote-section "\n"))
803 (set-marker ins-point nil)
804 ;; Insert the footnotes, separated by a blank line.
805 (insert
806 (mapconcat
807 (lambda (x)
808 ;; Clean markers.
809 (set-marker (nth 4 x) nil)
810 (format "\n[%s] %s" (nth (if sort-only 0 1) x) (nth 2 x)))
811 ref-table "\n"))
812 (unless (eobp) (insert "\n\n")))
813 ;; Each footnote definition has to be inserted at the end of
814 ;; the section where its first reference belongs.
816 (mapc
817 (lambda (x)
818 (let ((pos (nth 4 x)))
819 (goto-char pos)
820 ;; Clean marker.
821 (set-marker pos nil))
822 (org-footnote-goto-local-insertion-point)
823 (insert (format "\n[%s] %s\n"
824 (if sort-only (car x) (nth 1 x))
825 (nth 2 x))))
826 ref-table))))))
828 (defun org-footnote-goto-local-insertion-point ()
829 "Find insertion point for footnote, just before next outline heading."
830 (org-with-limited-levels (outline-next-heading))
831 (or (bolp) (newline))
832 (beginning-of-line 0)
833 (while (and (not (bobp)) (= (char-after) ?#))
834 (beginning-of-line 0))
835 (if (let ((case-fold-search t)) (looking-at "[ \t]*#\\+tblfm:")) (beginning-of-line 2))
836 (end-of-line 1)
837 (skip-chars-backward "\n\r\t ")
838 (forward-line))
840 (defun org-footnote-delete-references (label)
841 "Delete every reference to footnote LABEL.
842 Return the number of footnotes removed."
843 (save-excursion
844 (goto-char (point-min))
845 (let (ref (nref 0))
846 (while (setq ref (org-footnote-get-next-reference label))
847 (goto-char (nth 1 ref))
848 (delete-region (nth 1 ref) (nth 2 ref))
849 (incf nref))
850 nref)))
852 (defun org-footnote-delete-definitions (label)
853 "Delete every definition of the footnote LABEL.
854 Return the number of footnotes removed."
855 (save-excursion
856 (goto-char (point-min))
857 (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
858 (ndef 0))
859 (while (re-search-forward def-re nil t)
860 (let ((full-def (org-footnote-at-definition-p)))
861 (when full-def
862 ;; Remove the footnote, and all blank lines before it.
863 (goto-char (nth 1 full-def))
864 (skip-chars-backward " \r\t\n")
865 (unless (bolp) (forward-line))
866 (delete-region (point) (nth 2 full-def))
867 (incf ndef))))
868 ndef)))
870 (defun org-footnote-delete (&optional label)
871 "Delete the footnote at point.
872 This will remove the definition (even multiple definitions if they exist)
873 and all references of a footnote label.
875 If LABEL is non-nil, delete that footnote instead."
876 (catch 'done
877 (let* ((nref 0) (ndef 0) x
878 ;; 1. Determine LABEL of footnote at point.
879 (label (cond
880 ;; LABEL is provided as argument.
881 (label)
882 ;; Footnote reference at point. If the footnote is
883 ;; anonymous, delete it and exit instead.
884 ((setq x (org-footnote-at-reference-p))
885 (or (car x)
886 (progn
887 (delete-region (nth 1 x) (nth 2 x))
888 (message "Anonymous footnote removed")
889 (throw 'done t))))
890 ;; Footnote definition at point.
891 ((setq x (org-footnote-at-definition-p))
892 (car x))
893 (t (error "Don't know which footnote to remove")))))
894 ;; 2. Now that LABEL is non-nil, find every reference and every
895 ;; definition, and delete them.
896 (setq nref (org-footnote-delete-references label)
897 ndef (org-footnote-delete-definitions label))
898 ;; 3. Verify consistency of footnotes and notify user.
899 (org-footnote-auto-adjust-maybe)
900 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
901 ndef nref label))))
903 (defun org-footnote-renumber-fn:N ()
904 "Renumber the simple footnotes like fn:17 into a sequence in the document."
905 (interactive)
906 (let (map (n 0))
907 (org-with-wide-buffer
908 (goto-char (point-min))
909 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
910 (save-excursion
911 (goto-char (match-beginning 0))
912 ;; Ensure match is a footnote reference or definition.
913 (when (save-match-data (if (bolp)
914 (org-footnote-at-definition-p)
915 (org-footnote-at-reference-p)))
916 (let ((new-val (or (cdr (assoc (match-string 1) map))
917 (number-to-string (incf n)))))
918 (unless (assoc (match-string 1) map)
919 (push (cons (match-string 1) new-val) map))
920 (replace-match new-val nil nil nil 1))))))))
922 (defun org-footnote-auto-adjust-maybe ()
923 "Renumber and/or sort footnotes according to user settings."
924 (when (memq org-footnote-auto-adjust '(t renumber))
925 (org-footnote-renumber-fn:N))
926 (when (memq org-footnote-auto-adjust '(t sort))
927 (let ((label (car (org-footnote-at-definition-p))))
928 (org-footnote-normalize 'sort)
929 (when label
930 (goto-char (point-min))
931 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
932 nil t)
933 (progn (insert " ")
934 (just-one-space)))))))
936 (provide 'org-footnote)
938 ;; Local variables:
939 ;; generated-autoload-file: "org-loaddefs.el"
940 ;; End:
942 ;;; org-footnote.el ends here