org-footnote.el 34.8 KB
Newer Older
1 2
;;; org-footnote.el --- Footnote support in Org and elsewhere
;;
3
;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
;;
;; Author: Carsten Dominik <carsten at orgmode dot org>
;; Keywords: outlines, hypermedia, calendar, wp
;; Homepage: http://orgmode.org
;;
;; This file is part of GNU Emacs.
;;
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;; Commentary:

;; This file contains the code dealing with footnotes in Org-mode.
;; The code can also be used in arbitrary text modes to provide
;; footnotes.  Compared to Steven L Baur's footnote.el it provides
;; better support for resuming editing.  It is less configurable than
;; Steve's code, though.

;;; Code:

(eval-when-compile
  (require 'cl))
(require 'org-macs)
(require 'org-compat)

Bastien Guerry's avatar
Bastien Guerry committed
40 41 42
(declare-function message-point-in-header-p "message" ())
(declare-function org-back-over-empty-lines "org" ())
(declare-function org-back-to-heading "org" (&optional invisible-ok))
43
(declare-function org-combine-plists "org" (&rest plists))
Bastien Guerry's avatar
Bastien Guerry committed
44 45 46 47 48 49 50
(declare-function org-end-of-subtree "org"  (&optional invisible-ok to-heading))
(declare-function org-export-preprocess-string "org-exp"
		  (string &rest parameters))
(declare-function org-fill-paragraph "org" (&optional justify))
(declare-function org-icompleting-read "org" (&rest args))
(declare-function org-id-uuid "org-id" ())
(declare-function org-in-block-p "org" (names))
51
(declare-function org-in-commented-line "org" ())
52
(declare-function org-in-indented-comment-line "org" ())
53
(declare-function org-in-regexp "org" (re &optional nlines visually))
54
(declare-function org-in-verbatim-emphasis "org" ())
Bastien Guerry's avatar
Bastien Guerry committed
55
(declare-function org-inside-LaTeX-fragment-p "org" ())
56
(declare-function org-inside-latex-macro-p "org" ())
Bastien Guerry's avatar
Bastien Guerry committed
57 58 59 60
(declare-function org-mark-ring-push "org" (&optional pos buffer))
(declare-function org-show-context "org" (&optional key))
(declare-function org-trim "org" (s))
(declare-function outline-next-heading "outline")
61

Bastien Guerry's avatar
Bastien Guerry committed
62 63 64 65 66
(defvar org-outline-regexp-bol)		; defined in org.el
(defvar org-odd-levels-only)		; defined in org.el
(defvar org-bracket-link-regexp)	; defined in org.el
(defvar message-cite-prefix-regexp)	; defined in message.el
(defvar message-signature-separator)	; defined in message.el
67 68

(defconst org-footnote-re
69 70 71 72 73
  ;; Only [1]-like footnotes are closed in this regexp, as footnotes
  ;; from other types might contain square brackets (i.e. links) in
  ;; their definition.
  ;;
  ;; `org-re' is used for regexp compatibility with XEmacs.
Bastien Guerry's avatar
Bastien Guerry committed
74 75 76 77 78 79 80
  (concat "\\[\\(?:"
	  ;; Match inline footnotes.
	  (org-re "fn:\\([-_[:word:]]+\\)?:\\|")
	  ;; Match other footnotes.
	  "\\(?:\\([0-9]+\\)\\]\\)\\|"
	  (org-re "\\(fn:[-_[:word:]]+\\)")
	  "\\)")
81 82
  "Regular expression for matching footnotes.")

83
(defconst org-footnote-definition-re
Bastien Guerry's avatar
Bastien Guerry committed
84
  (org-re "^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
85 86
  "Regular expression matching the definition of a footnote.")

87 88 89 90
(defvar org-footnote-forbidden-blocks '("example" "verse" "src" "ascii" "beamer"
					"docbook" "html" "latex" "odt")
  "Names of blocks where footnotes are not allowed.")

91 92 93 94 95
(defgroup org-footnote nil
  "Footnotes in Org-mode."
  :tag "Org Footnote"
  :group 'org)

96 97 98 99 100 101 102 103 104 105
(defcustom org-footnote-section "Footnotes"
  "Outline heading containing footnote definitions before export.
This can be nil, to place footnotes locally at the end of the current
outline node.  If can also be the name of a special outline heading
under which footnotes should be put.
This variable defines the place where Org puts the definition
automatically, i.e. when creating the footnote, and when sorting the notes.
However, by hand you may place definitions *anywhere*.
If this is a string, during export, all subtrees starting with this
heading will be removed after extracting footnote definitions."
106
  :group 'org-footnote
107
  :type '(choice
108
	  (string :tag "Collect footnotes under heading")
109 110 111 112
	  (const :tag "Define footnotes locally" nil)))

(defcustom org-footnote-tag-for-non-org-mode-files "Footnotes:"
  "Tag marking the beginning of footnote section.
Bastien Guerry's avatar
Bastien Guerry committed
113 114
The Org footnote engine can be used in arbitrary text files as well
as in Org-mode.  Outside Org mode, new footnotes are always placed at
115 116
the end of the file.  When you normalize the notes, any line containing
only this tag will be removed, a new one will be inserted at the end
Bastien Guerry's avatar
Bastien Guerry committed
117 118 119
of the file, followed by the collected and normalized footnotes.

If you don't want any tag in such buffers, set this variable to nil."
120
  :group 'org-footnote
Bastien Guerry's avatar
Bastien Guerry committed
121 122 123
  :type '(choice
	  (string :tag "Collect footnotes under tag")
	  (const :tag "Don't use a tag" nil)))
124 125

(defcustom org-footnote-define-inline nil
126
  "Non-nil means define footnotes inline, at reference location.
127 128 129 130 131 132 133
When nil, footnotes will be defined in a special section near
the end of the document.  When t, the [fn:label:definition] notation
will be used to define the footnote at the reference position."
  :group 'org-footnote
  :type 'boolean)

(defcustom org-footnote-auto-label t
134
  "Non-nil means define automatically new labels for footnotes.
135 136 137 138 139 140 141
Possible values are:

nil        prompt the user for each label
t          create unique labels of the form [fn:1], [fn:2], ...
confirm    like t, but let the user edit the created value.  In particular,
           the label can be removed from the minibuffer, to create
           an anonymous footnote.
142
random	   Automatically generate a unique, random label.
143 144 145
plain      Automatically create plain number labels like [1]"
  :group 'org-footnote
  :type '(choice
146
	  (const :tag "Prompt for label" nil)
147 148
	  (const :tag "Create automatic [fn:N]" t)
	  (const :tag "Offer automatic [fn:N] for editing" confirm)
149
	  (const :tag "Create a random label" random)
150 151
	  (const :tag "Create automatic [N]" plain)))

152
(defcustom org-footnote-auto-adjust nil
153
  "Non-nil means automatically adjust footnotes after insert/delete.
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
When this is t, after each insertion or deletion of a footnote,
simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
If you want to have just sorting or just renumbering, set this variable
to `sort' or `renumber'.

The main values of this variable can be set with in-buffer options:

#+STARTUP: fnadjust
#+STARTUP: nofnadjust"
  :group 'org-footnote
  :type '(choice
	  (const :tag "Renumber" renumber)
	  (const :tag "Sort" sort)
	  (const :tag "Renumber and Sort" t)))

169
(defcustom org-footnote-fill-after-inline-note-extraction nil
170
  "Non-nil means fill paragraphs after extracting footnotes.
171 172 173 174 175 176
When extracting inline footnotes, the lengths of lines can change a lot.
When this option is set, paragraphs from which an inline footnote has been
extracted will be filled again."
  :group 'org-footnote
  :type 'boolean)

177 178 179 180 181
(defun org-footnote-in-valid-context-p ()
  "Is point in a context where footnotes are allowed?"
  (save-match-data
    (not (or (org-in-commented-line)
	     (org-in-indented-comment-line)
Bastien Guerry's avatar
Bastien Guerry committed
182 183 184
	     (org-inside-LaTeX-fragment-p)
	     ;; Avoid protected environments (LaTeX export)
	     (get-text-property (point) 'org-protected)
185
	     ;; Avoid literal example.
Bastien Guerry's avatar
Bastien Guerry committed
186
	     (org-in-verbatim-emphasis)
187 188 189 190 191 192 193 194 195 196 197 198
	     (save-excursion
	       (beginning-of-line)
	       (looking-at "[ \t]*:[ \t]+"))
	     ;; Avoid cited text and headers in message-mode.
	     (and (derived-mode-p 'message-mode)
		  (or (save-excursion
			(beginning-of-line)
			(looking-at message-cite-prefix-regexp))
		      (message-point-in-header-p)))
	     ;; Avoid forbidden blocks.
	     (org-in-block-p org-footnote-forbidden-blocks)))))

199 200
(defun org-footnote-at-reference-p ()
  "Is the cursor at a footnote reference?
201 202 203 204 205 206 207

If so, return a list containing its label, beginning and ending
positions, and the definition, when inlined."
  (when (and (org-footnote-in-valid-context-p)
	     (or (looking-at org-footnote-re)
		 (org-in-regexp org-footnote-re)
		 (save-excursion (re-search-backward org-footnote-re nil t)))
Bastien Guerry's avatar
Bastien Guerry committed
208
	     (/= (match-beginning 0) (point-at-bol)))
209
    (let* ((beg (match-beginning 0))
Bastien Guerry's avatar
Bastien Guerry committed
210 211
	   (label (or (org-match-string-no-properties 2)
		      (org-match-string-no-properties 3)
212
		      ;; Anonymous footnotes don't have labels
Bastien Guerry's avatar
Bastien Guerry committed
213 214
		      (and (match-string 1)
			   (concat "fn:" (org-match-string-no-properties 1)))))
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
	   ;; Inline footnotes don't end at (match-end 0) as
	   ;; `org-footnote-re' stops just after the second colon.
	   ;; Find the real ending with `scan-sexps', so Org doesn't
	   ;; get fooled by unrelated closing square brackets.
	   (end (ignore-errors (scan-sexps beg 1))))
      ;; Point is really at a reference if it's located before true
      ;; ending of the footnote.
      (when (and end (< (point) end)
		 ;; Verify match isn't a part of a link.
		 (not (save-excursion
			(goto-char beg)
			(let ((linkp
			       (save-match-data
				 (org-in-regexp org-bracket-link-regexp))))
			  (and linkp (< (point) (cdr linkp))))))
		 ;; Verify point doesn't belong to a LaTeX macro.
		 ;; Beware though, when two footnotes are side by
		 ;; side, once the first one is changed into LaTeX,
		 ;; the second one might then be considered as an
		 ;; optional argument of the command.  Thus, check
		 ;; the `org-protected' property of that command.
		 (or (not (org-inside-latex-macro-p))
Bastien Guerry's avatar
Bastien Guerry committed
237
		     (get-text-property (1- beg) 'org-protected)))
238 239 240
	(list label beg end
	      ;; Definition: ensure this is an inline footnote first.
	      (and (or (not label) (match-string 1))
Bastien Guerry's avatar
Bastien Guerry committed
241 242
		   (org-trim (buffer-substring-no-properties
			      (match-end 0) (1- end)))))))))
243 244

(defun org-footnote-at-definition-p ()
245 246
  "Is the cursor at a footnote definition?

247
This matches only pure definitions like [1] or [fn:name] at the beginning
248
of a line.  It does not match references like [fn:name:definition], where the
249
footnote text is included and defined locally.
250 251 252

The return value will be nil if not at a footnote definition, and a list with
label, start, end and definition of the footnote otherwise."
Bastien Guerry's avatar
Bastien Guerry committed
253
  (when (save-excursion (beginning-of-line) (org-footnote-in-valid-context-p))
254 255 256 257 258 259 260
    (save-excursion
      (end-of-line)
      (let ((lim (save-excursion (re-search-backward
				  (concat org-outline-regexp-bol
					  "\\|^[ \t]*$") nil t))))
	(when (re-search-backward org-footnote-definition-re lim t)
	  (end-of-line)
Bastien Guerry's avatar
Bastien Guerry committed
261
	  (list (org-match-string-no-properties 1)
262 263 264 265 266 267 268 269 270
		(match-beginning 0)
		(save-match-data
		  ;; In a message, limit search to signature.
		  (let ((bound (and (derived-mode-p 'message-mode)
				    (save-excursion
				      (goto-char (point-max))
				      (re-search-backward
				       message-signature-separator nil t)))))
		    (or (and (re-search-forward
Bastien Guerry's avatar
Bastien Guerry committed
271 272 273
			      (concat org-outline-regexp-bol "\\|"
				      org-footnote-definition-re "\\|"
				      "^[ \t]*$")
274 275 276
			      bound 'move)
			     (progn (skip-chars-forward " \t\n") (point-at-bol)))
			(point))))
Bastien Guerry's avatar
Bastien Guerry committed
277 278
		(org-trim (buffer-substring-no-properties
			   (match-end 0) (point)))))))))
279 280 281 282 283 284 285 286 287 288

(defun org-footnote-get-next-reference (&optional label backward limit)
  "Return complete reference of the next footnote.

If LABEL is provided, get the next reference of that footnote.  If
BACKWARD is non-nil, find previous reference instead.  LIMIT is
the buffer position bounding the search.

Return value is a list like those provided by `org-footnote-at-reference-p'.
If no footnote is found, return nil."
289
  (save-excursion
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    (let* ((label-fmt (if label (format "\\[%s[]:]" label) org-footnote-re)))
      (catch 'exit
	(while t
	  (unless (funcall (if backward #'re-search-backward #'re-search-forward)
			   label-fmt limit t)
	    (throw 'exit nil))
	  (unless backward (backward-char))
	  (let ((ref (org-footnote-at-reference-p)))
	    (when ref (throw 'exit ref))))))))

(defun org-footnote-next-reference-or-definition (limit)
  "Move point to next footnote reference or definition.

LIMIT is the buffer position bounding the search.

Return value is a list like those provided by
`org-footnote-at-reference-p' or `org-footnote-at-definition-p'.
If no footnote is found, return nil."
Bastien Guerry's avatar
Bastien Guerry committed
308
  (let* (ref (origin (point)))
309 310 311
    (catch 'exit
      (while t
	(unless (re-search-forward org-footnote-re limit t)
Bastien Guerry's avatar
Bastien Guerry committed
312
	  (goto-char origin)
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
	  (throw 'exit nil))
	;; Beware: with [1]-like footnotes point will be just after
	;; the closing square bracket.
	(backward-char)
	(cond
	 ((setq ref (org-footnote-at-reference-p))
	  (throw 'exit ref))
	 ;; Definition: also grab the last square bracket, only
	 ;; matched in `org-footnote-re' for [1]-like footnotes.
	 ((save-match-data (org-footnote-at-definition-p))
	  (let ((end (match-end 0)))
	    (throw 'exit
		   (list nil (match-beginning 0)
			 (if (eq (char-before end) 93) end (1+ end)))))))))))

(defun org-footnote-get-definition (label)
  "Return label, boundaries and definition of the footnote LABEL."
  (let* ((label (regexp-quote (org-footnote-normalize-label label)))
	 (re (format "^\\[%s\\]\\|.\\[%s:" label label))
	 pos)
    (save-excursion
Bastien Guerry's avatar
Bastien Guerry committed
334 335 336 337 338 339 340 341 342 343 344
      (save-restriction
	(when (or (re-search-forward re nil t)
		  (and (goto-char (point-min))
		       (re-search-forward re nil t))
		  (and (progn (widen) t)
		       (goto-char (point-min))
		       (re-search-forward re nil t)))
	  (let ((refp (org-footnote-at-reference-p)))
	    (cond
	     ((and (nth 3 refp) refp))
	     ((org-footnote-at-definition-p)))))))))
345 346

(defun org-footnote-goto-definition (label)
Bastien Guerry's avatar
Bastien Guerry committed
347 348
  "Move point to the definition of the footnote LABEL.
Return a non-nil value when a definition has been found."
349 350
  (interactive "sLabel: ")
  (org-mark-ring-push)
351 352
  (let ((def (org-footnote-get-definition label)))
    (if (not def)
353
	(error "Cannot find definition of footnote %s" label)
354 355 356
      (goto-char (nth 1 def))
      (looking-at (format "\\[%s\\]\\|\\[%s:" label label))
      (goto-char (match-end 0))
357
      (org-show-context 'link-search)
Bastien Guerry's avatar
Bastien Guerry committed
358 359 360
      (when (eq major-mode 'org-mode)
	(message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))
      t)))
361

362
(defun org-footnote-goto-previous-reference (label)
Carsten Dominik's avatar
Carsten Dominik committed
363
  "Find the first closest (to point) reference of footnote with label LABEL."
364 365
  (interactive "sLabel: ")
  (org-mark-ring-push)
366
  (let* ((label (org-footnote-normalize-label label)) ref)
367
    (save-excursion
368 369 370 371 372 373 374 375 376 377 378
      (setq ref (or (org-footnote-get-next-reference label t)
		    (org-footnote-get-next-reference label)
		    (save-restriction
		      (widen)
		      (or
		       (org-footnote-get-next-reference label t)
		       (org-footnote-get-next-reference label))))))
    (if (not ref)
	(error "Cannot find reference of footnote %s" label)
      (goto-char (nth 1 ref))
      (org-show-context 'link-search))))
379 380

(defun org-footnote-normalize-label (label)
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
  "Return LABEL as an appropriate string."
  (cond
   ((numberp label) (number-to-string label))
   ((equal "" label) nil)
   ((not (string-match "^[0-9]+$\\|^fn:" label))
    (concat "fn:" label))
   (t label)))

(defun org-footnote-all-labels (&optional with-defs)
  "Return list with all defined foot labels used in the buffer.

If WITH-DEFS is non-nil, also associate the definition to each
label.  The function will then return an alist whose key is label
and value definition."
  (let* (rtn
	 (push-to-rtn
	  (function
	   ;; Depending on WITH-DEFS, store label or (label . def) of
	   ;; footnote reference/definition given as argument in RTN.
	   (lambda (el)
	     (let ((lbl (car el)))
	       (push (if with-defs (cons lbl (nth 3 el)) lbl) rtn))))))
403 404 405
    (save-excursion
      (save-restriction
	(widen)
406
	;; Find all labels found in definitions.
407
	(goto-char (point-min))
408 409 410 411 412
	(let (def)
	  (while (re-search-forward org-footnote-definition-re nil t)
	    (when (setq def (org-footnote-at-definition-p))
	      (funcall push-to-rtn def))))
	;; Find all labels found in references.
413
	(goto-char (point-min))
414 415 416 417 418 419
	(let (ref)
	  (while (setq ref (org-footnote-get-next-reference))
	    (goto-char (nth 2 ref))
	    (and (car ref)		; ignore anonymous footnotes
		 (not (funcall (if with-defs #'assoc #'member) (car ref) rtn))
		 (funcall push-to-rtn ref))))))
420 421 422 423
    rtn))

(defun org-footnote-unique-label (&optional current)
  "Return a new unique footnote label.
Bastien Guerry's avatar
Bastien Guerry committed
424 425 426 427 428 429

The function returns the first \"fn:N\" or \"N\" label that is
currently not used.

Optional argument CURRENT is the list of labels active in the
buffer."
430 431 432 433 434 435 436 437 438 439 440 441 442
  (unless current (setq current (org-footnote-all-labels)))
  (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
	(cnt 1))
    (while (member (format fmt cnt) current)
      (incf cnt))
    (format fmt cnt)))

(defun org-footnote-new ()
  "Insert a new footnote.
This command prompts for a label.  If this is a label referencing an
existing label, only insert the label.  If the footnote label is empty
or new, let the user edit the definition of the footnote."
  (interactive)
Bastien Guerry's avatar
Bastien Guerry committed
443
  (unless (org-footnote-in-valid-context-p)
444
    (error "Cannot insert a footnote here"))
Bastien Guerry's avatar
Bastien Guerry committed
445 446 447
  (let* ((lbls (and (not (equal org-footnote-auto-label 'random))
		    (org-footnote-all-labels)))
	 (propose (org-footnote-unique-label lbls))
448
	 (label
449 450 451 452 453 454 455 456
	  (org-footnote-normalize-label
	   (cond
	    ((member org-footnote-auto-label '(t plain))
	     propose)
	    ((equal org-footnote-auto-label 'random)
	     (require 'org-id)
	     (substring (org-id-uuid) 0 8))
	    (t
Bastien Guerry's avatar
Bastien Guerry committed
457
	     (org-icompleting-read
458
	      "Label (leave empty for anonymous): "
Bastien Guerry's avatar
Bastien Guerry committed
459 460
	      (mapcar 'list lbls) nil nil
	      (if (eq org-footnote-auto-label 'confirm) propose nil)))))))
461
    (cond
Bastien Guerry's avatar
Bastien Guerry committed
462
     ((bolp) (error "Cannot create a footnote reference at left margin"))
463
     ((not label)
464 465
      (insert "[fn:: ]")
      (backward-char 1))
Bastien Guerry's avatar
Bastien Guerry committed
466
     ((member label lbls)
467 468 469 470
      (insert "[" label "]")
      (message "New reference to existing note"))
     (org-footnote-define-inline
      (insert "[" label ": ]")
471 472
      (backward-char 1)
      (org-footnote-auto-adjust-maybe))
473 474
     (t
      (insert "[" label "]")
475 476
      (org-footnote-create-definition label)
      (org-footnote-auto-adjust-maybe)))))
477

478
(defvar org-blank-before-new-entry) ; silence byte-compiler
479 480 481
(defun org-footnote-create-definition (label)
  "Start the definition of a footnote with label LABEL."
  (interactive "sLabel: ")
482
  (let ((label (org-footnote-normalize-label label)))
483
    (cond
Bastien Guerry's avatar
Bastien Guerry committed
484 485 486 487
     ;; In an Org file.
     ((eq major-mode 'org-mode)
      ;; If `org-footnote-section' is defined, find it, or create it
      ;; at the end of the buffer.
488 489 490 491 492 493
      (when org-footnote-section
	(goto-char (point-min))
	(let ((re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$")))
	  (unless (or (re-search-forward re nil t)
		      (and (progn (widen) t)
			   (re-search-forward re nil t)))
Bastien Guerry's avatar
Bastien Guerry committed
494 495 496 497 498 499 500 501 502 503 504 505
	    (goto-char (point-max))
	    (skip-chars-backward " \t\r\n")
	    (unless (bolp) (newline))
	    ;; Insert new section.  Separate it from the previous one
	    ;; with a blank line, unless `org-blank-before-new-entry'
	    ;; explicitly says no.
	    (when (and (cdr (assq 'heading org-blank-before-new-entry))
		       (zerop (save-excursion (org-back-over-empty-lines))))
	      (insert "\n"))
	    (insert "* " org-footnote-section "\n"))))
      ;; Move to the end of this entry (which may be
      ;; `org-footnote-section' or the current one).
506 507
      (org-footnote-goto-local-insertion-point)
      (org-show-context 'link-search))
508
     (t
509
      ;; In a non-Org file.  Search for footnote tag, or create it if
Bastien Guerry's avatar
Bastien Guerry committed
510
      ;; specified (at the end of buffer, or before signature if in
511
      ;; Message mode).  Set point after any definition already there.
Bastien Guerry's avatar
Bastien Guerry committed
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
      (let ((tag (and org-footnote-tag-for-non-org-mode-files
		      (concat "^" (regexp-quote
				   org-footnote-tag-for-non-org-mode-files)
			      "[ \t]*$")))
	    (max (if (and (derived-mode-p 'message-mode)
			  (goto-char (point-max))
			  (re-search-backward
			   message-signature-separator nil t))
		     (progn
		       ;; Ensure one blank line separates last
		       ;; footnote from signature.
		       (beginning-of-line)
		       (open-line 2)
		       (point-marker))
		   (point-max-marker))))
	(set-marker-insertion-type max t)
528
	(goto-char max)
Bastien Guerry's avatar
Bastien Guerry committed
529 530 531 532
	;; Check if the footnote tag is defined but missing.  In this
	;; case, insert it, before any footnote or one blank line
	;; after any previous text.
	(when (and tag (not (re-search-backward tag nil t)))
Carsten Dominik's avatar
Carsten Dominik committed
533
	  (skip-chars-backward " \t\r\n")
Bastien Guerry's avatar
Bastien Guerry committed
534 535 536 537 538 539 540 541
	  (while (re-search-backward org-footnote-definition-re nil t))
	  (unless (bolp) (newline 2))
	  (insert org-footnote-tag-for-non-org-mode-files "\n\n"))
	;; Remove superfluous white space and clear marker.
	(goto-char max)
	(skip-chars-backward " \t\r\n")
	(delete-region (point) max)
	(unless (bolp) (newline))
542
	(set-marker max nil))))
Bastien Guerry's avatar
Bastien Guerry committed
543 544 545 546 547 548 549
    ;; Insert footnote label.
    (insert "\n[" label "] ")
    ;; Only notify user about next possible action when in an Org
    ;; buffer, as the bindings may have different meanings otherwise.
    (when (eq major-mode 'org-mode)
      (message
       "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
550 551 552 553

;;;###autoload
(defun org-footnote-action (&optional special)
  "Do the right thing for footnotes.
554 555 556 557 558 559 560 561 562

When at a footnote reference, jump to the definition.

When at a definition, jump to the references if they exist, offer
to create them otherwise.

When neither at definition or reference, create a new footnote,
interactively.

563 564 565 566 567
With prefix arg SPECIAL, offer additional commands in a menu."
  (interactive "P")
  (let (tmp c)
    (cond
     (special
568
      (message "Footnotes: [s]ort  |  [r]enumber fn:N  |  [S]=r+s |->[n]umeric  |  [d]elete")
569 570
      (setq c (read-char-exclusive))
      (cond
571 572 573
       ((eq c ?s) (org-footnote-normalize 'sort))
       ((eq c ?r) (org-footnote-renumber-fn:N))
       ((eq c ?S)
574 575
	(org-footnote-renumber-fn:N)
	(org-footnote-normalize 'sort))
576 577
       ((eq c ?n) (org-footnote-normalize))
       ((eq c ?d) (org-footnote-delete))
578 579
       (t (error "No such footnote command %c" c))))
     ((setq tmp (org-footnote-at-reference-p))
580 581 582 583 584 585 586 587 588 589 590
      (cond
       ;; Anonymous footnote: move point at the beginning of its
       ;; definition.
       ((not (car tmp))
	(goto-char (nth 1 tmp))
	(forward-char 5))
       ;; A definition exists: move to it.
       ((ignore-errors (org-footnote-goto-definition (car tmp))))
       ;; No definition exists: offer to create it.
       ((yes-or-no-p (format "No definition for %s.  Create one? " (car tmp)))
	(org-footnote-create-definition (car tmp)))))
591
     ((setq tmp (org-footnote-at-definition-p))
592
      (org-footnote-goto-previous-reference (car tmp)))
593 594
     (t (org-footnote-new)))))

595 596 597
(defvar org-footnote-insert-pos-for-preprocessor 'point-max
  "See `org-footnote-normalize'.")

598 599
(defvar org-export-footnotes-seen) ; silence byte-compiler
(defvar org-export-footnotes-data) ; silence byte-compiler
600

601
;;;###autoload
602
(defun org-footnote-normalize (&optional sort-only export-props)
603
  "Collect the footnotes in various formats and normalize them.
604

605
This finds the different sorts of footnotes allowed in Org, and
606 607
normalizes them to the usual [N] format that is understood by the
Org-mode exporters.
608

609
When SORT-ONLY is set, only sort the footnote definitions into the
610 611 612 613 614 615
referenced sequence.

If Org is amidst an export process, EXPORT-PROPS will hold the
export properties of the buffer.

When EXPORT-PROPS is non-nil, the default action is to insert
Bastien Guerry's avatar
Bastien Guerry committed
616 617 618 619 620
normalized footnotes towards the end of the pre-processing
buffer.  Some exporters (docbook, odt...) expect footnote
definitions to be available before any references to them.  Such
exporters can let bind `org-footnote-insert-pos-for-preprocessor'
to symbol `point-min' to achieve the desired behaviour.
621 622 623 624 625 626

Additional note on `org-footnote-insert-pos-for-preprocessor':
1. This variable has not effect when FOR-PREPROCESSOR is nil.
2. This variable (potentially) obviates the need for extra scan
   of pre-processor buffer as witnessed in
   `org-export-docbook-get-footnotes'."
627
  ;; This is based on Paul's function, but rewritten.
628 629 630
  ;;
  ;; Re-create `org-with-limited-levels', but not limited to Org
  ;; buffers.
631 632 633 634 635 636 637 638
  (let* ((limit-level
	  (and (boundp 'org-inlinetask-min-level)
	       org-inlinetask-min-level
	       (1- org-inlinetask-min-level)))
	 (nstars (and limit-level
		      (if org-odd-levels-only
			  (and limit-level (1- (* limit-level 2)))
			limit-level)))
639
	 (org-outline-regexp
640
	  (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
641 642 643 644 645 646 647 648 649 650
	 ;; Determine the highest marker used so far.
	 (ref-table (when export-props org-export-footnotes-seen))
	 (count (if (and export-props ref-table)
		    (apply 'max (mapcar (lambda (e) (nth 1 e)) ref-table))
		  0))
	 ins-point ref)
    (save-excursion
      ;; 1. Find every footnote reference, extract the definition, and
      ;;    collect that data in REF-TABLE.  If SORT-ONLY is nil, also
      ;;    normalize references.
651
      (goto-char (point-min))
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
      (while (setq ref (org-footnote-get-next-reference))
	(let* ((lbl (car ref))
	       ;; When footnote isn't anonymous, check if it's label
	       ;; (REF) is already stored in REF-TABLE.  In that case,
	       ;; extract number used to identify it (MARKER).  If
	       ;; footnote is unknown, increment the global counter
	       ;; (COUNT) to create an unused identifier.
	       (a (and lbl (assoc lbl ref-table)))
	       (marker (or (nth 1 a) (incf count)))
	       ;; Is the reference inline or pointing to an inline
	       ;; footnote?
	       (inlinep (or (stringp (nth 3 ref)) (nth 3 a))))
	  ;; Replace footnote reference with [MARKER].  Maybe fill
	  ;; paragraph once done.  If SORT-ONLY is non-nil, only move
	  ;; to the end of reference found to avoid matching it twice.
	  ;; If EXPORT-PROPS isn't nil, also add `org-footnote'
	  ;; property to it, so it can be easily recognized by
	  ;; exporters.
	  (if sort-only
	      (goto-char (nth 2 ref))
	    (delete-region (nth 1 ref) (nth 2 ref))
	    (goto-char (nth 1 ref))
	    (let ((new-ref (format "[%d]" marker)))
	      (when export-props (org-add-props new-ref '(org-footnote t)))
	      (insert new-ref))
	    (and inlinep
		 org-footnote-fill-after-inline-note-extraction
		 (org-fill-paragraph)))
Bastien Guerry's avatar
Bastien Guerry committed
680 681
	  ;; Add label (REF), identifier (MARKER), definition (DEF)
	  ;; and type (INLINEP) to REF-TABLE if data was unknown.
682 683 684 685 686 687 688 689 690 691
	  (unless a
	    (let ((def (or (nth 3 ref)	; inline
			   (and export-props
				(cdr (assoc lbl org-export-footnotes-data)))
			   (nth 3 (org-footnote-get-definition lbl)))))
	      (push (list lbl marker
			  ;; When exporting, each definition goes
			  ;; through `org-export-preprocess-string' so
			  ;; it is ready to insert in the
			  ;; backend-specific buffer.
Bastien Guerry's avatar
Bastien Guerry committed
692
			  (if (and export-props def)
693 694 695 696 697 698
			      (let ((parameters
				     (org-combine-plists
				      export-props
				      '(:todo-keywords t :tags t :priority t))))
				(org-export-preprocess-string def parameters))
			    def)
Bastien Guerry's avatar
Bastien Guerry committed
699
			  inlinep) ref-table)))))
700 701
      ;; 2. Find and remove the footnote section, if any.  Also
      ;;    determine where footnotes shall be inserted (INS-POINT).
702 703
      (goto-char (point-min))
      (cond
Bastien Guerry's avatar
Bastien Guerry committed
704 705 706 707 708 709 710 711 712 713
       ((and org-footnote-section
	     (eq major-mode 'org-mode)
	     (re-search-forward
	      (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
		      "[ \t]*$")
	      nil t))
	(delete-region (match-beginning 0) (org-end-of-subtree t)))
       ((eq major-mode 'org-mode)
	(goto-char (point-max))
	(unless (bolp) (newline)))
714
       (t
Bastien Guerry's avatar
Bastien Guerry committed
715 716 717 718 719 720 721 722 723
	;; Remove any left-over tag in the buffer, if one is set up.
	(when org-footnote-tag-for-non-org-mode-files
	  (let ((tag (concat "^" (regexp-quote
				  org-footnote-tag-for-non-org-mode-files)
			     "[ \t]*$")))
	    (while (re-search-forward tag nil t)
	      (replace-match "")
	      (delete-region (point) (progn (forward-line) (point))))))
	;; In Message mode, ensure footnotes are inserted before the
724
	;; signature.
Bastien Guerry's avatar
Bastien Guerry committed
725 726 727 728 729 730 731 732 733 734 735 736 737
	(if (and (derived-mode-p 'message-mode)
		 (goto-char (point-max))
		 (re-search-backward message-signature-separator nil t))
	    (beginning-of-line)
	  (goto-char (point-max)))))
      ;; During export, `org-footnote-insert-pos-for-preprocessor' has
      ;; precedence over previously found position.
      (setq ins-point
	    (copy-marker
	     (if (and export-props
		      (eq org-footnote-insert-pos-for-preprocessor 'point-min))
		 (point-min)
	       (point))))
738
      ;; 3. Clean-up REF-TABLE.
739
      (setq ref-table
740 741
	    (delq nil
		  (mapcar
742
		   (lambda (x)
743 744 745 746 747 748 749 750 751 752 753
		     (cond
		      ;; When only sorting, ignore inline footnotes.
		      ((and sort-only (nth 3 x)) nil)
		      ;; No definition available: provide one.
		      ((not (nth 2 x))
		       (append (butlast x 2)
			       (list (format "DEFINITION NOT FOUND: %s" (car x))
				     (nth 3 x))))
		      (t x)))
		   ref-table)))
      (setq ref-table (nreverse ref-table))
Bastien Guerry's avatar
Bastien Guerry committed
754 755 756 757 758
      ;; 4. Remove left-over definitions in the buffer.
      (mapc (lambda (x) (unless (nth 3 x)
		     (org-footnote-delete-definitions (car x))))
	    ref-table)
      ;; 5. Insert the footnotes again in the buffer, at the
759
      ;;    appropriate spot.
Bastien Guerry's avatar
Bastien Guerry committed
760
      (goto-char ins-point)
761 762 763 764
      (cond
       ;; No footnote: exit.
       ((not ref-table))
       ;; Cases when footnotes should be inserted in one place.
Bastien Guerry's avatar
Bastien Guerry committed
765
       ((or (not (eq major-mode 'org-mode))
766 767
	    org-footnote-section
	    (not sort-only))
Bastien Guerry's avatar
Bastien Guerry committed
768 769 770 771 772
	;; Insert again the section title, if any.  Ensure that title,
	;; or the subsequent footnotes, will be separated by a blank
	;; lines from the rest of the document.  In an Org buffer,
	;; separate section with a blank line, unless explicitly
	;; stated in `org-blank-before-new-entry'.
773
	(cond
Bastien Guerry's avatar
Bastien Guerry committed
774 775 776 777 778 779 780 781 782 783 784
	 ((not (eq major-mode 'org-mode))
	  (skip-chars-backward " \t\n\r")
	  (delete-region (point) ins-point)
	  (unless (bolp) (newline))
	  ;; Keep one blank line between footnotes and signature.
	  (when (and (derived-mode-p 'message-mode)
		     (save-excursion
		       (re-search-forward message-signature-separator nil t)))
	    (open-line 1))
	  (when org-footnote-tag-for-non-org-mode-files
	    (insert "\n" org-footnote-tag-for-non-org-mode-files "\n")))
785
	 ((and org-footnote-section (not export-props))
Bastien Guerry's avatar
Bastien Guerry committed
786 787 788
	  (when (and (cdr (assq 'heading org-blank-before-new-entry))
		     (zerop (save-excursion (org-back-over-empty-lines))))
	    (insert "\n"))
789
	  (insert "* " org-footnote-section "\n")))
Bastien Guerry's avatar
Bastien Guerry committed
790 791 792
	(set-marker ins-point nil)
	;; Insert the footnotes, separated by a blank line.
	(insert (mapconcat (lambda (x) (format "\n[%s] %s"
793
					  (nth (if sort-only 0 1) x) (nth 2 x)))
Bastien Guerry's avatar
Bastien Guerry committed
794 795
			   ref-table "\n"))
	(unless (eobp) (insert "\n"))
796 797 798 799 800 801 802 803 804 805
	;; When exporting, add newly inserted markers along with their
	;; associated definition to `org-export-footnotes-seen'.
	(when export-props
	  (setq org-export-footnotes-seen ref-table)))
       ;; Else, insert each definition at the end of the section
       ;; containing their first reference.  Happens only in Org files
       ;; with no special footnote section, and only when doing
       ;; sorting.
       (t (mapc 'org-insert-footnote-reference-near-definition
		ref-table))))))
806 807 808 809 810

(defun org-insert-footnote-reference-near-definition (entry)
  "Find first reference of footnote ENTRY and insert the definition there.
ENTRY is (fn-label num-mark definition)."
  (when (car entry)
811
    (goto-char (point-min))
812 813 814 815 816
    (let ((ref (org-footnote-get-next-reference (car entry))))
      (when ref
	(goto-char (nth 2 ref))
	(org-footnote-goto-local-insertion-point)
	(insert (format "\n[%s] %s\n" (car entry) (nth 2 entry)))))))
817 818 819

(defun org-footnote-goto-local-insertion-point ()
  "Find insertion point for footnote, just before next outline heading."
820
  (org-with-limited-levels (outline-next-heading))
821 822 823 824
  (or (bolp) (newline))
  (beginning-of-line 0)
  (while (and (not (bobp)) (= (char-after) ?#))
    (beginning-of-line 0))
825
  (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
826
  (end-of-line 1)
Carsten Dominik's avatar
Carsten Dominik committed
827 828
  (skip-chars-backward "\n\r\t ")
  (forward-line))
829

830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
(defun org-footnote-delete-references (label)
  "Delete every reference to footnote LABEL.
Return the number of footnotes removed."
  (save-excursion
    (goto-char (point-min))
    (let (ref (nref 0))
      (while (setq ref (org-footnote-get-next-reference label))
	(goto-char (nth 1 ref))
	(delete-region (nth 1 ref) (nth 2 ref))
	(incf nref))
      nref)))

(defun org-footnote-delete-definitions (label)
  "Delete every definition of the footnote LABEL.
Return the number of footnotes removed."
  (save-excursion
    (goto-char (point-min))
    (let ((def-re (concat "^\\[" (regexp-quote label) "\\]"))
	  (ndef 0))
      (while (re-search-forward def-re nil t)
	(let ((full-def (org-footnote-at-definition-p)))
	  (delete-region (nth 1 full-def) (nth 2 full-def)))
	(incf ndef))
      ndef)))

855 856 857
(defun org-footnote-delete (&optional label)
  "Delete the footnote at point.
This will remove the definition (even multiple definitions if they exist)
858 859 860
and all references of a footnote label.

If LABEL is non-nil, delete that footnote instead."
861
  (catch 'done
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
    (let* ((nref 0) (ndef 0) x
	   ;; 1. Determine LABEL of footnote at point.
	   (label (cond
		   ;; LABEL is provided as argument.
		   (label)
		   ;; Footnote reference at point. If the footnote is
		   ;; anonymous, delete it and exit instead.
		   ((setq x (org-footnote-at-reference-p))
		    (or (car x)
			(progn
			  (delete-region (nth 1 x) (nth 2 x))
			  (message "Anonymous footnote removed")
			  (throw 'done t))))
		   ;; Footnote definition at point.
		   ((setq x (org-footnote-at-definition-p))
		    (car x))
		   (t (error "Don't know which footnote to remove")))))
      ;; 2. Now that LABEL is non-nil, find every reference and every
      ;; definition, and delete them.
      (setq nref (org-footnote-delete-references label)
	    ndef (org-footnote-delete-definitions label))
      ;; 3. Verify consistency of footnotes and notify user.
884
      (org-footnote-auto-adjust-maybe)
885 886 887
      (message "%d definition(s) of and %d reference(s) of footnote %s removed"
	       ndef nref label))))

888 889 890
(defun org-footnote-renumber-fn:N ()
  "Renumber the simple footnotes like fn:17 into a sequence in the document."
  (interactive)
Bastien Guerry's avatar
Bastien Guerry committed
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
  (let (map (n 0))
    (org-with-wide-buffer
     (goto-char (point-min))
     (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
       (save-excursion
	 (goto-char (match-beginning 0))
	 ;; Ensure match is a footnote reference or definition.
	 (when (save-match-data (if (bolp)
				    (org-footnote-at-definition-p)
				  (org-footnote-at-reference-p)))
	   (let ((new-val (or (cdr (assoc (match-string 1) map))
			      (number-to-string (incf n)))))
	     (unless (assoc (match-string 1) map)
	       (push (cons (match-string 1) new-val) map))
	     (replace-match new-val nil nil nil 1))))))))
906 907 908 909 910 911

(defun org-footnote-auto-adjust-maybe ()
  "Renumber and/or sort footnotes according to user settings."
  (when (memq org-footnote-auto-adjust '(t renumber))
    (org-footnote-renumber-fn:N))
  (when (memq org-footnote-auto-adjust '(t sort))
912
    (let ((label (car (org-footnote-at-definition-p))))
913 914 915 916 917 918 919 920
      (org-footnote-normalize 'sort)
      (when label
	(goto-char (point-min))
	(and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
				nil t)
	     (progn (insert " ")
		    (just-one-space)))))))

921 922 923
(provide 'org-footnote)

;;; org-footnote.el ends here