* lisp/mail/footnote.el: Use lexical-binding
[emacs.git] / lisp / mail / footnote.el
blob2448211a238118d222d8f36a6f4d317a7dc1237c
1 ;;; footnote.el --- footnote support for message mode -*- lexical-binding:t -*-
3 ;; Copyright (C) 1997, 2000-2017 Free Software Foundation, Inc.
5 ;; Author: Steven L Baur <steve@xemacs.org> (1997-)
6 ;; Boruch Baum <boruch_baum@gmx.com> (2017-)
7 ;; Keywords: mail, news
8 ;; Version: 0.19
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 <https://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; This file provides footnote[1] support for message-mode in emacsen.
28 ;; footnote-mode is implemented as a minor mode.
30 ;; [1] Footnotes look something like this. Along with some decorative
31 ;; stuff.
33 ;;;; TODO:
34 ;; + Reasonable Undo support.
35 ;; - could use an `apply' entry in the buffer-undo-list to be warned when
36 ;; a footnote we inserted is removed via undo.
37 ;; - should try to handle the more general problem of deleting/removing
38 ;; footnotes via standard editing commands rather than via footnote
39 ;; commands.
40 ;; + more language styles.
41 ;; + The key sequence 'C-c ! a C-y C-c ! b' should auto-fill the
42 ;; footnote in adaptive fill mode. This does not seem to be a bug in
43 ;; `adaptive-fill' because it behaves that way on all point movements
44 ;; + Handle footmode mode elegantly in all modes, even if that means refuses to
45 ;; accept the burden. For example, in a programming language mode, footnotes
46 ;; should be commented.
47 ;; + Manually autofilling the a first footnote should not cause it to
48 ;; wrap into the footnote section tag
49 ;; + Current solution adds a second newline after the section tag, so it is
50 ;; clearly a separate paragraph. There may be stylistic objections to this.
51 ;; + Footnotes with multiple paragraphs should not have their first
52 ;; line out-dented.
53 ;; + Upon leaving footnote area, perform an auto-fill on an entire
54 ;; footnote (including multiple paragraphs), or on entire footnote area.
55 ;; + fill-paragraph takes arg REGION, but seemingly only when called
56 ;; interactively.
57 ;; + At some point, it became necessary to change `footnote-section-tag-regexp'
58 ;; to remove its trailing space. (Adaptive fill side-effect?)
59 ;; + useful for lazy testing
60 ;; (setq footnote-narrow-to-footnotes-when-editing t)
61 ;; (setq footnote-section-tag "Footnotes: ")
62 ;; (setq footnote-section-tag-regexp "Footnotes\\(\\[.\\]\\)?:")
64 ;;; Code:
66 (eval-when-compile (require 'cl-lib))
67 (defvar filladapt-token-table)
69 (defgroup footnote nil
70 "Support for footnotes in mail and news messages."
71 :version "21.1"
72 :group 'message)
74 (defcustom footnote-mode-line-string " FN"
75 "String to display in modes section of the mode-line."
76 :type 'string
77 :group 'footnote)
79 (defcustom footnote-mode-hook nil
80 "Hook functions run when footnote-mode is activated."
81 :type 'hook
82 :group 'footnote)
84 (defcustom footnote-narrow-to-footnotes-when-editing nil
85 "If non-nil, narrow to footnote text body while editing a footnote."
86 :type 'boolean
87 :group 'footnote)
89 (defcustom footnote-prompt-before-deletion t
90 "If non-nil, prompt before deleting a footnote.
91 There is currently no way to undo deletions."
92 :type 'boolean
93 :group 'footnote)
95 (defcustom footnote-spaced-footnotes t
96 "If non-nil, insert an empty line between footnotes.
97 Customizing this variable has no effect on buffers already
98 displaying footnotes."
99 :type 'boolean
100 :group 'footnote)
102 (defcustom footnote-use-message-mode t ; Nowhere used.
103 "If non-nil, assume Footnoting will be done in `message-mode'."
104 :type 'boolean
105 :group 'footnote)
107 (defcustom footnote-body-tag-spacing 2
108 "Number of spaces separating a footnote body tag and its text.
109 Customizing this variable has no effect on buffers already
110 displaying footnotes."
111 :type 'integer
112 :group 'footnote)
114 (defcustom footnote-prefix [(control ?c) ?!]
115 "Prefix key to use for Footnote command in Footnote minor mode.
116 The value of this variable is checked as part of loading Footnote mode.
117 After that, changing the prefix key requires manipulating keymaps."
118 :type 'key-sequence
119 :group 'footnote)
121 ;;; Interface variables that probably shouldn't be changed
123 (defcustom footnote-section-tag "Footnotes:"
124 "Tag inserted at beginning of footnote section.
125 If you set this to the empty string, no tag is inserted and the
126 value of `footnote-section-tag-regexp' is ignored. Customizing
127 this variable has no effect on buffers already displaying
128 footnotes."
129 :version "27.1"
130 :type 'string
131 :group 'footnote)
133 (defcustom footnote-section-tag-regexp
134 ;; Even if `footnote-section-tag' has a trailing space, let's not require it
135 ;; here, since it might be trimmed by various commands.
136 "Footnotes\\(\\[.\\]\\)?:"
137 "Regexp which indicates the start of a footnote section.
138 This variable is disregarded when `footnote-section-tag' is the
139 empty string. Customizing this variable has no effect on buffers
140 already displaying footnotes."
141 :version "27.1"
142 :type 'regexp
143 :group 'footnote)
145 ;; The following three should be consumed by footnote styles.
146 (defcustom footnote-start-tag "["
147 "String used to denote start of numbered footnote.
148 Should not be set to the empty string. Customizing this variable
149 has no effect on buffers already displaying footnotes."
150 :type 'string
151 :group 'footnote)
153 (defcustom footnote-end-tag "]"
154 "String used to denote end of numbered footnote.
155 Should not be set to the empty string. Customizing this variable
156 has no effect on buffers already displaying footnotes."
157 :type 'string
158 :group 'footnote)
160 (defcustom footnote-signature-separator
161 (if (boundp 'message-signature-separator)
162 message-signature-separator
163 "^-- $")
164 "Regexp used by Footnote mode to recognize signatures."
165 :type 'regexp
166 :group 'footnote)
168 (defcustom footnote-align-to-fn-text t
169 "How to left-align footnote text.
170 If nil, footnote text is to be aligned flush left with left side
171 of the footnote number. If non-nil, footnote text is to be aligned
172 left with the first character of footnote text."
173 :type 'boolean)
175 ;;; Private variables
177 (defvar footnote-style-number nil
178 "Footnote style represented as an index into footnote-style-alist.")
179 (make-variable-buffer-local 'footnote-style-number)
181 (defvar footnote-text-marker-alist nil
182 "List of markers pointing to text of footnotes in message buffer.")
183 (make-variable-buffer-local 'footnote-text-marker-alist)
185 (defvar footnote-pointer-marker-alist nil
186 "List of markers pointing to footnote pointers in message buffer.")
187 (make-variable-buffer-local 'footnote-pointer-marker-alist)
189 (defvar footnote-mouse-highlight 'highlight
190 "Text property name to enable mouse over highlight.")
192 (defvar footnote-mode)
194 ;;; Default styles
195 ;;; NUMERIC
196 (defconst footnote-numeric-regexp "[0-9]+"
197 "Regexp for digits.")
199 (defun footnote--numeric (n)
200 "Numeric footnote style.
201 Use Arabic numerals for footnoting."
202 (int-to-string n))
204 ;;; ENGLISH UPPER
205 (defconst footnote-english-upper "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
206 "Upper case English alphabet.")
208 (defconst footnote-english-upper-regexp "[A-Z]+"
209 "Regexp for upper case English alphabet.")
211 (defun footnote--english-upper (n)
212 "Upper case English footnoting.
213 Wrapping around the alphabet implies successive repetitions of letters."
214 (let* ((ltr (mod (1- n) (length footnote-english-upper)))
215 (rep (/ (1- n) (length footnote-english-upper)))
216 (chr (char-to-string (aref footnote-english-upper ltr)))
218 (while (>= rep 0)
219 (setq rc (concat rc chr))
220 (setq rep (1- rep)))
221 rc))
223 ;;; ENGLISH LOWER
224 (defconst footnote-english-lower "abcdefghijklmnopqrstuvwxyz"
225 "Lower case English alphabet.")
227 (defconst footnote-english-lower-regexp "[a-z]+"
228 "Regexp of lower case English alphabet.")
230 (defun footnote--english-lower (n)
231 "Lower case English footnoting.
232 Wrapping around the alphabet implies successive repetitions of letters."
233 (let* ((ltr (mod (1- n) (length footnote-english-lower)))
234 (rep (/ (1- n) (length footnote-english-lower)))
235 (chr (char-to-string (aref footnote-english-lower ltr)))
237 (while (>= rep 0)
238 (setq rc (concat rc chr))
239 (setq rep (1- rep)))
240 rc))
242 ;;; ROMAN LOWER
243 (defconst footnote-roman-lower-list
244 '((1 . "i") (5 . "v") (10 . "x")
245 (50 . "l") (100 . "c") (500 . "d") (1000 . "m"))
246 "List of roman numerals with their values.")
248 (defconst footnote-roman-lower-regexp "[ivxlcdm]+"
249 "Regexp of roman numerals.")
251 (defun footnote--roman-lower (n)
252 "Generic Roman number footnoting."
253 (footnote--roman-common n footnote-roman-lower-list))
255 ;;; ROMAN UPPER
256 (defconst footnote-roman-upper-list
257 '((1 . "I") (5 . "V") (10 . "X")
258 (50 . "L") (100 . "C") (500 . "D") (1000 . "M"))
259 "List of roman numerals with their values.")
261 (defconst footnote-roman-upper-regexp "[IVXLCDM]+"
262 "Regexp of roman numerals. Not complete")
264 (defun footnote--roman-upper (n)
265 "Generic Roman number footnoting."
266 (footnote--roman-common n footnote-roman-upper-list))
268 (defun footnote--roman-common (n footnote-roman-list)
269 "Lower case Roman footnoting."
270 (let* ((our-list footnote-roman-list)
271 (rom-lngth (length our-list))
272 (rom-high 0)
273 (rom-low 0)
274 (rom-div -1)
275 (count-high 0)
276 (count-low 0))
277 ;; find surrounding numbers
278 (while (and (<= count-high (1- rom-lngth))
279 (>= n (car (nth count-high our-list))))
280 ;; (message "Checking %d" (car (nth count-high our-list)))
281 (setq count-high (1+ count-high)))
282 (setq rom-high count-high)
283 (setq rom-low (1- count-high))
284 ;; find the appropriate divisor (if it exists)
285 (while (and (= rom-div -1)
286 (< count-low rom-high))
287 (when (or (> n (- (car (nth rom-high our-list))
288 (/ (car (nth count-low our-list))
289 2)))
290 (= n (- (car (nth rom-high our-list))
291 (car (nth count-low our-list)))))
292 (setq rom-div count-low))
293 ;; (message "Checking %d and %d in div loop" rom-high count-low)
294 (setq count-low (1+ count-low)))
295 ;;(message "We now have high: %d, low: %d, div: %d, n: %d"
296 ;; rom-high rom-low (if rom-div rom-div -1) n)
297 (let ((rom-low-pair (nth rom-low our-list))
298 (rom-high-pair (nth rom-high our-list))
299 (rom-div-pair (if (not (= rom-div -1)) (nth rom-div our-list) nil)))
300 ;; (message "pairs are: rom-low: %S, rom-high: %S, rom-div: %S"
301 ;; rom-low-pair rom-high-pair rom-div-pair)
302 (cond
303 ((< n 0) (error "footnote--roman-common called with n < 0"))
304 ((= n 0) "")
305 ((= n (car rom-low-pair)) (cdr rom-low-pair))
306 ((= n (car rom-high-pair)) (cdr rom-high-pair))
307 ((= (car rom-low-pair) (car rom-high-pair))
308 (concat (cdr rom-low-pair)
309 (footnote--roman-common
310 (- n (car rom-low-pair))
311 footnote-roman-list)))
312 ((>= rom-div 0) (concat (cdr rom-div-pair) (cdr rom-high-pair)
313 (footnote--roman-common
314 (- n (- (car rom-high-pair)
315 (car rom-div-pair)))
316 footnote-roman-list)))
317 (t (concat (cdr rom-low-pair)
318 (footnote--roman-common
319 (- n (car rom-low-pair))
320 footnote-roman-list)))))))
322 ;; Latin-1
324 (defconst footnote-latin-string "¹²³ºª§¶"
325 "String of Latin-1 footnoting characters.")
327 ;; Note not [...]+, because this style cycles.
328 (defconst footnote-latin-regexp (concat "[" footnote-latin-string "]")
329 "Regexp for Latin-1 footnoting characters.")
331 (defun footnote--latin (n)
332 "Latin-1 footnote style.
333 Use a range of Latin-1 non-ASCII characters for footnoting."
334 (string (aref footnote-latin-string
335 (mod (1- n) (length footnote-latin-string)))))
337 ;; Unicode
339 (defconst footnote-unicode-string "⁰¹²³⁴⁵⁶⁷⁸⁹"
340 "String of Unicode footnoting characters.")
342 (defconst footnote-unicode-regexp (concat "[" footnote-unicode-string "]+")
343 "Regexp for Unicode footnoting characters.")
345 (defun footnote--unicode (n)
346 "Unicode footnote style.
347 Use Unicode characters for footnoting."
348 (let (modulus result done)
349 (while (not done)
350 (setq modulus (mod n 10)
351 n (truncate n 10))
352 (and (zerop n) (setq done t))
353 (push (aref footnote-unicode-string modulus) result))
354 (apply #'string result)))
356 ;; Hebrew
358 (defconst footnote-hebrew-numeric-regex "[אבגדהוזחטיכלמנסעפצקרשת']+")
359 ; (defconst footnote-hebrew-numeric-regex "\\([אבגדהוזחט]'\\)?\\(ת\\)?\\(ת\\)?\\([קרשת]\\)?\\([טיכלמנסעפצ]\\)?\\([אבגדהוזחט]\\)?")
361 (defconst footnote-hebrew-numeric
363 ("א" "ב" "ג" "ד" "ה" "ו" "ז" "ח" "ט")
364 ("י" "כ" "ל" "מ" "נ" "ס" "ע" "פ" "צ")
365 ("ק" "ר" "ש" "ת" "תק" "תר"" תש" "תת" "תתק")))
367 (defun footnote--hebrew-numeric (n)
368 "Supports 9999 footnotes, then rolls over."
369 (let* ((n (+ (mod n 10000) (/ n 10000)))
370 (thousands (/ n 1000))
371 (hundreds (/ (mod n 1000) 100))
372 (tens (/ (mod n 100) 10))
373 (units (mod n 10))
374 (special (if (not (= tens 1)) nil
375 (or (when (= units 5) "טו")
376 (when (= units 6) "טז")))))
377 (concat
378 (when (/= 0 thousands)
379 (concat (nth (1- thousands) (nth 0 footnote-hebrew-numeric)) "'"))
380 (when (/= 0 hundreds)
381 (nth (1- hundreds) (nth 2 footnote-hebrew-numeric)))
382 (if special special
383 (concat
384 (when (/= 0 tens) (nth (1- tens) (nth 1 footnote-hebrew-numeric)))
385 (when (/= 0 units) (nth (1- units) (nth 0 footnote-hebrew-numeric))))))))
387 (defconst footnote-hebrew-symbolic-regex "[אבגדהוזחטיכלמנסעפצקרשת]")
389 (defconst footnote-hebrew-symbolic
391 "א" "ב" "ג" "ד" "ה" "ו" "ז" "ח" "ט" "י" "כ" "ל" "מ" "נ" "ס" "ע" "פ" "צ" "ק" "ר" "ש" "ת"))
393 (defun footnote--hebrew-symbolic (n)
394 "Only 22 elements, per the style of eg. 'פירוש שפתי חכמים על רש״י'.
395 Proceeds from `י' to `כ', from `צ' to `ק'. After `ת', rolls over to `א'."
396 (nth (mod (1- n) 22) footnote-hebrew-symbolic))
398 ;;; list of all footnote styles
399 (defvar footnote-style-alist
400 `((numeric footnote--numeric ,footnote-numeric-regexp)
401 (english-lower footnote--english-lower ,footnote-english-lower-regexp)
402 (english-upper footnote--english-upper ,footnote-english-upper-regexp)
403 (roman-lower footnote--roman-lower ,footnote-roman-lower-regexp)
404 (roman-upper footnote--roman-upper ,footnote-roman-upper-regexp)
405 (latin footnote--latin ,footnote-latin-regexp)
406 (unicode footnote--unicode ,footnote-unicode-regexp)
407 (hebrew-numeric footnote--hebrew-numeric ,footnote-hebrew-numeric-regex)
408 (hebrew-symbolic footnote--hebrew-symbolic ,footnote-hebrew-symbolic-regex))
409 "Styles of footnote tags available.
410 By default, Arabic numbers, English letters, Roman Numerals,
411 Latin and Unicode superscript characters, and Hebrew numerals
412 are available.")
414 (defcustom footnote-style 'numeric
415 "Default style used for footnoting.
416 numeric == 1, 2, 3, ...
417 english-lower == a, b, c, ...
418 english-upper == A, B, C, ...
419 roman-lower == i, ii, iii, iv, v, ...
420 roman-upper == I, II, III, IV, V, ...
421 latin == ¹ ² ³ º ª § ¶
422 unicode == ¹, ², ³, ...
423 hebrew-numeric == א, ב, ..., יא, ..., תקא...
424 hebrew-symbolic == א, ב, ..., י, כ, ..., צ, ק, ..., ת, א
425 See also variables `footnote-start-tag' and `footnote-end-tag'.
427 Note: some characters in the unicode style may not show up
428 properly if the default font does not contain those characters.
430 Customizing this variable has no effect on buffers already
431 displaying footnotes. To change the style of footnotes in such a
432 buffer use the command `footnote-set-style'."
433 :type (cons 'choice (mapcar (lambda (x) (list 'const (car x)))
434 footnote-style-alist))
435 :group 'footnote)
437 ;;; Style utilities & functions
438 (defun footnote--style-p (style)
439 "Return non-nil if style is a valid style known to `footnote-mode'."
440 (assq style footnote-style-alist))
442 (defun footnote--index-to-string (index)
443 "Convert a binary index into a string to display as a footnote.
444 Conversion is done based upon the current selected style."
445 (let ((alist (if (footnote--style-p footnote-style)
446 (assq footnote-style footnote-style-alist)
447 (nth 0 footnote-style-alist))))
448 (funcall (nth 1 alist) index)))
450 (defun footnote--current-regexp ()
451 "Return the regexp of the index of the current style."
452 (concat (nth 2 (or (assq footnote-style footnote-style-alist)
453 (nth 0 footnote-style-alist)))
454 "*"))
456 (defun footnote--refresh-footnotes (&optional index-regexp)
457 "Redraw all footnotes.
458 You must call this or arrange to have this called after changing footnote
459 styles."
460 (unless index-regexp
461 (setq index-regexp (footnote--current-regexp)))
462 (save-excursion
463 ;; Take care of the pointers first
464 (let ((i 0) locn alist)
465 (while (setq alist (nth i footnote-pointer-marker-alist))
466 (setq locn (cdr alist))
467 (while locn
468 (goto-char (car locn))
469 ;; Try to handle the case where `footnote-start-tag' and
470 ;; `footnote-end-tag' are the same string.
471 (when (looking-back (concat
472 (regexp-quote footnote-start-tag)
473 "\\(" index-regexp "+\\)"
474 (regexp-quote footnote-end-tag))
475 (line-beginning-position))
476 (replace-match
477 (propertize
478 (concat
479 footnote-start-tag
480 (footnote--index-to-string (1+ i))
481 footnote-end-tag)
482 'footnote-number (1+ i) footnote-mouse-highlight t)
483 nil "\\1"))
484 (setq locn (cdr locn)))
485 (setq i (1+ i))))
487 ;; Now take care of the text section
488 (let ((i 0) alist)
489 (while (setq alist (nth i footnote-text-marker-alist))
490 (goto-char (cdr alist))
491 (when (looking-at (concat
492 (regexp-quote footnote-start-tag)
493 "\\(" index-regexp "+\\)"
494 (regexp-quote footnote-end-tag)))
495 (replace-match
496 (propertize
497 (concat
498 footnote-start-tag
499 (footnote--index-to-string (1+ i))
500 footnote-end-tag)
501 'footnote-number (1+ i))
502 nil "\\1"))
503 (setq i (1+ i))))))
505 (defun footnote--assoc-index (key alist)
506 "Give index of key in alist."
507 (let ((i 0) (max (length alist)) rc)
508 (while (and (null rc)
509 (< i max))
510 (when (eq key (car (nth i alist)))
511 (setq rc i))
512 (setq i (1+ i)))
513 rc))
515 (defun footnote-cycle-style ()
516 "Select next defined footnote style."
517 (interactive)
518 (let ((old (footnote--assoc-index footnote-style footnote-style-alist))
519 (max (length footnote-style-alist))
520 idx)
521 (setq idx (1+ old))
522 (when (>= idx max)
523 (setq idx 0))
524 (setq footnote-style (car (nth idx footnote-style-alist)))
525 (footnote--refresh-footnotes (nth 2 (nth old footnote-style-alist)))))
527 (defun footnote-set-style (&optional style)
528 "Select a specific style."
529 (interactive
530 (list (intern (completing-read
531 "Footnote Style: "
532 obarray #'footnote--style-p 'require-match))))
533 (let ((old (footnote--assoc-index footnote-style footnote-style-alist)))
534 (setq footnote-style style)
535 (footnote--refresh-footnotes (nth 2 (nth old footnote-style-alist)))))
537 ;; Internal functions
538 (defun footnote--insert-numbered-footnote (arg &optional mousable)
539 "Insert numbered footnote at (point)."
540 (let ((string (concat footnote-start-tag
541 (footnote--index-to-string arg)
542 footnote-end-tag)))
543 (insert-before-markers
544 (if mousable
545 (propertize
546 string 'footnote-number arg footnote-mouse-highlight t)
547 (propertize string 'footnote-number arg)))))
549 (defun footnote--renumber (_from to pointer-alist text-alist)
550 "Renumber a single footnote."
551 (let* ((posn-list (cdr pointer-alist)))
552 (setcar pointer-alist to)
553 (setcar text-alist to)
554 (while posn-list
555 (goto-char (car posn-list))
556 (when (looking-back (concat (regexp-quote footnote-start-tag)
557 (footnote--current-regexp)
558 (regexp-quote footnote-end-tag))
559 (line-beginning-position))
560 (replace-match
561 (propertize
562 (concat footnote-start-tag
563 (footnote--index-to-string to)
564 footnote-end-tag)
565 'footnote-number to footnote-mouse-highlight t)))
566 (setq posn-list (cdr posn-list)))
567 (goto-char (cdr text-alist))
568 (when (looking-at (concat (regexp-quote footnote-start-tag)
569 (footnote--current-regexp)
570 (regexp-quote footnote-end-tag)))
571 (replace-match
572 (propertize
573 (concat footnote-start-tag
574 (footnote--index-to-string to)
575 footnote-end-tag)
576 'footnote-number to)))))
578 (defun footnote--narrow-to-footnotes ()
579 "Restrict text in buffer to show only text of footnotes."
580 (interactive) ; testing
581 (narrow-to-region (footnote--get-area-point-min)
582 (footnote--get-area-point-max)))
584 (defun footnote--goto-char-point-max ()
585 "Move to end of buffer or prior to start of .signature."
586 (goto-char (point-max))
587 (or (re-search-backward footnote-signature-separator nil t)
588 (point)))
590 (defun footnote--insert-text-marker (arg locn)
591 "Insert a marker pointing to footnote ARG, at buffer location LOCN."
592 (let ((marker (make-marker)))
593 (unless (assq arg footnote-text-marker-alist)
594 (set-marker marker locn)
595 (setq footnote-text-marker-alist
596 (cons (cons arg marker) footnote-text-marker-alist))
597 (setq footnote-text-marker-alist
598 (footnote--sort footnote-text-marker-alist)))))
600 (defun footnote--insert-pointer-marker (arg locn)
601 "Insert a marker pointing to footnote ARG, at buffer location LOCN."
602 (let ((marker (make-marker))
603 alist)
604 (set-marker marker locn)
605 (if (setq alist (assq arg footnote-pointer-marker-alist))
606 (setf alist
607 (cons marker (cdr alist)))
608 (setq footnote-pointer-marker-alist
609 (cons (cons arg (list marker)) footnote-pointer-marker-alist))
610 (setq footnote-pointer-marker-alist
611 (footnote--sort footnote-pointer-marker-alist)))))
613 (defun footnote--insert-footnote (arg)
614 "Insert a footnote numbered ARG, at (point)."
615 (push-mark)
616 (footnote--insert-pointer-marker arg (point))
617 (footnote--insert-numbered-footnote arg t)
618 (footnote--goto-char-point-max)
619 (if (cond
620 ((not (string-equal footnote-section-tag ""))
621 (re-search-backward (concat "^" footnote-section-tag-regexp) nil t))
622 (footnote-text-marker-alist
623 (goto-char (cdar footnote-text-marker-alist))))
624 (save-restriction
625 (when footnote-narrow-to-footnotes-when-editing
626 (footnote--narrow-to-footnotes))
627 (footnote-goto-footnote (1- arg)) ; evil, FIXME (less evil now)
628 ;; (message "Inserting footnote %d" arg)
629 (unless
630 (or (eq arg 1)
631 (when (re-search-forward
632 (if footnote-spaced-footnotes
633 "\n\n"
634 (concat "\n"
635 (regexp-quote footnote-start-tag)
636 (footnote--current-regexp)
637 (regexp-quote footnote-end-tag)))
638 nil t)
639 (unless (beginning-of-line) t))
640 (footnote--goto-char-point-max)
641 (cond
642 ((not (string-equal footnote-section-tag ""))
643 (re-search-backward
644 (concat "^" footnote-section-tag-regexp) nil t))
645 (footnote-text-marker-alist
646 (goto-char (cdar footnote-text-marker-alist)))))))
647 (unless (looking-at "^$")
648 (insert "\n"))
649 (when (eobp)
650 (insert "\n"))
651 (unless (string-equal footnote-section-tag "")
652 (insert footnote-section-tag "\n")))
653 (let ((old-point (point)))
654 (footnote--insert-numbered-footnote arg nil)
655 (footnote--insert-text-marker arg old-point)))
657 (defun footnote--sort (list)
658 (sort list (lambda (e1 e2)
659 (< (car e1) (car e2)))))
661 (defun footnote--text-under-cursor ()
662 "Return the number of the current footnote if in footnote text.
663 Return nil if the cursor is not positioned over the text of
664 a footnote."
665 (when (and footnote-text-marker-alist
666 (<= (footnote--get-area-point-min)
667 (point)
668 (footnote--get-area-point-max)))
669 (let ((i 1) alist-txt result)
670 (while (and (setq alist-txt (nth i footnote-text-marker-alist))
671 (null result))
672 (when (< (point) (cdr alist-txt))
673 (setq result (car (nth (1- i) footnote-text-marker-alist))))
674 (setq i (1+ i)))
675 (when (and (null result) (null alist-txt))
676 (setq result (car (nth (1- i) footnote-text-marker-alist))))
677 result)))
679 (defun footnote--under-cursor ()
680 "Return the number of the footnote underneath the cursor.
681 Return nil if the cursor is not over a footnote."
682 (or (get-text-property (point) 'footnote-number)
683 (footnote--text-under-cursor)))
685 (defun footnote--calc-fn-alignment-column ()
686 "Calculate the left alignment for footnote text."
687 ;; FIXME: Maybe it would be better to go to the footnote's beginning and
688 ;; see at which column it starts.
689 (+ footnote-body-tag-spacing
690 (string-width
691 (concat footnote-start-tag footnote-end-tag
692 (footnote--index-to-string
693 (caar (last footnote-text-marker-alist)))))))
695 (defun footnote--fill-prefix-string ()
696 "Return the fill prefix to be used by footnote mode."
697 ;; TODO: Prefix to this value other prefix strings, such as those
698 ;; designating a comment line, a message response, or a boxquote.
699 (make-string (footnote--calc-fn-alignment-column) ?\s))
701 (defun footnote--point-in-body-p ()
702 "Return non-nil if point is in the buffer text area,
703 i.e. before the beginning of the footnote area."
704 (< (point) (footnote--get-area-point-min)))
706 (defun footnote--get-area-point-min (&optional before-tag)
707 "Return start of the first footnote.
708 If there is no footnote area, returns `point-max'.
709 With optional arg BEFORE-TAG, return position of the `footnote-section-tag'
710 instead, if applicable."
711 (cond
712 ;; FIXME: Shouldn't we use `footnote--get-area-point-max' instead?
713 ((not footnote-text-marker-alist) (point-max))
714 ((not before-tag) (cdr (car footnote-text-marker-alist)))
715 ((string-equal footnote-section-tag "")
716 (cdr (car footnote-text-marker-alist)))
718 (save-excursion
719 (goto-char (cdr (car footnote-text-marker-alist)))
720 (if (re-search-backward (concat "^" footnote-section-tag-regexp) nil t)
721 (match-beginning 0)
722 (message "Footnote section tag not found!")
723 ;; This `else' should never happen, and indicates an error,
724 ;; ie. footnotes already exist and a footnote-section-tag is defined,
725 ;; but the section tag hasn't been found. We choose to assume that the
726 ;; user deleted it intentionally and wants us to behave in this buffer
727 ;; as if the section tag was set "", so we do that, now.
728 ;;(setq footnote-section-tag "")
730 ;; HOWEVER: The rest of footnote mode does not currently honor or
731 ;; account for this.
733 ;; To illustrate the difference in behavior, create a few footnotes,
734 ;; delete the section tag, and create another footnote. Then undo,
735 ;; comment the above line (that sets the tag to ""), re-evaluate this
736 ;; function, and repeat.
738 ;; TODO: integrate sanity checks at reasonable operational points.
739 (cdr (car footnote-text-marker-alist)))))))
741 (defun footnote--get-area-point-max ()
742 "Return the end of footnote area.
743 This is either `point-max' or the start of a `.signature' string, as
744 defined by variable `footnote-signature-separator'. If there is no
745 footnote area, returns `point-max'."
746 (save-excursion (footnote--goto-char-point-max)))
748 (defun footnote--adaptive-fill-function (orig-fun)
750 (and
751 footnote-mode
752 footnote-align-to-fn-text
753 (footnote--text-under-cursor)
754 ;; (not (footnote--point-in-body-p))
755 ;; (< (point) (footnote--signature-area-start-point))
756 (footnote--fill-prefix-string))
757 ;; If not within a footnote's text, fallback to the default.
758 (funcall orig-fun)))
760 ;;; User functions
762 (defun footnote--make-hole ()
763 (save-excursion
764 (let ((i 0)
765 (notes (length footnote-pointer-marker-alist))
766 alist-ptr alist-txt rc)
767 (while (< i notes)
768 (setq alist-ptr (nth i footnote-pointer-marker-alist))
769 (setq alist-txt (nth i footnote-text-marker-alist))
770 (when (< (point) (- (cadr alist-ptr) 3))
771 (unless rc
772 (setq rc (car alist-ptr)))
773 (save-excursion
774 (message "Renumbering from %s to %s"
775 (footnote--index-to-string (car alist-ptr))
776 (footnote--index-to-string
777 (1+ (car alist-ptr))))
778 (footnote--renumber (car alist-ptr)
779 (1+ (car alist-ptr))
780 alist-ptr
781 alist-txt)))
782 (setq i (1+ i)))
783 rc)))
785 (defun footnote-add-footnote ()
786 "Add a numbered footnote.
787 The number the footnote receives is dependent upon the relative location
788 of any other previously existing footnotes.
789 If the variable `footnote-narrow-to-footnotes-when-editing' is set,
790 the buffer is narrowed to the footnote body. The restriction is removed
791 by using `footnote-back-to-message'."
792 (interactive "*")
793 (let ((num
794 (if footnote-text-marker-alist
795 (if (< (point) (cl-cadar (last footnote-pointer-marker-alist)))
796 (footnote--make-hole)
797 (1+ (caar (last footnote-text-marker-alist))))
798 1)))
799 (message "Adding footnote %d" num)
800 (footnote--insert-footnote num)
801 (insert-before-markers (make-string footnote-body-tag-spacing ? ))
802 (let ((opoint (point)))
803 (save-excursion
804 (insert-before-markers
805 (if footnote-spaced-footnotes
806 "\n\n"
807 "\n"))
808 (when footnote-narrow-to-footnotes-when-editing
809 (footnote--narrow-to-footnotes)))
810 ;; Emacs/XEmacs bug? save-excursion doesn't restore point when using
811 ;; insert-before-markers.
812 (goto-char opoint))))
814 (defun footnote-delete-footnote (&optional arg)
815 "Delete a numbered footnote.
816 With no parameter, delete the footnote under (point). With ARG specified,
817 delete the footnote with that number."
818 (interactive "*P")
819 (unless arg
820 (setq arg (footnote--under-cursor)))
821 (when (and arg
822 (or (not footnote-prompt-before-deletion)
823 (y-or-n-p (format "Really delete footnote %d?" arg))))
824 (let (alist-ptr alist-txt locn)
825 (setq alist-ptr (assq arg footnote-pointer-marker-alist))
826 (setq alist-txt (assq arg footnote-text-marker-alist))
827 (unless (and alist-ptr alist-txt)
828 (error "Can't delete footnote %d" arg))
829 (setq locn (cdr alist-ptr))
830 (while (car locn)
831 (save-excursion
832 (goto-char (car locn))
833 (when (looking-back (concat (regexp-quote footnote-start-tag)
834 (footnote--current-regexp)
835 (regexp-quote footnote-end-tag))
836 (line-beginning-position))
837 (delete-region (match-beginning 0) (match-end 0))))
838 (setq locn (cdr locn)))
839 (save-excursion
840 (goto-char (cdr alist-txt))
841 (delete-region
842 (point)
843 (if footnote-spaced-footnotes
844 (search-forward "\n\n" nil t)
845 (save-restriction ; <= 2017-12 Boruch: WHY?? I see no narrowing / widening here.
846 (end-of-line)
847 (next-single-char-property-change
848 (point) 'footnote-number nil (footnote--goto-char-point-max))))))
849 (setq footnote-pointer-marker-alist
850 (delq alist-ptr footnote-pointer-marker-alist))
851 (setq footnote-text-marker-alist
852 (delq alist-txt footnote-text-marker-alist))
853 (footnote-renumber-footnotes)
854 (when (and (null footnote-text-marker-alist)
855 (null footnote-pointer-marker-alist))
856 (save-excursion
857 (if (not (string-equal footnote-section-tag ""))
858 (let* ((end (footnote--goto-char-point-max))
859 (start (1- (re-search-backward
860 (concat "^" footnote-section-tag-regexp)
861 nil t))))
862 (forward-line -1)
863 (when (looking-at "\n")
864 (kill-line))
865 (delete-region start (if (< end (point-max))
867 (point-max))))
868 (footnote--goto-char-point-max)
869 (when (looking-back "\n\n" (- (point) 2))
870 (kill-line -1))))))))
872 (defun footnote-renumber-footnotes ()
873 "Renumber footnotes, starting from 1."
874 (interactive "*")
875 (save-excursion
876 (let ((i 0)
877 (notes (length footnote-pointer-marker-alist))
878 alist-ptr alist-txt)
879 (while (< i notes)
880 (setq alist-ptr (nth i footnote-pointer-marker-alist))
881 (setq alist-txt (nth i footnote-text-marker-alist))
882 (unless (= (1+ i) (car alist-ptr))
883 (footnote--renumber (car alist-ptr) (1+ i) alist-ptr alist-txt))
884 (setq i (1+ i))))))
886 (defun footnote-goto-footnote (&optional arg)
887 "Jump to the text of a footnote.
888 With no parameter, jump to the text of the footnote under (point). With ARG
889 specified, jump to the text of that footnote."
890 (interactive "P")
891 (unless arg
892 (setq arg (footnote--under-cursor)))
893 (let ((footnote (assq arg footnote-text-marker-alist)))
894 (cond
895 (footnote
896 (goto-char (cdr footnote)))
897 ((eq arg 0)
898 (goto-char (point-max))
899 (cond
900 ((not (string-equal footnote-section-tag ""))
901 (re-search-backward (concat "^" footnote-section-tag-regexp))
902 (forward-line 1))
903 (footnote-text-marker-alist
904 (goto-char (cdar footnote-text-marker-alist)))))
906 (error "I don't see a footnote here")))))
908 (defun footnote-back-to-message ()
909 "Move cursor back to footnote referent.
910 If the cursor is not over the text of a footnote, point is not changed.
911 If the buffer was narrowed due to `footnote-narrow-to-footnotes-when-editing'
912 being set it is automatically widened."
913 (interactive)
914 (let ((note (footnote--text-under-cursor)))
915 (when note
916 (when footnote-narrow-to-footnotes-when-editing
917 (widen))
918 (goto-char (cadr (assq note footnote-pointer-marker-alist))))))
920 (defvar footnote-mode-map
921 (let ((map (make-sparse-keymap)))
922 (define-key map "a" 'footnote-add-footnote)
923 (define-key map "b" 'footnote-back-to-message)
924 (define-key map "c" 'footnote-cycle-style)
925 (define-key map "d" 'footnote-delete-footnote)
926 (define-key map "g" 'footnote-goto-footnote)
927 (define-key map "r" 'footnote-renumber-footnotes)
928 (define-key map "s" 'footnote-set-style)
929 map))
931 (defvar footnote-minor-mode-map
932 (let ((map (make-sparse-keymap)))
933 (define-key map footnote-prefix footnote-mode-map)
934 map)
935 "Keymap used for binding footnote minor mode.")
937 ;;;###autoload
938 (define-minor-mode footnote-mode
939 "Toggle Footnote mode.
940 With a prefix argument ARG, enable Footnote mode if ARG is
941 positive, and disable it otherwise. If called from Lisp, enable
942 the mode if ARG is omitted or nil.
944 Footnote mode is a buffer-local minor mode. If enabled, it
945 provides footnote support for `message-mode'. To get started,
946 play around with the following keys:
947 \\{footnote-minor-mode-map}"
948 :lighter footnote-mode-line-string
949 :keymap footnote-minor-mode-map
950 ;; (filladapt-mode t)
951 (unless adaptive-fill-function
952 ;; nil and `ignore' have the same semantics for adaptive-fill-function,
953 ;; but only `ignore' behaves correctly with add/remove-function.
954 (setq adaptive-fill-function #'ignore))
955 (remove-function (local 'adaptive-fill-function)
956 #'footnote--adaptive-fill-function)
957 (when footnote-mode
958 ;; (footnote-setup-keybindings)
959 (make-local-variable 'footnote-style)
960 (make-local-variable 'footnote-body-tag-spacing)
961 (make-local-variable 'footnote-spaced-footnotes)
962 (make-local-variable 'footnote-section-tag)
963 (make-local-variable 'footnote-section-tag-regexp)
964 (make-local-variable 'footnote-start-tag)
965 (make-local-variable 'footnote-end-tag)
966 (make-local-variable 'adaptive-fill-function)
967 (add-function :around (local 'adaptive-fill-function)
968 #'footnote--adaptive-fill-function)
970 ;; filladapt is an XEmacs package which AFAIK has never been ported
971 ;; to Emacs.
972 (when (boundp 'filladapt-token-table)
973 ;; add tokens to filladapt to match footnotes
974 ;; 1] xxxxxxxxxxx x x x or [1] x x x x x x x
975 ;; xxx x xx xxx xxxx x x x xxxxxxxxxx
976 (let ((bullet-regexp (concat (regexp-quote footnote-start-tag)
977 "?[0-9a-zA-Z]+"
978 (regexp-quote footnote-end-tag)
979 "[ \t]")))
980 (unless (assoc bullet-regexp filladapt-token-table)
981 (setq filladapt-token-table
982 (append filladapt-token-table
983 (list (list bullet-regexp 'bullet)))))))))
985 (provide 'footnote)
987 ;;; footnote.el ends here