HTML export: Fix bug with horizontal rules in plain lists.
[org-mode.git] / lisp / org-footnote.el
blob35caefea0891f719bd25550cb2061d331cc953f7
1 ;;; org-footnote.el --- Footnote support in Org and elsewhere
2 ;;
3 ;; Copyright (C) 2009 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: 6.28trans
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-regexp "org" (re &optional nlines visually))
42 (declare-function org-mark-ring-push "org" (&optional pos buffer))
43 (declare-function outline-next-heading "outline")
44 (declare-function org-trim "org" (s))
45 (declare-function org-show-context "org" (&optional key))
46 (declare-function org-back-to-heading "org" (&optional invisible-ok))
47 (declare-function org-end-of-subtree "org" (&optional invisible-ok to-heading))
48 (defvar org-odd-levels-only) ;; defined in org.el
50 (defconst org-footnote-re
51 (concat "[^][\n]" ; to make sure it is not at the beginning of a line
52 "\\["
53 "\\(?:"
54 "\\([0-9]+\\)"
55 "\\|"
56 (org-re "\\(fn:\\([-_[:word:]]+?\\)?\\)\\(?::\\([^\]]*?\\)\\)?")
57 "\\)"
58 "\\]")
59 "Regular expression for matching footnotes.")
61 (defconst org-footnote-definition-re
62 (org-re "^\\(\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]\\)")
63 "Regular expression matching the definition of a footnote.")
65 (defcustom org-footnote-section "Footnotes"
66 "Outline heading containing footnote definitions before export.
67 This can be nil, to place footnotes locally at the end of the current
68 outline node. If can also be the name of a special outline heading
69 under which footnotes should be put.
70 This variable defines the place where Org puts the definition
71 automatically, i.e. when creating the footnote, and when sorting the notes.
72 However, by hand you may place definitions *anywhere*.
73 If this is a string, during export, all subtrees starting with this
74 heading will be removed after extracting footnote definitions."
75 :group 'org-footnotes
76 :type '(choice
77 (string :tag "Collect fotnotes under heading")
78 (const :tag "Define footnotes locally" nil)))
80 (defcustom org-footnote-tag-for-non-org-mode-files "Footnotes:"
81 "Tag marking the beginning of footnote section.
82 The Org-mode footnote engine can be used in arbitrary text files as well
83 as in Org-mode. Outside Org-mode, new footnotes are always placed at
84 the end of the file. When you normalize the notes, any line containing
85 only this tag will be removed, a new one will be inserted at the end
86 of the file, followed by the collected and normalized footnotes."
87 :group 'org-footnotes
88 :type 'string)
90 (defcustom org-footnote-define-inline nil
91 "Non-nil means, define footnotes inline, at reference location.
92 When nil, footnotes will be defined in a special section near
93 the end of the document. When t, the [fn:label:definition] notation
94 will be used to define the footnote at the reference position."
95 :group 'org-footnote
96 :type 'boolean)
98 (defcustom org-footnote-auto-label t
99 "Non-nil means, define automatically new labels for footnotes.
100 Possible values are:
102 nil prompt the user for each label
103 t create unique labels of the form [fn:1], [fn:2], ...
104 confirm like t, but let the user edit the created value. In particular,
105 the label can be removed from the minibuffer, to create
106 an anonymous footnote.
107 plain Automatically create plain number labels like [1]"
108 :group 'org-footnote
109 :type '(choice
110 (const :tag "Frompt for label" nil)
111 (const :tag "Create automatic [fn:N]" t)
112 (const :tag "Offer automatic [fn:N] for editing" confirm)
113 (const :tag "Create automatic [N]" plain)))
115 (defcustom org-footnote-auto-adjust nil
116 "Non-nil means, automatically adjust footnotes after insert/delete.
117 When this is t, after each insertion or deletion of a footnote,
118 simple fn:N footnotes will be renumbered, and all footnotes will be sorted.
119 If you want to have just sorting or just renumbering, set this variable
120 to `sort' or `renumber'.
122 The main values of this variable can be set with in-buffer options:
124 #+STARTUP: fnadjust
125 #+STARTUP: nofnadjust"
126 :group 'org-footnote
127 :type '(choice
128 (const :tag "Renumber" renumber)
129 (const :tag "Sort" sort)
130 (const :tag "Renumber and Sort" t)))
132 (defcustom org-footnote-fill-after-inline-note-extraction nil
133 "Non-nil means, fill paragraphs after extracting footnotes.
134 When extracting inline footnotes, the lengths of lines can change a lot.
135 When this option is set, paragraphs from which an inline footnote has been
136 extracted will be filled again."
137 :group 'org-footnote
138 :type 'boolean)
140 (defun org-footnote-at-reference-p ()
141 "Is the cursor at a footnote reference?
142 If yes, return the beginning position, the label, and the definition, if local."
143 (when (org-in-regexp org-footnote-re 15)
144 (list (match-beginning 0)
145 (or (match-string 1)
146 (if (equal (match-string 2) "fn:") nil (match-string 2)))
147 (match-string 4))))
149 (defun org-footnote-at-definition-p ()
150 "Is the cursor at a footnote definition.
151 This matches only pure definitions like [1] or [fn:name] at the beginning
152 of a line. It does not a references like [fn:name:definition], where the
153 footnote text is included and defined locally.
154 The return value will be nil if not at a footnote definition, and a list
155 with start and label of the footnote if there is a definition at point."
156 (save-excursion
157 (end-of-line 1)
158 (let ((lim (save-excursion (re-search-backward "^\\*+ \\|^[ \t]*$" nil t))))
159 (when (re-search-backward org-footnote-definition-re lim t)
160 (list (match-beginning 0) (match-string 2))))))
162 (defun org-footnote-goto-definition (label)
163 "Find the definition of the footnote with label LABEL."
164 (interactive "sLabel: ")
165 (org-mark-ring-push)
166 (setq label (org-footnote-normalize-label label))
167 (let ((re (format "^\\[%s\\]\\|.\\[%s:" label label))
168 pos)
169 (save-excursion
170 (setq pos (or (re-search-forward re nil t)
171 (and (goto-char (point-min))
172 (re-search-forward re nil t))
173 (and (progn (widen) t)
174 (goto-char (point-min))
175 (re-search-forward re nil t)))))
176 (if (not pos)
177 (error "Cannot find definition of footnote %s" label)
178 (goto-char pos)
179 (org-show-context 'link-search)
180 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'."))))
182 (defun org-footnote-goto-next-reference (label)
183 "Find the definition of the footnote with label LABEL."
184 (interactive "sLabel: ")
185 (org-mark-ring-push)
186 (setq label (org-footnote-normalize-label label))
187 (let ((re (format ".\\[%s[]:]" label))
188 (p0 (point)) pos)
189 (save-excursion
190 (setq pos (or (re-search-forward re nil t)
191 (and (goto-char (point-min))
192 (re-search-forward re nil t))
193 (and (progn (widen) t)
194 (goto-char p0)
195 (re-search-forward re nil t))
196 (and (goto-char (point-min))
197 (re-search-forward re nil t)))))
198 (if pos
199 (progn
200 (goto-char pos)
201 (org-show-context 'link-search))
202 (error "Cannot find reference of footnote %s" label))))
204 (defun org-footnote-normalize-label (label)
205 (if (numberp label) (setq label (number-to-string label)))
206 (if (not (string-match "^[0-9]+$\\|^$\\|^fn:" label))
207 (setq label (concat "fn:" label)))
208 label)
210 (defun org-footnote-all-labels ()
211 "Return list with all defined foot labels used in the buffer."
212 (let (rtn l)
213 (save-excursion
214 (save-restriction
215 (widen)
216 (goto-char (point-min))
217 (while (re-search-forward org-footnote-definition-re nil t)
218 (setq l (org-match-string-no-properties 2))
219 (and l (add-to-list 'rtn l)))
220 (goto-char (point-min))
221 (while (re-search-forward org-footnote-re nil t)
222 (setq l (or (org-match-string-no-properties 1)
223 (org-match-string-no-properties 2)))
224 (and l (not (equal l "fn:")) (add-to-list 'rtn l)))))
225 rtn))
227 (defun org-footnote-unique-label (&optional current)
228 "Return a new unique footnote label.
229 The returns the firsts fn:N labels that is currently not used."
230 (unless current (setq current (org-footnote-all-labels)))
231 (let ((fmt (if (eq org-footnote-auto-label 'plain) "%d" "fn:%d"))
232 (cnt 1))
233 (while (member (format fmt cnt) current)
234 (incf cnt))
235 (format fmt cnt)))
237 (defvar org-footnote-label-history nil
238 "History of footnote labels entered in current buffer.")
239 (make-variable-buffer-local 'org-footnote-label-history)
241 (defun org-footnote-new ()
242 "Insert a new footnote.
243 This command prompts for a label. If this is a label referencing an
244 existing label, only insert the label. If the footnote label is empty
245 or new, let the user edit the definition of the footnote."
246 (interactive)
247 (let* ((labels (org-footnote-all-labels))
248 (propose (org-footnote-unique-label labels))
249 (label
250 (if (member org-footnote-auto-label '(t plain))
251 propose
252 (completing-read
253 "Label (leave empty for anonymous): "
254 (mapcar 'list labels) nil nil
255 (if (eq org-footnote-auto-label 'confirm) propose nil)
256 'org-footnote-label-history))))
257 (setq label (org-footnote-normalize-label label))
258 (cond
259 ((equal label "")
260 (insert "[fn:: ]")
261 (backward-char 1))
262 ((member label labels)
263 (insert "[" label "]")
264 (message "New reference to existing note"))
265 (org-footnote-define-inline
266 (insert "[" label ": ]")
267 (backward-char 1)
268 (org-footnote-auto-adjust-maybe))
270 (insert "[" label "]")
271 (org-footnote-create-definition label)
272 (org-footnote-auto-adjust-maybe)))))
274 (defun org-footnote-create-definition (label)
275 "Start the definition of a footnote with label LABEL."
276 (interactive "sLabel: ")
277 (setq label (org-footnote-normalize-label label))
278 (let (re)
279 (cond
280 ((org-mode-p)
281 (if (not org-footnote-section)
282 ;; No section, put footnote into the current outline node
284 ;; Try to find or make the special node
285 (setq re (concat "^\\*+[ \t]+" org-footnote-section "[ \t]*$"))
286 (unless (or (re-search-forward re nil t)
287 (and (progn (widen) t)
288 (re-search-forward re nil t)))
289 (goto-char (point-max))
290 (insert "\n\n* " org-footnote-section "\n")))
291 ;; Now go to the end of this entry and insert there.
292 (org-footnote-goto-local-insertion-point))
294 (setq re (concat "^" org-footnote-tag-for-non-org-mode-files "[ \t]*$"))
295 (unless (re-search-forward re nil t)
296 (goto-char (point-max))
297 (skip-chars-backward " \t\r\n")
298 (insert "\n\n")
299 (delete-region (point) (point-max))
300 (insert org-footnote-tag-for-non-org-mode-files "\n"))
301 (goto-char (point-max))
302 (skip-chars-backward " \t\r\n")))
303 (insert "\n\n")
304 (insert "[" label "] ")
305 (message "Edit definition and go back with `C-c &' or, if unique, with `C-c C-c'.")))
307 ;;;###autoload
308 (defun org-footnote-action (&optional special)
309 "Do the right thing for footnotes.
310 When at a footnote reference, jump to the definition. When at a definition,
311 jump to the refernces. When neither at definition or reference,
312 create a new footnote, interactively.
313 With prefix arg SPECIAL, offer additional commands in a menu."
314 (interactive "P")
315 (let (tmp c)
316 (cond
317 (special
318 (message "Footnotes: [s]ort | [r]enumber fn:N | [S]=r+s |->[n]umeric | [d]elete")
319 (setq c (read-char-exclusive))
320 (cond
321 ((equal c ?s)
322 (org-footnote-normalize 'sort))
323 ((equal c ?r)
324 (org-footnote-renumber-fn:N))
325 ((equal c ?S)
326 (org-footnote-renumber-fn:N)
327 (org-footnote-normalize 'sort))
328 ((equal c ?n)
329 (org-footnote-normalize))
330 ((equal c ?d)
331 (org-footnote-delete))
332 (t (error "No such footnote command %c" c))))
333 ((setq tmp (org-footnote-at-reference-p))
334 (if (nth 1 tmp)
335 (org-footnote-goto-definition (nth 1 tmp))
336 (goto-char (match-beginning 4))))
337 ((setq tmp (org-footnote-at-definition-p))
338 (org-footnote-goto-next-reference (nth 1 tmp)))
339 (t (org-footnote-new)))))
341 ;;;###autoload
342 (defun org-footnote-normalize (&optional sort-only for-preprocessor)
343 "Collect the footnotes in various formats and normalize them.
344 This finds the different sorts of footnotes allowed in Org, and
345 normalizes them to the usual [N] format that is understood by the
346 Org-mode exporters.
347 When SORT-ONLY is set, only sort the footnote definitions into the
348 referenced sequence."
349 ;; This is based on Paul's function, but rewritten.
350 (let* ((limit-level
351 (and (boundp 'org-inlinetask-min-level)
352 org-inlinetask-min-level
353 (1- org-inlinetask-min-level)))
354 (nstars (and limit-level
355 (if org-odd-levels-only
356 (and limit-level (1- (* limit-level 2)))
357 limit-level)))
358 (outline-regexp
359 (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))
360 (count 0)
361 ref def idef ref-table beg beg1 marker a before ins-point)
362 (save-excursion
363 ;; Now find footnote references, and extract the definitions
364 (goto-char (point-min))
365 (while (re-search-forward org-footnote-re nil t)
366 (org-if-unprotected
367 (setq def (match-string 4)
368 idef def
369 ref (or (match-string 1) (match-string 2))
370 before (char-to-string (char-after (match-beginning 0))))
371 (if (equal ref "fn:") (setq ref nil))
372 (if (and ref (setq a (assoc ref ref-table)))
373 (progn
374 (setq marker (nth 1 a))
375 (unless (nth 2 a) (setf (caddr a) def)))
376 (setq marker (number-to-string (incf count))))
377 (save-match-data
378 (if def
379 (setq def (org-trim def))
380 (save-excursion
381 (goto-char (point-min))
382 (if (not (re-search-forward (concat "^\\[" (regexp-quote ref)
383 "\\]") nil t))
384 (setq def nil)
385 (setq beg (match-beginning 0))
386 (setq beg1 (match-end 0))
387 (re-search-forward
388 (org-re "^[ \t]*$\\|^\\*+ \\|^\\[\\([0-9]+\\|fn:[-_[:word:]]+\\)\\]")
389 nil 'move)
390 (setq def (buffer-substring beg1 (or (match-beginning 0)
391 (point-max))))
392 (goto-char beg)
393 (skip-chars-backward " \t\n\t")
394 (delete-region (1+ (point)) (match-beginning 0))))))
395 (unless sort-only
396 (replace-match (concat before "[" marker "]"))
397 (and idef
398 org-footnote-fill-after-inline-note-extraction
399 (fill-paragraph)))
400 (if (not a) (push (list ref marker def (if idef t nil)) ref-table))))
402 ;; First find and remove the footnote section
403 (goto-char (point-min))
404 (cond
405 ((org-mode-p)
406 (if (and org-footnote-section
407 (re-search-forward
408 (concat "^\\*[ \t]+" (regexp-quote org-footnote-section)
409 "[ \t]*$")
410 nil t))
411 (if (or for-preprocessor (not org-footnote-section))
412 (replace-match "")
413 (org-back-to-heading t)
414 (forward-line 1)
415 (setq ins-point (point))
416 (delete-region (point) (org-end-of-subtree t)))
417 (goto-char (point-max))
418 (unless for-preprocessor
419 (when org-footnote-section
420 (or (bolp) (insert "\n"))
421 (insert "* " org-footnote-section "\n")
422 (setq ins-point (point))))))
424 (if (re-search-forward
425 (concat "^"
426 (regexp-quote org-footnote-tag-for-non-org-mode-files)
427 "[ \t]*$")
428 nil t)
429 (replace-match ""))
430 (goto-char (point-max))
431 (skip-chars-backward " \t\n\r")
432 (delete-region (point) (point-max))
433 (insert "\n\n" org-footnote-tag-for-non-org-mode-files "\n")
434 (setq ins-point (point))))
436 ;; Insert the footnotes again
437 (goto-char (or ins-point (point-max)))
438 (setq ref-table (reverse ref-table))
439 (when sort-only
440 ;; remove anonymous and inline footnotes from the list
441 (setq ref-table
442 (delq nil (mapcar
443 (lambda (x) (and (car x)
444 (not (equal (car x) "fn:"))
445 (not (nth 3 x))
447 ref-table))))
448 ;; Make sure each footnote has a description, or an error message.
449 (setq ref-table
450 (mapcar
451 (lambda (x)
452 (if (not (nth 2 x))
453 (setcar (cddr x)
454 (format "FOOTNOTE DEFINITION NOT FOUND: %s" (car x)))
455 (setcar (cddr x) (org-trim (nth 2 x))))
457 ref-table))
459 (if (or (not (org-mode-p)) ; not an Org file
460 org-footnote-section ; we do not use a footnote section
461 (not sort-only) ; this is normalization
462 for-preprocessor) ; the is the preprocessor
463 ;; Insert the footnotes together in one place
464 (progn
465 (setq def
466 (mapconcat
467 (lambda (x)
468 (format "[%s] %s" (nth (if sort-only 0 1) x)
469 (org-trim (nth 2 x))))
470 ref-table "\n\n"))
471 (if ref-table (insert "\n" def "\n\n")))
472 ;; Insert each footnote near the first reference
473 ;; Happens only in Org files with no special footnote section,
474 ;; and only when doing sorting
475 (mapc 'org-insert-footnote-reference-near-definition
476 ref-table)))))
478 (defun org-insert-footnote-reference-near-definition (entry)
479 "Find first reference of footnote ENTRY and insert the definition there.
480 ENTRY is (fn-label num-mark definition)."
481 (when (car entry)
482 (goto-char (point-min))
483 (when (re-search-forward (format ".\\[%s[]:]" (regexp-quote (car entry)))
484 nil t)
485 (org-footnote-goto-local-insertion-point)
486 (insert (format "\n\n[%s] %s" (car entry) (nth 2 entry))))))
488 (defun org-footnote-goto-local-insertion-point ()
489 "Find insertion point for footnote, just before next outline heading."
490 (org-with-limited-levels (outline-next-heading))
491 (or (bolp) (newline))
492 (beginning-of-line 0)
493 (while (and (not (bobp)) (= (char-after) ?#))
494 (beginning-of-line 0))
495 (if (looking-at "[ \t]*#\\+TBLFM:") (beginning-of-line 2))
496 (end-of-line 1)
497 (skip-chars-backward "\n\r\t "))
499 (defun org-footnote-delete (&optional label)
500 "Delete the footnote at point.
501 This will remove the definition (even multiple definitions if they exist)
502 and all references of a footnote label."
503 (catch 'done
504 (let (x label l beg def-re (nref 0) (ndef 0))
505 (unless label
506 (when (setq x (org-footnote-at-reference-p))
507 (setq label (nth 1 x))
508 (when (or (not label) (equal "fn:" label))
509 (delete-region (1+ (match-beginning 0)) (match-end 0))
510 (message "Anonymous footnote removed")
511 (throw 'done t)))
512 (when (and (not label) (setq x (org-footnote-at-definition-p)))
513 (setq label (nth 1 x)))
514 (unless label (error "Don't know which footnote to remove")))
515 (save-excursion
516 (save-restriction
517 (goto-char (point-min))
518 (while (re-search-forward org-footnote-re nil t)
519 (setq l (or (match-string 1) (match-string 2)))
520 (when (equal l label)
521 (delete-region (1+ (match-beginning 0)) (match-end 0))
522 (incf nref)))
523 (goto-char (point-min))
524 (setq def-re (concat "^\\[" (regexp-quote label) "\\]"))
525 (while (re-search-forward def-re nil t)
526 (setq beg (match-beginning 0))
527 (if (re-search-forward "^\\[\\|^[ \t]*$\\|^\\*+ " nil t)
528 (goto-char (match-beginning 0))
529 (goto-char (point-max)))
530 (delete-region beg (point))
531 (incf ndef))))
532 (org-footnote-auto-adjust-maybe)
533 (message "%d definition(s) of and %d reference(s) of footnote %s removed"
534 ndef nref label))))
536 (defun org-footnote-renumber-fn:N ()
537 "Renumber the simple footnotes like fn:17 into a sequence in the document."
538 (interactive)
539 (let (map i (n 0))
540 (save-excursion
541 (save-restriction
542 (widen)
543 (goto-char (point-min))
544 (while (re-search-forward "\\[fn:\\([0-9]+\\)[]:]" nil t)
545 (setq i (string-to-number (match-string 1)))
546 (when (and (string-match "\\S-" (buffer-substring
547 (point-at-bol) (match-beginning 0)))
548 (not (assq i map)))
549 (push (cons i (number-to-string (incf n))) map)))
550 (goto-char (point-min))
551 (while (re-search-forward "\\(\\[fn:\\)\\([0-9]+\\)\\([]:]\\)" nil t)
552 (replace-match (concat "\\1" (cdr (assq (string-to-number (match-string 2)) map)) "\\3")))))))
554 (defun org-footnote-auto-adjust-maybe ()
555 "Renumber and/or sort footnotes according to user settings."
556 (when (memq org-footnote-auto-adjust '(t renumber))
557 (org-footnote-renumber-fn:N))
558 (when (memq org-footnote-auto-adjust '(t sort))
559 (let ((label (nth 1 (org-footnote-at-definition-p))))
560 (org-footnote-normalize 'sort)
561 (when label
562 (goto-char (point-min))
563 (and (re-search-forward (concat "^\\[" (regexp-quote label) "\\]")
564 nil t)
565 (progn (insert " ")
566 (just-one-space)))))))
568 (provide 'org-footnote)
570 ;; arch-tag: 1b5954df-fb5d-4da5-8709-78d944dbfc37
572 ;;; org-footnote.el ends here