Synch with Gnus.
[elisp/gnus.git-] / lisp / gnus-cite.el
1 ;;; gnus-cite.el --- parse citations in articles for Gnus
2 ;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Per Abhiddenware; you can redistribute it and/or modify
6 ;; it under the terms of the GNU General Public License as published by
7 ;; the Free Software Foundation; either version 2, or (at your option)
8 ;; any later version.
9
10 ;; GNU Emacs is distributed in the hope that it will be useful,
11 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 ;; GNU General Public License for more details.
14
15 ;; You should have received a copy of the GNU General Public License
16 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
17 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 ;; Boston, MA 02111-1307, USA.
19
20 ;;; Commentary:
21
22 ;;; Code:
23
24 (eval-when-compile (require 'cl))
25
26 (require 'gnus)
27 (require 'gnus-art)
28 (require 'gnus-range)
29
30 (eval-when-compile (require 'static))
31
32 ;;; Customization:
33
34 (defgroup gnus-cite nil
35   "Citation."
36   :prefix "gnus-cite-"
37   :link '(custom-manual "(gnus)Article Highlighting")
38   :group 'gnus-article)
39
40 (defcustom gnus-cite-reply-regexp
41   "^\\(Subject: Re\\|In-Reply-To\\|References\\):"
42   "*If headers match this regexp it is reasonable to believe that
43 article has citations."
44   :group 'gnus-cite
45   :type 'string)
46
47 (defcustom gnus-cite-always-check nil
48   "Check article always for citations.  Set it t to check all articles."
49   :group 'gnus-cite
50   :type '(choice (const :tag "no" nil)
51                  (const :tag "yes" t)))
52
53 (defcustom gnus-cited-opened-text-button-line-format "%(%{[-]%}%)\n"
54   "Format of opened cited text buttons."
55   :group 'gnus-cite
56   :type 'string)
57
58 (defcustom gnus-cited-closed-text-button-line-format "%(%{[+]%}%)\n"
59   "Format of closed cited text buttons."
60   :group 'gnus-cite
61   :type 'string)
62
63 (defcustom gnus-cited-lines-visible nil
64   "The number of lines of hidden cited text to remain visible.
65 Or a pair (cons) of numbers which are the number of lines at the top
66 and bottom of the text, respectively, to remain visible."
67   :group 'gnus-cite
68   :type '(choice (const :tag "none" nil)
69                  integer
70                  (cons :tag "Top and Bottom" integer integer)))
71
72 (defcustom gnus-cite-parse-max-size 25000
73   "Maximum article size (in bytes) where parsing citations is allowed.
74 Set it to nil to parse all articles."
75   :group 'gnus-cite
76   :type '(choice (const :tag "all" nil)
77                  integer))
78
79 (defcustom gnus-cite-prefix-regexp
80   "^[]>»|:}+ ]*[]>»|:}+]\\(.*>»\\)?\\|^.*>"
81   "*Regexp matching the longest possible citation prefix on a line."
82   :group 'gnus-cite
83   :type 'regexp)
84
85 (defcustom gnus-cite-max-prefix 20
86   "Maximum possible length for a citation prefix."
87   :group 'gnus-cite
88   :type 'integer)
89
90 (defcustom gnus-supercite-regexp
91   (concat "^\\(" gnus-cite-prefix-regexp "\\)? *"
92           ">>>>> +\"\\([^\"\n]+\\)\" +==")
93   "*Regexp matching normal Supercite attribution lines.
94 The first grouping must match prefixes added by other packages."
95   :group 'gnus-cite
96   :type 'regexp)
97
98 (defcustom gnus-supercite-secondary-regexp "^.*\"\\([^\"\n]+\\)\" +=="
99   "Regexp matching mangled Supercite attribution lines.
100 The first regexp group should match the Supercite attribution."
101   :group 'gnus-cite
102   :type 'regexp)
103
104 (defcustom gnus-cite-minimum-match-count 2
105   "Minimum number of identical prefixes before we believe it's a citation."
106   :group 'gnus-cite
107   :type 'integer)
108
109 (defcustom gnus-cite-attribution-prefix
110   "In article\\|in <\\|On \\(Mon\\|Tue\\|Wed\\|Thu\\|Fri\\|Sat\\|Sun\\),\\|-----Original Message-----"
111   "*Regexp matching the beginning of an attribution line."
112   :group 'gnus-cite
113   :type 'regexp)
114
115 (defcustom gnus-cite-attribution-suffix
116   "\\(\\(wrote\\|writes\\|said\\|says\\|>\\)\\(:\\|\\.\\.\\.\\)\\|-----Original Message-----\\)[ \t]*$"
117   "*Regexp matching the end of an attribution line.
118 The text matching the first grouping will be used as a button."
119   :group 'gnus-cite
120   :type 'regexp)
121
122 (defface gnus-cite-attribution-face '((t
123                                        (:italic t)))
124   "Face used for attribution lines.")
125
126 (defcustom gnus-cite-attribution-face 'gnus-cite-attribution-face
127   "Face used for attribution lines.
128 It is merged with the face for the cited text belonging to the attribution."
129   :group 'gnus-cite
130   :type 'face)
131
132 (defface gnus-cite-face-1 '((((class color)
133                               (background dark))
134                              (:foreground "light blue"))
135                             (((class color)
136                               (background light))
137                              (:foreground "MidnightBlue"))
138                             (t
139                              (:italic t)))
140   "Citation face.")
141
142 (defface gnus-cite-face-2 '((((class color)
143                               (background dark))
144                              (:foreground "light cyan"))
145                             (((class color)
146                               (background light))
147                              (:foreground "firebrick"))
148                             (t
149                              (:italic t)))
150   "Citation face.")
151
152 (defface gnus-cite-face-3 '((((class color)
153                               (background dark))
154                              (:foreground "light yellow"))
155                             (((class color)
156                               (background light))
157                              (:foreground "dark green"))
158                             (t
159                              (:italic t)))
160   "Citation face.")
161
162 (defface gnus-cite-face-4 '((((class color)
163                               (background dark))
164                              (:foreground "light pink"))
165                             (((class color)
166                               (background light))
167                              (:foreground "OrangeRed"))
168                             (t
169                              (:italic t)))
170   "Citation face.")
171
172 (defface gnus-cite-face-5 '((((class color)
173                               (background dark))
174                              (:foreground "pale green"))
175                             (((class color)
176                               (background light))
177                              (:foreground "dark khaki"))
178                             (t
179                              (:italic t)))
180   "Citation face.")
181
182 (defface gnus-cite-face-6 '((((class color)
183                               (background dark))
184                              (:foreground "beige"))
185                             (((class color)
186                               (background light))
187                              (:foreground "dark violet"))
188                             (t
189                              (:italic t)))
190   "Citation face.")
191
192 (defface gnus-cite-face-7 '((((class color)
193                               (background dark))
194                              (:foreground "orange"))
195                             (((class color)
196                               (background light))
197                              (:foreground "SteelBlue4"))
198                             (t
199                              (:italic t)))
200   "Citation face.")
201
202 (defface gnus-cite-face-8 '((((class color)
203                               (background dark))
204                              (:foreground "magenta"))
205                             (((class color)
206                               (background light))
207                              (:foreground "magenta"))
208                             (t
209                              (:italic t)))
210   "Citation face.")
211
212 (defface gnus-cite-face-9 '((((class color)
213                               (background dark))
214                              (:foreground "violet"))
215                             (((class color)
216                               (background light))
217                              (:foreground "violet"))
218                             (t
219                              (:italic t)))
220   "Citation face.")
221
222 (defface gnus-cite-face-10 '((((class color)
223                                (background dark))
224                               (:foreground "medium purple"))
225                              (((class color)
226                                (background light))
227                               (:foreground "medium purple"))
228                              (t
229                               (:italic t)))
230   "Citation face.")
231
232 (defface gnus-cite-face-11 '((((class color)
233                                (background dark))
234                               (:foreground "turquoise"))
235                              (((class color)
236                                (background light))
237                               (:foreground "turquoise"))
238                              (t
239                               (:italic t)))
240   "Citation face.")
241
242 (defcustom gnus-cite-face-list
243   '(gnus-cite-face-1 gnus-cite-face-2 gnus-cite-face-3 gnus-cite-face-4
244                      gnus-cite-face-5 gnus-cite-face-6 gnus-cite-face-7 gnus-cite-face-8
245                      gnus-cite-face-9 gnus-cite-face-10 gnus-cite-face-11)
246   "*List of faces used for highlighting citations.
247
248 When there are citations from multiple articles in the same message,
249 Gnus will try to give each citation from each article its own face.
250 This should make it easier to see who wrote what."
251   :group 'gnus-cite
252   :type '(repeat face))
253
254 (defcustom gnus-cite-hide-percentage 50
255   "Only hide excess citation if above this percentage of the body."
256   :group 'gnus-cite
257   :type 'number)
258
259 (defcustom gnus-cite-hide-absolute 10
260   "Only hide excess citation if above this number of lines in the body."
261   :group 'gnus-cite
262   :type 'integer)
263
264 ;;; Internal Variables:
265
266 (defvar gnus-cite-article nil)
267 (defvar gnus-cite-overlay-list nil)
268
269 (defvar gnus-cite-prefix-alist nil)
270 ;; Alist of citation prefixes.
271 ;; The cdr is a list of lines with that prefix.
272
273 (defvar gnus-cite-attribution-alist nil)
274 ;; Alist of attribution lines.
275 ;; The car is a line number.
276 ;; The cdr is the prefix for the citation started by that line.
277
278 (defvar gnus-cite-loose-prefix-alist nil)
279 ;; Alist of citation prefixes that have no matching attribution.
280 ;; The cdr is a list of lines with that prefix.
281
282 (defvar gnus-cite-loose-attribution-alist nil)
283 ;; Alist of attribution lines that have no matching citation.
284 ;; Each member has the form (WROTE IN PREFIX TAG), where
285 ;; WROTE: is the attribution line number
286 ;; IN: is the line number of the previous line if part of the same attribution,
287 ;; PREFIX: Is the citation prefix of the attribution line(s), and
288 ;; TAG: Is a Supercite tag, if any.
289
290 (defvar gnus-cited-opened-text-button-line-format-alist
291   `((?b (marker-position beg) ?d)
292     (?e (marker-position end) ?d)
293     (?n (count-lines beg end) ?d)
294     (?l (- end beg) ?d)))
295 (defvar gnus-cited-opened-text-button-line-format-spec nil)
296 (defvar gnus-cited-closed-text-button-line-format-alist
297   gnus-cited-opened-text-button-line-format-alist)
298 (defvar gnus-cited-closed-text-button-line-format-spec nil)
299
300
301 ;;; Commands:
302
303 (defun gnus-article-highlight-citation (&optional force)
304   "Highlight cited text.
305 Each citation in the article will be highlighted with a different face.
306 The faces are taken from `gnus-cite-face-list'.
307 Attribution lines are highlighted with the same face as the
308 corresponding citation merged with `gnus-cite-attribution-face'.
309
310 Text is considered cited if at least `gnus-cite-minimum-match-count'
311 lines matches `gnus-cite-prefix-regexp' with the same prefix.
312
313 Lines matching `gnus-cite-attribution-suffix' and perhaps
314 `gnus-cite-attribution-prefix' are considered attribution lines."
315   (interactive (list 'force))
316   (save-excursion
317     (set-buffer gnus-article-buffer)
318     (gnus-cite-parse-maybe force)
319     (let ((buffer-read-only nil)
320           (alist gnus-cite-prefix-alist)
321           (faces gnus-cite-face-list)
322           (inhibit-point-motion-hooks t)
323           face entry prefix skip numbers number face-alist)
324       ;; Loop through citation prefixes.
325       (while alist
326         (setq entry (car alist)
327               alist (cdr alist)
328               prefix (car entry)
329               numbers (cdr entry)
330               face (car faces)
331               faces (or (cdr faces) gnus-cite-face-list)
332               face-alist (cons (cons prefix face) face-alist))
333         (while numbers
334           (setq number (car numbers)
335                 numbers (cdr numbers))
336           (and (not (assq number gnus-cite-attribution-alist))
337                (not (assq number gnus-cite-loose-attribution-alist))
338                (gnus-cite-add-face number prefix face))))
339       ;; Loop through attribution lines.
340       (setq alist gnus-cite-attribution-alist)
341       (while alist
342         (setq entry (car alist)
343               alist (cdr alist)
344               number (car entry)
345               prefix (cdr entry)
346               skip (gnus-cite-find-prefix number)
347               face (cdr (assoc prefix face-alist)))
348         ;; Add attribution button.
349         (goto-char (point-min))
350         (forward-line (1- number))
351         (when (re-search-forward gnus-cite-attribution-suffix
352                                  (save-excursion (end-of-line 1) (point))
353                                  t)
354           (gnus-article-add-button (match-beginning 1) (match-end 1)
355                                    'gnus-cite-toggle prefix))
356         ;; Highlight attribution line.
357         (gnus-cite-add-face number skip face)
358         (gnus-cite-add-face number skip gnus-cite-attribution-face))
359       ;; Loop through attribution lines.
360       (setq alist gnus-cite-loose-attribution-alist)
361       (while alist
362         (setq entry (car alist)
363               alist (cdr alist)
364               number (car entry)
365               skip (gnus-cite-find-prefix number))
366         (gnus-cite-add-face number skip gnus-cite-attribution-face)))))
367
368 (defun gnus-dissect-cited-text ()
369   "Dissect the article buffer looking for cited text."
370   (save-excursion
371     (set-buffer gnus-article-buffer)
372     (gnus-cite-parse-maybe nil t)
373     (let ((alist gnus-cite-prefix-alist)
374           prefix numbers number marks m)
375       ;; Loop through citation prefixes.
376       (while alist
377         (setq numbers (pop alist)
378               prefix (pop numbers))
379         (while numbers
380           (setq number (pop numbers))
381           (goto-char (point-min))
382           (forward-line number)
383           (push (cons (point-marker) "") marks)
384           (while (and numbers
385                       (= (1- number) (car numbers)))
386             (setq number (pop numbers)))
387           (goto-char (point-min))
388           (forward-line (1- number))
389           (push (cons (point-marker) prefix) marks)))
390       ;; Skip to the beginning of the body.
391       (article-goto-body)
392       (push (cons (point-marker) "") marks)
393       ;; Find the end of the body.
394       (goto-char (point-max))
395       (gnus-article-search-signature)
396       (push (cons (point-marker) "") marks)
397       ;; Sort the marks.
398       (setq marks (sort marks 'car-less-than-car))
399       (let ((omarks marks))
400         (setq marks nil)
401         (while (cdr omarks)
402           (if (= (caar omarks) (caadr omarks))
403               (progn
404                 (unless (equal (cdar omarks) "")
405                   (push (car omarks) marks))
406                 (unless (equal (cdadr omarks) "")
407                   (push (cadr omarks) marks))
408                 (unless (and (equal (cdar omarks) "")
409                              (equal (cdadr omarks) "")
410                              (not (cddr omarks)))
411                   (setq omarks (cdr omarks))))
412             (push (car omarks) marks))
413           (setq omarks (cdr omarks)))
414         (when (car omarks)
415           (push (car omarks) marks))
416         (setq marks (setq m (nreverse marks)))
417         (while (cddr m)
418           (if (and (equal (cdadr m) "")
419                    (equal (cdar m) (cdaddr m))
420                    (goto-char (caadr m))
421                    (forward-line 1)
422                    (= (point) (caaddr m)))
423               (setcdr m (cdddr m))
424             (setq m (cdr m))))
425         marks))))
426
427 (defun gnus-article-fill-cited-article (&optional force width)
428   "Do word wrapping in the current article.
429 If WIDTH (the numerical prefix), use that text width when filling."
430   (interactive (list t current-prefix-arg))
431   (save-excursion
432     (set-buffer gnus-article-buffer)
433     (let ((buffer-read-only nil)
434           (inhibit-point-motion-hooks t)
435           (marks (gnus-dissect-cited-text))
436           (adaptive-fill-mode nil)
437           (filladapt-mode nil)
438           (fill-column (if width (prefix-numeric-value width) fill-column)))
439       (save-restriction
440         (while (cdr marks)
441           (narrow-to-region (caar marks) (caadr marks))
442           (let ((adaptive-fill-regexp
443                  (concat "^" (regexp-quote (cdar marks)) " *"))
444                 (fill-prefix (cdar marks)))
445             (fill-region (point-min) (point-max)))
446           (set-marker (caar marks) nil)
447           (setq marks (cdr marks)))
448         (when marks
449           (set-marker (caar marks) nil))
450         ;; All this information is now incorrect.
451         (setq gnus-cite-prefix-alist nil
452               gnus-cite-attribution-alist nil
453               gnus-cite-loose-prefix-alist nil
454               gnus-cite-loose-attribution-alist nil
455               gnus-cite-article nil)))))
456
457 (defun gnus-article-hide-citation (&optional arg force)
458   "Toggle hiding of all cited text except attribution lines.
459 See the documentation for `gnus-article-highlight-citation'.
460 If given a negative prefix, always show; if given a positive prefix,
461 always hide."
462   (interactive (append (gnus-article-hidden-arg) (list 'force)))
463   (gnus-set-format 'cited-opened-text-button t)
464   (gnus-set-format 'cited-closed-text-button t)
465   (save-excursion
466     (set-buffer gnus-article-buffer)
467     (cond
468      ((gnus-article-check-hidden-text 'cite arg)
469       t)
470      ((gnus-article-text-type-exists-p 'cite)
471       (let ((buffer-read-only nil))
472         (gnus-article-hide-text-of-type 'cite)))
473      (t
474       (let ((buffer-read-only nil)
475             (marks (gnus-dissect-cited-text))
476             (inhibit-point-motion-hooks t)
477             (props (nconc (list 'article-type 'cite)
478                           gnus-hidden-properties))
479             beg end start)
480         (while marks
481           (setq beg nil
482                 end nil)
483           (while (and marks (string= (cdar marks) ""))
484             (setq marks (cdr marks)))
485           (when marks
486             (setq beg (caar marks)))
487           (while (and marks (not (string= (cdar marks) "")))
488             (setq marks (cdr marks)))
489           (when marks
490             (setq end (caar marks)))
491           ;; Skip past lines we want to leave visible.
492           (when (and beg end gnus-cited-lines-visible)
493             (goto-char beg)
494             (forward-line (if (consp gnus-cited-lines-visible)
495                               (car gnus-cited-lines-visible)
496                             gnus-cited-lines-visible))
497             (if (>= (point) end)
498                 (setq beg nil)
499               (setq beg (point-marker))
500               (when (consp gnus-cited-lines-visible)
501                 (goto-char end)
502                 (forward-line (- (cdr gnus-cited-lines-visible)))
503                 (if (<= (point) beg)
504                     (setq beg nil)
505                   (setq end (point-marker))))))
506           (when (and beg end)
507             ;; We use markers for the end-points to facilitate later
508             ;; wrapping and mangling of text.
509             (setq beg (set-marker (make-marker) beg)
510                   end (set-marker (make-marker) end))
511             (gnus-add-text-properties beg end props)
512             (goto-char beg)
513             (unless (save-excursion (search-backward "\n\n" nil t))
514               (insert "\n"))
515             (put-text-property
516              (setq start (point-marker))
517              (progn
518                (gnus-article-add-button
519                 (point)
520                 (progn (eval gnus-cited-closed-text-button-line-format-spec)
521                        (point))
522                 `gnus-article-toggle-cited-text
523                 (list (cons beg end) start))
524                (point))
525              'article-type 'annotation)
526             (set-marker beg (point)))))))))
527
528 (defun gnus-article-toggle-cited-text (args)
529   "Toggle hiding the text in REGION."
530   (let* ((region (car args))
531          (beg (car region))
532          (end (cdr region))
533          (start (cadr args))
534          (hidden
535           (text-property-any
536            beg (1- end)
537            (car gnus-hidden-properties) (cadr gnus-hidden-properties)))
538          (inhibit-point-motion-hooks t)
539          buffer-read-only)
540     (funcall
541      (if hidden
542          'remove-text-properties 'gnus-add-text-properties)
543      beg end gnus-hidden-properties)
544     (save-excursion
545       (goto-char start)
546       (gnus-delete-line)
547       (put-text-property
548        (point)
549        (progn
550          (gnus-article-add-button
551           (point)
552           (progn (eval
553                   (if hidden
554                       gnus-cited-opened-text-button-line-format-spec
555                     gnus-cited-closed-text-button-line-format-spec))
556                  (point))
557           `gnus-article-toggle-cited-text
558           args)
559          (point))
560        'article-type 'annotation))))
561
562 (defun gnus-article-hide-citation-maybe (&optional arg force)
563   "Toggle hiding of cited text that has an attribution line.
564 If given a negative prefix, always show; if given a positive prefix,
565 always hide.
566 This will do nothing unless at least `gnus-cite-hide-percentage'
567 percent and at least `gnus-cite-hide-absolute' lines of the body is
568 cited text with attributions.  When called interactively, these two
569 variables are ignored.
570 See also the documentation for `gnus-article-highlight-citation'."
571   (interactive (append (gnus-article-hidden-arg) '(force)))
572   (unless (gnus-article-check-hidden-text 'cite arg)
573     (save-excursion
574       (set-buffer gnus-article-buffer)
575       (gnus-cite-parse-maybe force)
576       (article-goto-body)
577       (let ((start (point))
578             (atts gnus-cite-attribution-alist)
579             (buffer-read-only nil)
580             (inhibit-point-motion-hooks t)
581             (hidden 0)
582             total)
583         (goto-char (point-max))
584         (gnus-article-search-signature)
585         (setq total (count-lines start (point)))
586         (while atts
587           (setq hidden (+ hidden (length (cdr (assoc (cdar atts)
588                                                      gnus-cite-prefix-alist))))
589                 atts (cdr atts)))
590         (when (or force
591                   (and (> (* 100 hidden) (* gnus-cite-hide-percentage total))
592                        (> hidden gnus-cite-hide-absolute)))
593           (setq atts gnus-cite-attribution-alist)
594           (while atts
595             (setq total (cdr (assoc (cdar atts) gnus-cite-prefix-alist))
596                   atts (cdr atts))
597             (while total
598               (setq hidden (car total)
599                     total (cdr total))
600               (goto-char (point-min))
601               (forward-line (1- hidden))
602               (unless (assq hidden gnus-cite-attribution-alist)
603                 (gnus-add-text-properties
604                  (point) (progn (forward-line 1) (point))
605                  (nconc (list 'article-type 'cite)
606                         gnus-hidden-properties))))))))))
607
608 (defun gnus-article-hide-citation-in-followups ()
609   "Hide cited text in non-root articles."
610   (interactive)
611   (save-excursion
612     (set-buffer gnus-article-buffer)
613     (let ((article (cdr gnus-article-current)))
614       (unless (save-excursion
615                 (set-buffer gnus-summary-buffer)
616                 (gnus-article-displayed-root-p article))
617         (gnus-article-hide-citation)))))
618
619 ;;; Internal functions:
620
621 (defun gnus-cite-parse-maybe (&optional force no-overlay)
622   "Always parse the buffer."
623   (gnus-cite-localize)
624   ;;Reset parser information.
625   (setq gnus-cite-prefix-alist nil
626         gnus-cite-attribution-alist nil
627         gnus-cite-loose-prefix-alist nil
628         gnus-cite-loose-attribution-alist nil)
629   (unless no-overlay
630     (gnus-cite-delete-overlays))
631   ;; Parse if not too large.
632   (if (and gnus-cite-parse-max-size
633            (> (buffer-size) gnus-cite-parse-max-size))
634       ()
635     (setq gnus-cite-article (cons (car gnus-article-current)
636                                   (cdr gnus-article-current)))
637     (gnus-cite-parse-wrapper)))
638
639 (defun gnus-cite-delete-overlays ()
640   (dolist (overlay gnus-cite-overlay-list)
641     (when (or (not (gnus-overlay-end overlay))
642               (and (>= (gnus-overlay-end overlay) (point-min))
643                    (<= (gnus-overlay-end overlay) (point-max))))
644       (setq gnus-cite-overlay-list (delete overlay gnus-cite-overlay-list))
645       (gnus-delete-overlay overlay))))
646
647 (defun gnus-cite-parse-wrapper ()
648   ;; Wrap chopped gnus-cite-parse.
649   (article-goto-body)
650   (let ((inhibit-point-motion-hooks t))
651     (save-excursion
652       (gnus-cite-parse-attributions))
653     (save-excursion
654       (gnus-cite-parse))
655     (save-excursion
656       (gnus-cite-connect-attributions))))
657
658 (defun gnus-cite-parse ()
659   ;; Parse and connect citation prefixes and attribution lines.
660
661   ;; Parse current buffer searching for citation prefixes.
662   (let ((line (1+ (count-lines (point-min) (point))))
663         (case-fold-search t)
664         (max (save-excursion
665                (goto-char (point-max))
666                (gnus-article-search-signature)
667                (point)))
668         alist entry start begin end numbers prefix mc-flag)
669     ;; Get all potential prefixes in `alist'.
670     (while (< (point) max)
671       ;; Each line.
672       (setq begin (point)
673             end (progn (beginning-of-line 2) (point))
674             start end)
675       (goto-char begin)
676       ;; Ignore standard Supercite attribution prefix.
677       (when (looking-at gnus-supercite-regexp)
678         (if (match-end 1)
679             (setq end (1+ (match-end 1)))
680           (setq end (1+ begin))))
681       ;; Ignore very long prefixes.
682       (when (> end (+ (point) gnus-cite-max-prefix))
683         (setq end (+ (point) gnus-cite-max-prefix)))
684       (while (re-search-forward gnus-cite-prefix-regexp (1- end) t)
685         ;; Each prefix.
686         (setq end (match-end 0)
687               prefix (buffer-substring begin end))
688         (gnus-set-text-properties 0 (length prefix) nil prefix)
689         (setq entry (assoc prefix alist))
690         (if entry
691             (setcdr entry (cons line (cdr entry)))
692           (push (list prefix line) alist))
693         (goto-char begin))
694       (goto-char start)
695       (setq line (1+ line)))
696     ;; We got all the potential prefixes.  Now create
697     ;; `gnus-cite-prefix-alist' containing the oldest prefix for each
698     ;; line that appears at least gnus-cite-minimum-match-count
699     ;; times.  First sort them by length.  Longer is older.
700     (setq alist (sort alist (lambda (a b)
701                               (> (length (car a)) (length (car b))))))
702     (while alist
703       (setq entry (car alist)
704             prefix (car entry)
705             numbers (cdr entry)
706             alist (cdr alist))
707       (cond ((null numbers)
708              ;; No lines with this prefix that wasn't also part of
709              ;; a longer prefix.
710              )
711             ((< (length numbers) gnus-cite-minimum-match-count)
712              ;; Too few lines with this prefix.  We keep it a bit
713              ;; longer in case it is an exact match for an attribution
714              ;; line, but we don't remove the line from other
715              ;; prefixes.
716              (push entry gnus-cite-prefix-alist))
717             (t
718              (push entry
719                    gnus-cite-prefix-alist)
720              ;; Remove articles from other prefixes.
721              (let ((loop alist)
722                    current)
723                (while loop
724                  (setq current (car loop)
725                        loop (cdr loop))
726                  (setcdr current
727                          (gnus-set-difference (cdr current) numbers)))))))))
728
729 (defun gnus-cite-parse-attributions ()
730   (let (al-alist)
731     ;; Parse attributions
732     (while (re-search-forward gnus-cite-attribution-suffix (point-max) t)
733       (let* ((start (match-beginning 0))
734              (end (match-end 0))
735              (wrote (count-lines (point-min) end))
736              (prefix (gnus-cite-find-prefix wrote))
737              ;; Check previous line for an attribution leader.
738              (tag (progn
739                     (beginning-of-line 1)
740                     (when (looking-at gnus-supercite-secondary-regexp)
741                       (buffer-substring (match-beginning 1)
742                                         (match-end 1)))))
743              (in (progn
744                    (goto-char start)
745                    (and (re-search-backward gnus-cite-attribution-prefix
746                                             (save-excursion
747                                               (beginning-of-line 0)
748                                               (point))
749                                             t)
750                         (not (re-search-forward gnus-cite-attribution-suffix
751                                                 start t))
752                         (count-lines (point-min) (1+ (point)))))))
753         (when (eq wrote in)
754           (setq in nil))
755         (goto-char end)
756         ;; don't add duplicates
757         (let ((al (buffer-substring (save-excursion (beginning-of-line 0)
758                                                     (1+ (point)))
759                                     end)))
760           (if (not (assoc al al-alist))
761               (progn
762                 (push (list wrote in prefix tag)
763                       gnus-cite-loose-attribution-alist)
764                 (push (cons al t) al-alist))))))))
765
766 (defun gnus-cite-connect-attributions ()
767   ;; Connect attributions to citations
768
769   ;; No citations have been connected to attribution lines yet.
770   (setq gnus-cite-loose-prefix-alist (append gnus-cite-prefix-alist nil))
771
772   ;; Parse current buffer searching for attribution lines.
773   ;; Find exact supercite citations.
774   (gnus-cite-match-attributions 'small nil
775                                 (lambda (prefix tag)
776                                   (when tag
777                                     (concat "\\`"
778                                             (regexp-quote prefix) "[ \t]*"
779                                             (regexp-quote tag) ">"))))
780   ;; Find loose supercite citations after attributions.
781   (gnus-cite-match-attributions 'small t
782                                 (lambda (prefix tag)
783                                   (when tag
784                                     (concat "\\<"
785                                             (regexp-quote tag)
786                                             "\\>"))))
787   ;; Find loose supercite citations anywhere.
788   (gnus-cite-match-attributions 'small nil
789                                 (lambda (prefix tag)
790                                   (when tag
791                                     (concat "\\<"
792                                             (regexp-quote tag)
793                                             "\\>"))))
794   ;; Find nested citations after attributions.
795   (gnus-cite-match-attributions 'small-if-unique t
796                                 (lambda (prefix tag)
797                                   (concat "\\`" (regexp-quote prefix) ".+")))
798   ;; Find nested citations anywhere.
799   (gnus-cite-match-attributions 'small nil
800                                 (lambda (prefix tag)
801                                   (concat "\\`" (regexp-quote prefix) ".+")))
802   ;; Remove loose prefixes with too few lines.
803   (let ((alist gnus-cite-loose-prefix-alist)
804         entry)
805     (while alist
806       (setq entry (car alist)
807             alist (cdr alist))
808       (when (< (length (cdr entry)) gnus-cite-minimum-match-count)
809         (setq gnus-cite-prefix-alist
810               (delq entry gnus-cite-prefix-alist)
811               gnus-cite-loose-prefix-alist
812               (delq entry gnus-cite-loose-prefix-alist)))))
813   ;; Find flat attributions.
814   (gnus-cite-match-attributions 'first t nil)
815   ;; Find any attributions (are we getting desperate yet?).
816   (gnus-cite-match-attributions 'first nil nil))
817
818 (defun gnus-cite-match-attributions (sort after fun)
819   ;; Match all loose attributions and citations (SORT AFTER FUN) .
820   ;;
821   ;; If SORT is `small', the citation with the shortest prefix will be
822   ;; used, if it is `first' the first prefix will be used, if it is
823   ;; `small-if-unique' the shortest prefix will be used if the
824   ;; attribution line does not share its own prefix with other
825   ;; loose attribution lines, otherwise the first prefix will be used.
826   ;;
827   ;; If AFTER is non-nil, only citations after the attribution line
828   ;; will be considered.
829   ;;
830   ;; If FUN is non-nil, it will be called with the arguments (WROTE
831   ;; PREFIX TAG) and expected to return a regular expression.  Only
832   ;; citations whose prefix matches the regular expression will be
833   ;; considered.
834   ;;
835   ;; WROTE is the attribution line number.
836   ;; PREFIX is the attribution line prefix.
837   ;; TAG is the Supercite tag on the attribution line.
838   (let ((atts gnus-cite-loose-attribution-alist)
839         (case-fold-search t)
840         att wrote in prefix tag regexp limit smallest best size)
841     (while atts
842       (setq att (car atts)
843             atts (cdr atts)
844             wrote (nth 0 att)
845             in (nth 1 att)
846             prefix (nth 2 att)
847             tag (nth 3 att)
848             regexp (if fun (funcall fun prefix tag) "")
849             size (cond ((eq sort 'small) t)
850                        ((eq sort 'first) nil)
851                        (t (< (length (gnus-cite-find-loose prefix)) 2)))
852             limit (if after wrote -1)
853             smallest 1000000
854             best nil)
855       (let ((cites gnus-cite-loose-prefix-alist)
856             cite candidate numbers first compare)
857         (while cites
858           (setq cite (car cites)
859                 cites (cdr cites)
860                 candidate (car cite)
861                 numbers (cdr cite)
862                 first (apply 'min numbers)
863                 compare (if size (length candidate) first))
864           (and (> first limit)
865                regexp
866                (string-match regexp candidate)
867                (< compare smallest)
868                (setq best cite
869                      smallest compare))))
870       (if (null best)
871           ()
872         (setq gnus-cite-loose-attribution-alist
873               (delq att gnus-cite-loose-attribution-alist))
874         (push (cons wrote (car best)) gnus-cite-attribution-alist)
875         (when in
876           (push (cons in (car best)) gnus-cite-attribution-alist))
877         (when (memq best gnus-cite-loose-prefix-alist)
878           (let ((loop gnus-cite-prefix-alist)
879                 (numbers (cdr best))
880                 current)
881             (setq gnus-cite-loose-prefix-alist
882                   (delq best gnus-cite-loose-prefix-alist))
883             (while loop
884               (setq current (car loop)
885                     loop (cdr loop))
886               (if (eq current best)
887                   ()
888                 (setcdr current (gnus-set-difference (cdr current) numbers))
889                 (when (null (cdr current))
890                   (setq gnus-cite-loose-prefix-alist
891                         (delq current gnus-cite-loose-prefix-alist)
892                         atts (delq current atts)))))))))))
893
894 (defun gnus-cite-find-loose (prefix)
895   ;; Return a list of loose attribution lines prefixed by PREFIX.
896   (let* ((atts gnus-cite-loose-attribution-alist)
897          att line lines)
898     (while atts
899       (setq att (car atts)
900             line (car att)
901             atts (cdr atts))
902       (when (string-equal (gnus-cite-find-prefix line) prefix)
903         (push line lines)))
904     lines))
905
906 (defun gnus-cite-add-face (number prefix face)
907   ;; At line NUMBER, ignore PREFIX and add FACE to the rest of the line.
908   (when face
909     (let ((inhibit-point-motion-hooks t)
910           from to overlay)
911       (goto-char (point-min))
912       (when (zerop (forward-line (1- number)))
913         (static-if (or (featurep 'xemacs)
914                        (and (eq emacs-major-version 20)
915                             (>= emacs-minor-version 3))
916                        (> emacs-major-version 20));-)
917             (forward-char (length prefix))
918           (move-to-column (string-width prefix)))
919         (skip-chars-forward " \t")
920         (setq from (point))
921         (end-of-line 1)
922         (skip-chars-backward " \t")
923         (setq to (point))
924         (when (< from to)
925           (push (setq overlay (gnus-make-overlay from to))
926                 gnus-cite-overlay-list)
927           (gnus-overlay-put overlay 'face face))))))
928
929 (defun gnus-cite-toggle (prefix)
930   (save-excursion
931     (set-buffer gnus-article-buffer)
932     (gnus-cite-parse-maybe nil t)
933     (let ((buffer-read-only nil)
934           (numbers (cdr (assoc prefix gnus-cite-prefix-alist)))
935           (inhibit-point-motion-hooks t)
936           number)
937       (while numbers
938         (setq number (car numbers)
939               numbers (cdr numbers))
940         (goto-char (point-min))
941         (forward-line (1- number))
942         (cond ((get-text-property (point) 'invisible)
943                (remove-text-properties (point) (progn (forward-line 1) (point))
944                                        gnus-hidden-properties))
945               ((assq number gnus-cite-attribution-alist))
946               (t
947                (gnus-add-text-properties
948                 (point) (progn (forward-line 1) (point))
949                 (nconc (list 'article-type 'cite)
950                        gnus-hidden-properties))))))))
951
952 (defun gnus-cite-find-prefix (line)
953   ;; Return citation prefix for LINE.
954   (let ((alist gnus-cite-prefix-alist)
955         (prefix "")
956         entry)
957     (while alist
958       (setq entry (car alist)
959             alist (cdr alist))
960       (when (memq line (cdr entry))
961         (setq prefix (car entry))))
962     prefix))
963
964 (defun gnus-cite-localize ()
965   "Make the citation variables local to the article buffer."
966   (let ((vars '(gnus-cite-article
967                 gnus-cite-overlay-list gnus-cite-prefix-alist
968                 gnus-cite-attribution-alist gnus-cite-loose-prefix-alist
969                 gnus-cite-loose-attribution-alist)))
970     (while vars
971       (make-local-variable (pop vars)))))
972
973 (gnus-ems-redefine)
974
975 (provide 'gnus-cite)
976
977 ;; Local Variables:
978 ;; coding: iso-8859-1
979 ;; End:
980
981 ;;; gnus-cite.el ends here