*** empty log message ***
[gnus] / lisp / gnus-score.el
1 ;;; gnus-score.el --- scoring code for Gnus
2 ;; Copyright (C) 1995 Free Software Foundation, Inc.
3
4 ;; Author: Per Abrahamsen <amanda@iesd.auc.dk>
5 ;;      Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to
22 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (require 'gnus)
29
30 (defvar gnus-score-expiry-days 7
31   "*Number of days before unused score file entries are expired.")
32
33 (defvar gnus-orphan-score nil
34   "*All orphans get this score added. Set in the score file.")
35
36 (defvar gnus-default-adaptive-score-alist  
37   '((gnus-kill-file-mark)
38     (gnus-unread-mark)
39     (gnus-read-mark (from  3) (subject  30))
40     (gnus-catchup-mark (subject -10))
41     (gnus-killed-mark (from -1) (subject -20))
42     (gnus-del-mark (from -2) (subject -15)))
43 "*Alist of marks and scores.")
44
45 (defvar gnus-score-mimic-keymap nil
46   "*Have the score entry functions pretend that they are a keymap.")
47
48 (defvar gnus-score-exact-adapt-limit 10
49   "*Number that says how long a match has to be before using substring matching.
50 When doing adaptive scoring, one normally uses fuzzy or substring
51 matching. However, if the header one matches is short, the possibility
52 for false positives is great, so if the length of the match is less
53 than this variable, exact matching will be used.
54
55 If this variable is nil, exact matching will always be used.")
56
57 (defvar gnus-score-uncacheable-files "ADAPT$"
58   "*All score files that match this regexp will not be cached.")
59
60 \f
61
62 ;; Internal variables.
63
64 (defvar gnus-score-help-winconf nil)
65 (defvar gnus-adaptive-score-alist gnus-default-adaptive-score-alist)
66 (defvar gnus-score-trace nil)
67 (defvar gnus-score-edit-buffer nil)
68
69 (defvar gnus-score-alist nil
70   "Alist containing score information.
71 The keys can be symbols or strings.  The following symbols are defined. 
72
73 touched: If this alist has been modified.
74 mark:    Automatically mark articles below this.
75 expunge: Automatically expunge articles below this.
76 files:   List of other score files to load when loading this one.
77 eval:    Sexp to be evaluated when the score file is loaded.
78
79 String entries have the form (HEADER (MATCH TYPE SCORE DATE) ...) 
80 where HEADER is the header being scored, MATCH is the string we are
81 looking for, TYPE is a flag indicating whether it should use regexp or
82 substring matching, SCORE is the score to add and DATE is the date
83 of the last successful match.")
84
85 (defvar gnus-score-cache nil)
86 (defvar gnus-scores-articles nil)
87 (defvar gnus-header-index nil)
88 (defvar gnus-score-index nil)
89
90 (eval-and-compile
91   (autoload 'gnus-uu-ctl-map "gnus-uu" nil nil 'keymap)
92   (autoload 'appt-select-lowest-window "appt.el"))
93
94 ;;; Summary mode score maps.
95
96 (defvar gnus-summary-score-map nil)
97
98 (define-prefix-command 'gnus-summary-score-map)
99 (define-key gnus-summary-mode-map "V" 'gnus-summary-score-map)
100 (define-key gnus-summary-score-map "s" 'gnus-summary-set-score)
101 (define-key gnus-summary-score-map "a" 'gnus-summary-score-entry)
102 (define-key gnus-summary-score-map "S" 'gnus-summary-current-score)
103 (define-key gnus-summary-score-map "c" 'gnus-score-change-score-file)
104 (define-key gnus-summary-score-map "m" 'gnus-score-set-mark-below)
105 (define-key gnus-summary-score-map "x" 'gnus-score-set-expunge-below)
106 (define-key gnus-summary-score-map "e" 'gnus-score-edit-alist)
107 (define-key gnus-summary-score-map "f" 'gnus-score-edit-file)
108 (define-key gnus-summary-score-map "t" 'gnus-score-find-trace)
109 (define-key gnus-summary-score-map "C" 'gnus-score-customize)
110
111
112
113 ;; Summary score file commands
114
115 ;; Much modification of the kill (ahem, score) code and lots of the
116 ;; functions are written by Per Abrahamsen <amanda@iesd.auc.dk>.
117
118 (defun gnus-summary-lower-score (&optional score)
119   "Make a score entry based on the current article.
120 The user will be prompted for header to score on, match type,
121 permanence, and the string to be used.  The numerical prefix will be
122 used as score."
123   (interactive "P")
124   (gnus-summary-increase-score (- (gnus-score-default score))))
125
126 (defun gnus-summary-increase-score (&optional score)
127   "Make a score entry based on the current article.
128 The user will be prompted for header to score on, match type,
129 permanence, and the string to be used.  The numerical prefix will be
130 used as score."
131   (interactive "P")
132   (gnus-set-global-variables)
133   (let* ((nscore (gnus-score-default score))
134          (prefix (if (< nscore 0) ?L ?I))
135          (increase (> nscore 0))
136          (char-to-header 
137           '((?a "from" nil nil string)
138             (?s "subject" nil nil string)
139             (?b "body" "" nil body-string)
140             (?h "head" "" nil body-string)
141             (?i "message-id" nil t string)
142             (?t "references" "message-id" t string)
143             (?x "xref" nil nil string)
144             (?l "lines" nil nil number)
145             (?d "date" nil nil date)
146             (?f "followup" nil nil string)))
147          (char-to-type
148           '((?s s "substring" string)
149             (?e e "exact string" string)
150             (?f f "fuzzy string" string)
151             (?r r "regexp string" string)
152             (?s s "substring" body-string)
153             (?r s "regexp string" body-string)
154             (?b before "before date" date)
155             (?a at "at date" date) 
156             (?n now "this date" date)
157             (?< < "less than number" number)
158             (?> > "greater than number" number) 
159             (?= = "equal to number" number)))
160          (char-to-perm
161           (list (list ?t (current-time-string) "temporary") 
162                 '(?p perm "permanent") '(?i now "immediate")))
163          (mimic gnus-score-mimic-keymap)
164          hchar entry temporary tchar pchar end type)
165     ;; First we read the header to score.
166     (while (not hchar)
167       (if mimic
168           (progn 
169             (sit-for 1)
170             (message "%c-" prefix))
171         (message "%s header (%s?): " (if increase "Increase" "Lower")
172                  (mapconcat (lambda (s) (char-to-string (car s)))
173                             char-to-header "")))
174       (setq hchar (read-char))
175       (if (not (or (= hchar ??) (= hchar ?\C-h)))
176           ()
177         (setq hchar nil)
178         (gnus-score-insert-help "Match on header" char-to-header 1)))
179
180     (and (get-buffer "*Score Help*")
181          (progn
182            (kill-buffer "*Score Help*")
183            (and gnus-score-help-winconf
184                 (set-window-configuration gnus-score-help-winconf))))
185
186     (or (setq entry (assq (downcase hchar) char-to-header))
187         (progn
188           (ding)
189           (setq end t)
190           (if mimic (message "%c %c" prefix hchar) (message ""))))
191     (if (or end (/= (downcase hchar) hchar))
192         (progn
193           ;; This was a majuscle, so we end reading and set the defaults.
194           (if mimic (message "%c %c" prefix hchar) (message ""))
195           (setq type nil
196                 temporary (current-time-string)))
197
198       ;; We continue reading - the type.
199       (while (not tchar)
200         (if mimic
201             (progn
202               (sit-for 1)
203               (message "%c %c-" prefix hchar))
204           (message "%s header '%s' with match type (%s?): "
205                    (if increase "Increase" "Lower")
206                    (nth 1 entry)
207                    (mapconcat (lambda (s) 
208                                 (if (eq (nth 4 entry) 
209                                         (nth 3 s))
210                                     (char-to-string (car s))
211                                   ""))
212                               char-to-type "")))
213         (setq tchar (read-char))
214         (if (not (or (= tchar ??) (= tchar ?\C-h)))
215             ()
216           (setq tchar nil)
217           (gnus-score-insert-help "Match type" char-to-type 2)))
218
219       (and (get-buffer "*Score Help*")
220            (progn
221              (and gnus-score-help-winconf
222                   (set-window-configuration gnus-score-help-winconf))
223              (kill-buffer "*Score Help*")))
224       
225       (or (setq type (nth 1 (assq (downcase tchar) char-to-type)))
226           (progn
227             (ding)
228             (if mimic (message "%c %c" prefix hchar) (message ""))
229             (setq end t)))
230       (if (or end (/= (downcase tchar) tchar))
231           (progn
232             ;; It was a majuscle, so we end reading and the the default.
233             (if mimic (message "%c %c %c" prefix hchar tchar)
234               (message ""))
235             (setq temporary (current-time-string)))
236
237         ;; We continue reading.
238         (while (not pchar)
239           (if mimic
240               (progn
241                 (sit-for 1)
242                 (message "%c %c %c-" prefix hchar tchar))
243             (message "%s permanence (%s?): " (if increase "Increase" "Lower")
244                      (mapconcat (lambda (s) (char-to-string (car s)))
245                                 char-to-perm "")))
246           (setq pchar (read-char))
247           (if (not (or (= pchar ??) (= pchar ?\C-h)))
248               ()
249             (setq pchar nil)
250             (gnus-score-insert-help "Match permanence" char-to-perm 2)))
251
252         (and (get-buffer "*Score Help*")
253              (progn
254                (and gnus-score-help-winconf
255                     (set-window-configuration gnus-score-help-winconf))
256                (kill-buffer "*Score Help*")))
257
258         (if mimic (message "%c %c %c" prefix hchar tchar pchar)
259           (message ""))
260         (if (setq temporary (nth 1 (assq pchar char-to-perm)))
261             ()
262           (ding)
263           (setq end t)
264           (if mimic 
265               (message "%c %c %c %c" prefix hchar tchar pchar)
266             (message "")))))
267
268     ;; We have all the data, so we enter this score.
269     (if end
270         ()
271       (gnus-summary-score-entry
272        (nth 1 entry)                    ; Header
273        (if (string= (nth 2 entry) "") ""
274          (gnus-summary-header (or (nth 2 entry) (nth 1 entry)))) ; Match
275        type                             ; Type
276        (if (eq 's score) nil score)     ; Score
277        (if (eq 'perm temporary)         ; Temp
278            nil
279          temporary)
280        (not (nth 3 entry)))             ; Prompt
281       )))
282   
283 (defun gnus-score-insert-help (string alist idx)
284   (setq gnus-score-help-winconf (current-window-configuration))
285   (save-excursion
286     (set-buffer (get-buffer-create "*Score Help*"))
287     (buffer-disable-undo (current-buffer))
288     (delete-windows-on (current-buffer))
289     (erase-buffer)
290     (insert string ":\n\n")
291     (let ((max -1)
292           (list alist)
293           (i 0)
294           n width pad format)
295       ;; find the longest string to display
296       (while list
297         (setq n (length (nth idx (car list))))
298         (or (> max n)
299             (setq max n))
300         (setq list (cdr list)))
301       (setq max (+ max 4))              ; %c, `:', SPACE, a SPACE at end
302       (setq n (/ (window-width) max))   ; items per line
303       (setq width (/ (window-width) n)) ; width of each item
304       ;; insert `n' items, each in a field of width `width' 
305       (while alist
306         (if (< i n)
307             ()
308           (setq i 0)
309           (delete-char -1)              ; the `\n' takes a char
310           (insert "\n"))
311         (setq pad (- width 3))
312         (setq format (concat "%c: %-" (int-to-string pad) "s"))
313         (insert (format format (car (car alist)) (nth idx (car alist))))
314         (setq alist (cdr alist))
315         (setq i (1+ i))))
316     ;; display ourselves in a small window at the bottom
317     (appt-select-lowest-window)
318     (split-window)
319     (pop-to-buffer "*Score Help*")
320     (shrink-window-if-larger-than-buffer)
321     (select-window (get-buffer-window gnus-summary-buffer))))
322   
323 (defun gnus-summary-header (header &optional no-err)
324   ;; Return HEADER for current articles, or error.
325   (let ((article (gnus-summary-article-number))
326         headers)
327     (if article
328         (if (and (setq headers (gnus-summary-article-header article))
329                  (vectorp headers))
330             (aref headers (nth 1 (assoc header gnus-header-index)))
331           (if no-err
332               nil
333             (error "Pseudo-articles can't be scored")))
334       (if no-err
335           (error "No article on current line")
336         nil))))
337
338 (defun gnus-summary-score-entry 
339   (header match type score date &optional prompt silent)
340   "Enter score file entry.
341 HEADER is the header being scored.
342 MATCH is the string we are looking for.
343 TYPE is the match type: substring, regexp, exact, fuzzy.
344 SCORE is the score to add.
345 DATE is the expire date, or nil for no expire, or 'now for immediate expire.
346 If optional argument `PROMPT' is non-nil, allow user to edit match.
347 If optional argument `SILENT' is nil, show effect of score entry."
348   (interactive
349    (list (completing-read "Header: "
350                           gnus-header-index
351                           (lambda (x) (fboundp (nth 2 x)))
352                           t)
353          (read-string "Match: ")
354          (if (y-or-n-p "Use regexp match? ") 'r 's)
355          (and current-prefix-arg
356               (prefix-numeric-value current-prefix-arg))
357          (cond ((not (y-or-n-p "Add to score file? "))
358                 'now)
359                ((y-or-n-p "Expire kill? ")
360                 (current-time-string))
361                (t nil))))
362   ;; Regexp is the default type.
363   (if (eq type t) (setq type 'r))
364   ;; Simplify matches...
365   (cond ((or (eq type 'r) (eq type 's) (eq type nil))
366          (setq match (if match (gnus-simplify-subject-re match) "")))
367         ((eq type 'f)
368          (setq match (gnus-simplify-subject-fuzzy match))))
369   (let ((score (gnus-score-default score))
370         (header (downcase header)))
371     (and prompt (setq match (read-string 
372                              (format "Match %s on %s, %s: " 
373                                      (cond ((eq date 'now)
374                                             "now")
375                                            ((stringp date)
376                                             "temp")
377                                            (t "permanent"))
378                                      header
379                                      (if (< score 0) "lower" "raise"))
380                              (if (numberp match)
381                                  (int-to-string match)
382                                match))))
383     (and (>= (nth 1 (assoc header gnus-header-index)) 0)
384          (eq (nth 2 (assoc header gnus-header-index)) 'gnus-score-string)
385          (not silent)
386          (gnus-summary-score-effect header match type score))
387
388     ;; If this is an integer comparison, we transform from string to int. 
389     (and (eq (nth 2 (assoc header gnus-header-index)) 'gnus-score-integer)
390          (setq match (string-to-int match)))
391
392     (if (eq date 'now)
393         ()
394       (and (= score gnus-score-interactive-default-score)
395            (setq score nil))
396       (let ((new (cond 
397                   (type
398                    (list match score (and date (gnus-day-number date)) type))
399                   (date
400                    (list match score (gnus-day-number date)))
401                   (score
402                    (list match score))
403                   (t
404                    (list match))))
405             (old (gnus-score-get header))
406             elem)
407         ;; We see whether we can collapse some score entries.
408         ;; This isn't quite correct, because there may be more elements
409         ;; later on with the same key that have matching elems... Hm.
410         (if (and old
411                  (setq elem (assoc match old))
412                  (eq (nth 3 elem) (nth 3 new))
413                  (or (and (numberp (nth 2 elem)) (numberp (nth 2 new)))
414                      (and (not (nth 2 elem)) (not (nth 2 new)))))
415             ;; Yup, we just add this new score to the old elem.
416             (setcar (cdr elem) (+ (or (nth 1 elem) 
417                                       gnus-score-interactive-default-score)
418                                   (or (nth 1 new)
419                                       gnus-score-interactive-default-score)))
420           ;; Nope, we have to add a new elem.
421           (gnus-score-set header (if old (cons new old) (list new)))))
422       (gnus-score-set 'touched '(t)))))
423
424 (defun gnus-summary-score-effect (header match type score)
425   "Simulate the effect of a score file entry.
426 HEADER is the header being scored.
427 MATCH is the string we are looking for.
428 TYPE is a flag indicating if it is a regexp or substring.
429 SCORE is the score to add."
430   (interactive (list (completing-read "Header: "
431                                       gnus-header-index
432                                       (lambda (x) (fboundp (nth 2 x)))
433                                       t)
434                      (read-string "Match: ")
435                      (y-or-n-p "Use regexp match? ")
436                      (prefix-numeric-value current-prefix-arg)))
437   (save-excursion
438     (or (and (stringp match) (> (length match) 0))
439         (error "No match"))
440     (goto-char (point-min))
441     (let ((regexp (cond ((eq type 'f)
442                          (gnus-simplify-subject-fuzzy match))
443                         (type match)
444                         (t (concat "\\`.*" (regexp-quote match) ".*\\'")))))
445       (while (not (eobp))
446         (let ((content (gnus-summary-header header 'noerr))
447               (case-fold-search t))
448           (and content
449                (if (if (eq type 'f)
450                        (string-equal (gnus-simplify-subject-fuzzy content)
451                                      regexp)
452                      (string-match regexp content))
453                    (gnus-summary-raise-score score))))
454         (beginning-of-line 2)))))
455
456 (defun gnus-summary-score-crossposting (score date)
457   ;; Enter score file entry for current crossposting.
458   ;; SCORE is the score to add.
459   ;; DATE is the expire date.
460   (let ((xref (gnus-summary-header "xref"))
461         (start 0)
462         group)
463     (or xref (error "This article is not crossposted"))
464     (while (string-match " \\([^ \t]+\\):" xref start)
465       (setq start (match-end 0))
466       (if (not (string= 
467                 (setq group 
468                       (substring xref (match-beginning 1) (match-end 1)))
469                 gnus-newsgroup-name))
470           (gnus-summary-score-entry
471            "xref" (concat " " group ":") nil score date t)))))
472
473 \f
474 ;;;
475 ;;; Gnus Score Files
476 ;;;
477
478 ;; All score code written by Per Abrahamsen <abraham@iesd.auc.dk>.
479
480 ;; Added by Per Abrahamsen <amanda@iesd.auc.dk>.
481 (defun gnus-score-set-mark-below (score)
482   "Automatically mark articles with score below SCORE as read."
483   (interactive 
484    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
485              (string-to-int (read-string "Mark below: ")))))
486   (setq score (or score gnus-summary-default-score 0))
487   (gnus-score-set 'mark (list score))
488   (gnus-score-set 'touched '(t))
489   (setq gnus-summary-mark-below score)
490   (gnus-summary-update-lines))
491
492 (defun gnus-score-set-expunge-below (score)
493   "Automatically expunge articles with score below SCORE."
494   (interactive 
495    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
496              (string-to-int (read-string "Expunge below: ")))))
497   (setq score (or score gnus-summary-default-score 0))
498   (gnus-score-set 'expunge (list score))
499   (gnus-score-set 'touched '(t)))
500
501 (defun gnus-score-set (symbol value &optional alist)
502   ;; Set SYMBOL to VALUE in ALIST.
503   (let* ((alist 
504           (or alist 
505               gnus-score-alist
506               (progn
507                 (gnus-score-load (gnus-score-file-name gnus-newsgroup-name))
508                 gnus-score-alist)))
509          (entry (assoc symbol alist)))
510     (cond ((gnus-score-get 'read-only alist)
511            ;; This is a read-only score file, so we do nothing.
512            )
513           (entry
514            (setcdr entry value))
515           ((null alist)
516            (error "Empty alist"))
517           (t
518            (setcdr alist
519                    (cons (cons symbol value) (cdr alist)))))))
520
521 (defun gnus-score-get (symbol &optional alist)
522   ;; Get SYMBOL's definition in ALIST.
523   (cdr (assoc symbol 
524               (or alist 
525                   gnus-score-alist
526                   (progn
527                     (gnus-score-load 
528                      (gnus-score-file-name gnus-newsgroup-name))
529                     gnus-score-alist)))))
530
531 (defun gnus-score-change-score-file (file)
532   "Change current score alist."
533   (interactive 
534    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
535   (gnus-score-load-file file)
536   (gnus-set-mode-line 'summary))
537
538 (defun gnus-score-edit-alist (file)
539   "Edit the current score alist."
540   (interactive (list gnus-current-score-file))
541   (let ((winconf (current-window-configuration)))
542     (and (buffer-name gnus-summary-buffer) (gnus-score-save))
543     (setq gnus-score-edit-buffer (find-file-noselect file))
544     (gnus-configure-windows 'edit-score)
545     (gnus-score-mode)
546     (make-local-variable 'gnus-prev-winconf)
547     (setq gnus-prev-winconf winconf))
548   (gnus-message 
549    4 (substitute-command-keys 
550       "\\<gnus-score-mode-map>\\[gnus-score-edit-done] to save edits")))
551   
552 (defun gnus-score-edit-file (file)
553   "Edit a score file."
554   (interactive 
555    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
556   (and (buffer-name gnus-summary-buffer) (gnus-score-save))
557   (let ((winconf (current-window-configuration)))
558     (setq gnus-score-edit-buffer (find-file-noselect file))
559     (gnus-configure-windows 'edit-score)
560     (gnus-score-mode)
561     (make-local-variable 'gnus-prev-winconf)
562     (setq gnus-prev-winconf winconf))
563   (gnus-message 
564    4 (substitute-command-keys 
565       "\\<gnus-score-mode-map>\\[gnus-score-edit-done] to save edits")))
566   
567 (defun gnus-score-load-file (file)
568   ;; Load score file FILE.  Returns a list a retrieved score-alists.
569   (setq gnus-kill-files-directory (or gnus-kill-files-directory "~/News/"))
570   (let* ((file (expand-file-name 
571                 (or (and (string-match
572                           (concat "^" (expand-file-name
573                                        gnus-kill-files-directory)) 
574                           (expand-file-name file))
575                          file)
576                     (concat gnus-kill-files-directory file))))
577          (cached (assoc file gnus-score-cache))
578          (global (member file gnus-internal-global-score-files))
579          lists alist)
580     (if cached
581         ;; The score file was already loaded.
582         (setq alist (cdr cached))
583       ;; We load the score file.
584       (setq gnus-score-alist nil)
585       (setq alist (gnus-score-load-score-alist file))
586       ;; We add '(touched) to the alist to signify that it hasn't been
587       ;; touched (yet). 
588       (or (assq 'touched alist) (setq alist (cons (list 'touched nil) alist)))
589       ;; If it is a global score file, we make it read-only.
590       (and global
591            (not (assq 'read-only alist))
592            (setq alist (cons (list 'read-only t) alist)))
593       (setq gnus-score-cache
594             (cons (cons file alist) gnus-score-cache)))
595     ;; If there are actual scores in the alist, we add it to the
596     ;; return value of this function.
597     (if (memq t (mapcar (lambda (e) (stringp (car e))) alist))
598         (setq lists (list alist)))
599     ;; Treat the other possible atoms in the score alist.
600     (let ((mark (car (gnus-score-get 'mark alist)))
601           (expunge (car (gnus-score-get 'expunge alist)))
602           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
603           (files (gnus-score-get 'files alist))
604           (exclude-files (gnus-score-get 'exclude-files alist))
605           (orphan (car (gnus-score-get 'orphan alist)))
606           (adapt (gnus-score-get 'adapt alist))
607           (local (gnus-score-get 'local alist))
608           (eval (car (gnus-score-get 'eval alist))))
609       ;; We do not respect eval and files atoms from global score
610       ;; files. 
611       (and files (not global)
612            (setq lists (apply 'append lists
613                               (mapcar (lambda (file)
614                                         (gnus-score-load-file file)) 
615                                       files))))
616       (and eval (not global) (eval eval))
617       (setq gnus-scores-exclude-files 
618             (append exclude-files gnus-scores-exclude-files))
619       (if (not local)
620           ()
621         (save-excursion
622           (set-buffer gnus-summary-buffer)
623           (while local
624             (and (consp (car local))
625                  (symbolp (car (car local)))
626                  (progn
627                    (make-local-variable (car (car local)))
628                    (set (car (car local)) (nth 1 (car local)))))
629             (setq local (cdr local)))))
630       (if orphan (setq gnus-orphan-score orphan))
631       (setq gnus-adaptive-score-alist
632             (cond ((equal adapt '(t))
633                    (setq gnus-newsgroup-adaptive t)
634                    gnus-default-adaptive-score-alist)
635                   ((equal adapt '(ignore))
636                    (setq gnus-newsgroup-adaptive nil))
637                   ((consp adapt)
638                    (setq gnus-newsgroup-adaptive t)
639                    adapt)
640                   (t
641                    ;;(setq gnus-newsgroup-adaptive gnus-use-adaptive-scoring)
642                    gnus-default-adaptive-score-alist)))
643       (setq gnus-summary-mark-below 
644             (or mark mark-and-expunge gnus-summary-mark-below))
645       (setq gnus-summary-expunge-below 
646             (or expunge mark-and-expunge gnus-summary-expunge-below)))
647     (setq gnus-current-score-file file)
648     (setq gnus-score-alist alist)
649     lists))
650
651 (defun gnus-score-load (file)
652   ;; Load score FILE.
653   (let ((cache (assoc file gnus-score-cache)))
654     (if cache
655         (setq gnus-score-alist (cdr cache))
656       (setq gnus-score-alist nil)
657       (gnus-score-load-score-alist file)
658       (or gnus-score-alist
659           (setq gnus-score-alist (copy-alist '((touched nil)))))
660       (setq gnus-score-cache
661             (cons (cons file gnus-score-alist) gnus-score-cache)))))
662
663 (defun gnus-score-remove-from-cache (file)
664   (setq gnus-score-cache 
665         (delq (assoc file gnus-score-cache) gnus-score-cache)))
666
667 (defun gnus-score-load-score-alist (file)
668   (let (alist)
669     (if (file-readable-p file)
670         (progn
671           (save-excursion
672             (gnus-set-work-buffer)
673             (insert-file-contents file)
674             (goto-char (point-min))
675             ;; Only do the loading if the score file isn't empty.
676             (if (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
677                 (setq alist
678                       (condition-case ()
679                           (read (current-buffer))
680                         (error 
681                          (progn
682                            (gnus-message 3 "Problem with score file %s" file)
683                            (ding) 
684                            (sit-for 2)
685                            nil))))))
686           (if (eq (car alist) 'setq)
687               (setq gnus-score-alist (gnus-score-transform-old-to-new alist))
688             (setq gnus-score-alist alist))
689           (setq gnus-score-alist
690                 (gnus-score-check-syntax gnus-score-alist file)))
691       (setq gnus-score-alist nil))))
692
693 (defun gnus-score-check-syntax (alist file)
694   (cond 
695    ((null alist)
696     nil)
697    ((not (consp alist))
698     (gnus-message 1 "Score file is not a list: %s" file)
699     (ding)
700     nil)
701    (t
702     (let ((a alist)
703           err)
704       (while (and a (not err))
705         (cond ((not (listp (car a)))
706                (gnus-message 3 "Illegal score element %s in %s" (car a) file)
707                (setq err t))
708               ((and (stringp (car (car a)))
709                     (not (listp (nth 1 (car a)))))
710                (gnus-message 3 "Illegal header match %s in %s" (nth 1 (car a)) file)
711                (setq err t))
712               (t
713                (setq a (cdr a)))))
714       (if err
715           (progn
716             (ding)
717             nil)
718         alist)))))    
719
720 (defun gnus-score-transform-old-to-new (alist)
721   (let* ((alist (nth 2 alist))
722          out entry)
723     (if (eq (car alist) 'quote)
724         (setq alist (nth 1 alist)))
725     (while alist
726       (setq entry (car alist))
727       (if (stringp (car entry))
728           (let ((scor (cdr entry)))
729             (setq out (cons entry out))
730             (while scor
731               (setcar scor
732                       (list (car (car scor)) (nth 2 (car scor))
733                             (and (nth 3 (car scor))
734                                  (gnus-day-number (nth 3 (car scor))))
735                             (if (nth 1 (car scor)) 'r 's)))
736               (setq scor (cdr scor))))
737         (setq out (cons (if (not (listp (cdr entry))) 
738                             (list (car entry) (cdr entry))
739                           entry)
740                         out)))
741       (setq alist (cdr alist)))
742     (cons (list 'touched t) (nreverse out))))
743   
744 (defun gnus-score-save ()
745   ;; Save all score information.
746   (let ((cache gnus-score-cache))
747     (save-excursion
748       (setq gnus-score-alist nil)
749       (set-buffer (get-buffer-create "*Score*"))
750       (buffer-disable-undo (current-buffer))
751       (let (entry score file)
752         (while cache
753           (setq entry (car cache)
754                 cache (cdr cache)
755                 file (car entry)
756                 score (cdr entry))
757           (if (or (not (equal (gnus-score-get 'touched score) '(t)))
758                   (gnus-score-get 'read-only score)
759                   (and (file-exists-p file)
760                        (not (file-writable-p file))))
761               ()
762             (setq score (setcdr entry (delq (assq 'touched score) score)))
763             (erase-buffer)
764             (let (emacs-lisp-mode-hook)
765               (if (string-match (concat gnus-adaptive-file-suffix "$") file)
766                   ;; This is an adaptive score file, so we do not run
767                   ;; it through `pp'.  These files can get huge, and
768                   ;; are not meant to be edited by human hands.
769                   (insert (format "%S" score))
770                 ;; This is a normal score file, so we print it very
771                 ;; prettily. 
772                 (pp score (current-buffer))))
773             (if (not (gnus-make-directory (file-name-directory file)))
774                 ()
775               ;; If the score file is empty, we delete it.
776               (if (zerop (buffer-size))
777                   (delete-file file)
778                 ;; There are scores, so we write the file. 
779                 (and (file-writable-p file)
780                      (write-region (point-min) (point-max) 
781                                    file nil 'silent))))
782             (and gnus-score-uncacheable-files
783                  (string-match gnus-score-uncacheable-files file)
784                  (gnus-score-remove-from-cache file)))))
785       (kill-buffer (current-buffer)))))
786   
787 (defun gnus-score-headers (score-files &optional trace)
788   ;; Score `gnus-newsgroup-headers'.
789   (let (scores)
790     ;; PLM: probably this is not the best place to clear orphan-score
791     (setq gnus-orphan-score nil)
792     (setq gnus-scores-articles nil)
793     (setq gnus-scores-exclude-files nil)
794     ;; Load the score files.
795     (while score-files
796       (if (stringp (car score-files))
797           ;; It is a string, which means that it's a score file name,
798           ;; so we load the score file and add the score alist to
799           ;; the list of alists.
800           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
801         ;; It is an alist, so we just add it to the list directly.
802         (setq scores (nconc (car score-files) scores)))
803       (setq score-files (cdr score-files)))
804     ;; Prune the score files that are to be excluded, if any.
805     (if (not gnus-scores-exclude-files)
806         ()
807       (let ((s scores)
808             c)
809         (while s
810           (and (setq c (rassq (car s) gnus-score-cache))
811                (member (car c) gnus-scores-exclude-files)
812                (setq scores (delq (car s) scores)))
813           (setq s (cdr s)))))
814     (if (not (and gnus-summary-default-score
815                   scores
816                   (> (length gnus-newsgroup-headers)
817                      (length gnus-newsgroup-scored))))
818         ()
819       (let* ((entries gnus-header-index)
820              (now (gnus-day-number (current-time-string)))
821              (expire (- now gnus-score-expiry-days))
822              (headers gnus-newsgroup-headers)
823              (current-score-file gnus-current-score-file)
824              entry header)
825         (gnus-message 5 "Scoring...")
826         ;; Create articles, an alist of the form `(HEADER . SCORE)'.
827         (while headers
828           (setq header (car headers)
829                 headers (cdr headers))
830           ;; WARNING: The assq makes the function O(N*S) while it could
831           ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
832           ;; and S is (length gnus-newsgroup-scored).
833           (or (assq (mail-header-number header) gnus-newsgroup-scored)
834               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
835                     (cons (cons header (or gnus-summary-default-score 0))
836                           gnus-scores-articles))))
837
838         (save-excursion
839           (set-buffer (get-buffer-create "*Headers*"))
840           (buffer-disable-undo (current-buffer))
841
842           ;; Set the global variant of this variable.
843           (setq gnus-current-score-file current-score-file)
844           ;; score orphans
845           (if gnus-orphan-score 
846               (progn
847                 (setq gnus-score-index 
848                       (nth 1 (assoc "references" gnus-header-index)))
849                 (gnus-score-orphans gnus-orphan-score)))
850           ;; Run each header through the score process.
851           (while entries
852             (setq entry (car entries)
853                   header (nth 0 entry)
854                   entries (cdr entries))
855             (setq gnus-score-index (nth 1 (assoc header gnus-header-index)))
856             (if (< 0 (apply 'max (mapcar
857                                   (lambda (score)
858                                     (length (gnus-score-get header score)))
859                                   scores)))
860                 (funcall (nth 2 entry) scores header now expire trace)))
861           ;; Remove the buffer.
862           (kill-buffer (current-buffer)))
863
864         ;; Add articles to `gnus-newsgroup-scored'.
865         (while gnus-scores-articles
866           (or (= gnus-summary-default-score (cdr (car gnus-scores-articles)))
867               (setq gnus-newsgroup-scored
868                     (cons (cons (mail-header-number 
869                                  (car (car gnus-scores-articles)))
870                                 (cdr (car gnus-scores-articles)))
871                           gnus-newsgroup-scored)))
872           (setq gnus-scores-articles (cdr gnus-scores-articles)))
873
874         (gnus-message 5 "Scoring...done")))))
875
876
877 (defun gnus-get-new-thread-ids (articles)
878   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
879         (refind gnus-score-index)
880         id-list art this tref)
881     (while articles
882       (setq art (car articles)
883             this (aref (car art) index)
884             tref (aref (car art) refind)
885             articles (cdr articles))
886       (if (string-equal tref "")        ;no references line
887           (setq id-list (cons this id-list))))
888     id-list))
889
890 ;; Orphan functions written by plm@atcmp.nl (Peter Mutsaers).
891 (defun gnus-score-orphans (score)
892   (let ((new-thread-ids (gnus-get-new-thread-ids gnus-scores-articles))
893         alike articles art arts this last this-id)
894     
895     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
896           articles gnus-scores-articles)
897
898     ;;more or less the same as in gnus-score-string
899     (erase-buffer)
900     (while articles
901       (setq art (car articles)
902             this (aref (car art) gnus-score-index)
903             articles (cdr articles))
904       ;;completely skip if this is empty (not a child, so not an orphan)
905       (if (not (string= this ""))
906           (if (equal last this)
907               ;; O(N*H) cons-cells used here, where H is the number of
908               ;; headers.
909               (setq alike (cons art alike))
910             (if last
911                 (progn
912                   ;; Insert the line, with a text property on the
913                   ;; terminating newline refering to the articles with
914                   ;; this line.
915                   (insert last ?\n)
916                   (put-text-property (1- (point)) (point) 'articles alike)))
917             (setq alike (list art)
918                   last this))))
919     (and last                           ; Bwadr, duplicate code.
920          (progn
921            (insert last ?\n)                    
922            (put-text-property (1- (point)) (point) 'articles alike)))
923
924     ;; PLM: now delete those lines that contain an entry from new-thread-ids
925     (while new-thread-ids
926       (setq this-id (car new-thread-ids)
927             new-thread-ids (cdr new-thread-ids))
928       (goto-char (point-min))
929       (while (search-forward this-id nil t)
930         ;; found a match. remove this line
931         (beginning-of-line)
932         (kill-line 1)))
933
934     ;; now for each line: update its articles with score by moving to
935     ;; every end-of-line in the buffer and read the articles property
936     (goto-char (point-min))
937     (while (eq 0 (progn
938                    (end-of-line)
939                    (setq arts (get-text-property (point) 'articles))
940                    (while arts
941                      (setq art (car arts)
942                            arts (cdr arts))
943                      (setcdr art (+ score (cdr art))))
944                    (forward-line))))))
945              
946
947 (defun gnus-score-integer (scores header now expire &optional trace)
948   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
949         entries alist)
950
951     ;; Find matches.
952     (while scores
953       (setq alist (car scores)
954             scores (cdr scores)
955             entries (assoc header alist))
956       (while (cdr entries)              ;First entry is the header index.
957         (let* ((rest (cdr entries))             
958                (kill (car rest))
959                (match (nth 0 kill))
960                (type (or (nth 3 kill) '>))
961                (score (or (nth 1 kill) gnus-score-interactive-default-score))
962                (date (nth 2 kill))
963                (found nil)
964                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
965                                    (eq type '>=) (eq type '=))
966                                type
967                              (error "Illegal match type: %s" type)))
968                (articles gnus-scores-articles))
969           ;; Instead of doing all the clever stuff that
970           ;; `gnus-score-string' does to minimize searches and stuff,
971           ;; I will assume that people generally will put so few
972           ;; matches on numbers that any cleverness will take more
973           ;; time than one would gain.
974           (while articles
975             (and (funcall match-func 
976                           (or (aref (car (car articles)) gnus-score-index) 0)
977                           match)
978                  (progn
979                    (and trace (setq gnus-score-trace 
980                                     (cons
981                                      (cons
982                                       (car-safe (rassq alist gnus-score-cache))
983                                       kill)
984                                      gnus-score-trace)))
985                    (setq found t)
986                    (setcdr (car articles) (+ score (cdr (car articles))))))
987             (setq articles (cdr articles)))
988           ;; Update expire date
989           (cond ((null date))           ;Permanent entry.
990                 (found                  ;Match, update date.
991                  (gnus-score-set 'touched '(t) alist)
992                  (setcar (nthcdr 2 kill) now))
993                 ((< date expire)        ;Old entry, remove.
994                  (gnus-score-set 'touched '(t) alist)
995                  (setcdr entries (cdr rest))
996                  (setq rest entries)))
997           (setq entries rest))))))
998
999 (defun gnus-score-date (scores header now expire &optional trace)
1000   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1001         entries alist)
1002
1003     ;; Find matches.
1004     (while scores
1005       (setq alist (car scores)
1006             scores (cdr scores)
1007             entries (assoc header alist))
1008       (while (cdr entries)              ;First entry is the header index.
1009         (let* ((rest (cdr entries))             
1010                (kill (car rest))
1011                (match (timezone-make-date-sortable (nth 0 kill)))
1012                (type (or (nth 3 kill) 'before))
1013                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1014                (date (nth 2 kill))
1015                (found nil)
1016                (match-func 
1017                 (cond ((eq type 'after) 'string<)
1018                       ((eq type 'before) 'gnus-string>)
1019                       ((eq type 'at) 'string=)
1020                       (t (error "Illegal match type: %s" type))))
1021                (articles gnus-scores-articles)
1022                l)
1023           ;; Instead of doing all the clever stuff that
1024           ;; `gnus-score-string' does to minimize searches and stuff,
1025           ;; I will assume that people generally will put so few
1026           ;; matches on numbers that any cleverness will take more
1027           ;; time than one would gain.
1028           (while articles
1029             (and
1030              (setq l (aref (car (car articles)) gnus-score-index))
1031              (funcall match-func match (timezone-make-date-sortable l))
1032              (progn
1033                (and trace (setq gnus-score-trace 
1034                                 (cons
1035                                  (cons
1036                                   (car-safe (rassq alist gnus-score-cache))
1037                                   kill)
1038                                  gnus-score-trace)))
1039                (setq found t)
1040                (setcdr (car articles) (+ score (cdr (car articles))))))
1041             (setq articles (cdr articles)))
1042           ;; Update expire date
1043           (cond ((null date))           ;Permanent entry.
1044                 (found                  ;Match, update date.
1045                  (gnus-score-set 'touched '(t) alist)
1046                  (setcar (nthcdr 2 kill) now))
1047                 ((< date expire)        ;Old entry, remove.
1048                  (gnus-score-set 'touched '(t) alist)
1049                  (setcdr entries (cdr rest))
1050                  (setq rest entries)))
1051           (setq entries rest))))))
1052
1053 (defun gnus-score-body (scores header now expire &optional trace)
1054   (save-excursion
1055     (set-buffer nntp-server-buffer)
1056     (save-restriction
1057       (let* ((buffer-read-only nil)
1058              (articles gnus-scores-articles)
1059              (last (mail-header-number (car (car gnus-scores-articles))))
1060              (all-scores scores)
1061              (request-func (cond ((string= "head" (downcase header))
1062                                   'gnus-request-head)
1063                                  ((string= "body" (downcase header))
1064                                   'gnus-request-body)
1065                                  (t 'gnus-request-article)))
1066              entries alist ofunc article)
1067         ;; Not all backends support partial fetching.  In that case,
1068         ;; we just fetch the entire article.
1069         (or (gnus-check-backend-function 
1070              (and (string-match "^gnus-" (symbol-name request-func))
1071                   (intern (substring (symbol-name request-func)
1072                                      (match-end 0))))
1073              gnus-newsgroup-name)
1074             (progn
1075               (setq ofunc request-func)
1076               (setq request-func 'gnus-request-article)))
1077         (while articles
1078           (setq article (mail-header-number (car (car articles))))
1079           (gnus-message 7 "Scoring on article %s of %s..." article last)
1080           (if (not (funcall request-func article gnus-newsgroup-name))
1081               ()
1082             (widen)
1083             (goto-char (point-min))
1084             ;; If just parts of the article is to be searched, but the
1085             ;; backend didn't support partial fetching, we just narrow
1086             ;; to the relevant parts.
1087             (if ofunc
1088                 (if (eq ofunc 'gnus-request-head)
1089                     (narrow-to-region
1090                      (point)
1091                      (or (search-forward "\n\n" nil t) (point-max)))
1092                   (narrow-to-region
1093                    (or (search-forward "\n\n" nil t) (point))
1094                    (point-max))))
1095             (setq scores all-scores)
1096             ;; Find matches.
1097             (while scores
1098               (setq alist (car scores)
1099                     scores (cdr scores)
1100                     entries (assoc header alist))
1101               (while (cdr entries)      ;First entry is the header index.
1102                 (let* ((rest (cdr entries))             
1103                        (kill (car rest))
1104                        (match (nth 0 kill))
1105                        (type (or (nth 3 kill) 's))
1106                        (score (or (nth 1 kill) 
1107                                   gnus-score-interactive-default-score))
1108                        (date (nth 2 kill))
1109                        (found nil)
1110                        (case-fold-search 
1111                         (not (or (eq type 'R) (eq type 'S)
1112                                  (eq type 'Regexp) (eq type 'String))))
1113                        (search-func 
1114                         (cond ((or (eq type 'r) (eq type 'R)
1115                                    (eq type 'regexp) (eq type 'Regexp))
1116                                're-search-forward)
1117                               ((or (eq type 's) (eq type 'S)
1118                                    (eq type 'string) (eq type 'String))
1119                                'search-forward)
1120                               (t
1121                                (error "Illegal match type: %s" type)))))
1122                   (goto-char (point-min))
1123                   (if (funcall search-func match nil t)
1124                       ;; Found a match, update scores.
1125                       (progn
1126                         (setcdr (car articles) (+ score (cdr (car articles))))
1127                         (setq found t)
1128                         (and trace (setq gnus-score-trace 
1129                                          (cons
1130                                           (cons
1131                                            (car-safe
1132                                             (rassq alist gnus-score-cache))
1133                                            kill)
1134                                           gnus-score-trace)))))
1135                   ;; Update expire date
1136                   (cond ((null date))   ;Permanent entry.
1137                         (found          ;Match, update date.
1138                          (gnus-score-set 'touched '(t) alist)
1139                          (setcar (nthcdr 2 kill) now))
1140                         ((< date expire) ;Old entry, remove.
1141                          (gnus-score-set 'touched '(t) alist)
1142                          (setcdr entries (cdr rest))
1143                          (setq rest entries)))
1144                   (setq entries rest)))))
1145           (setq articles (cdr articles)))))))
1146
1147
1148
1149 (defun gnus-score-followup (scores header now expire &optional trace)
1150   ;; Insert the unique article headers in the buffer.
1151   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1152         (current-score-file gnus-current-score-file)
1153         (all-scores scores)
1154         ;; gnus-score-index is used as a free variable.
1155         alike last this art entries alist articles)
1156
1157     ;; Change score file to the adaptive score file.  All entries that
1158     ;; this function makes will be put into this file.
1159     (gnus-score-load-file (gnus-score-file-name 
1160                            gnus-newsgroup-name gnus-adaptive-file-suffix))
1161
1162     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1163           articles gnus-scores-articles)
1164
1165     (erase-buffer)
1166     (while articles
1167       (setq art (car articles)
1168             this (aref (car art) gnus-score-index)
1169             articles (cdr articles))
1170       (if (equal last this)
1171           (setq alike (cons art alike))
1172         (if last
1173             (progn
1174               (insert last ?\n)
1175               (put-text-property (1- (point)) (point) 'articles alike)))
1176         (setq alike (list art)
1177               last this)))
1178     (and last                           ; Bwadr, duplicate code.
1179          (progn
1180            (insert last ?\n)                    
1181            (put-text-property (1- (point)) (point) 'articles alike)))
1182   
1183     ;; Find matches.
1184     (while scores
1185       (setq alist (car scores)
1186             scores (cdr scores)
1187             entries (assoc header alist))
1188       (while (cdr entries)              ;First entry is the header index.
1189         (let* ((rest (cdr entries))             
1190                (kill (car rest))
1191                (match (nth 0 kill))
1192                (type (or (nth 3 kill) 's))
1193                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1194                (date (nth 2 kill))
1195                (found nil)
1196                (mt (aref (symbol-name type) 0))
1197                (case-fold-search 
1198                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1199                (dmt (downcase mt))
1200                (search-func 
1201                 (cond ((= dmt ?r) 're-search-forward)
1202                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1203                       (t (error "Illegal match type: %s" type))))
1204                arts art)
1205           (goto-char (point-min))
1206           (if (= dmt ?e)
1207               (while (funcall search-func match nil t)
1208                 (and (= (progn (beginning-of-line) (point))
1209                         (match-beginning 0))
1210                      (= (progn (end-of-line) (point))
1211                         (match-end 0))
1212                      (progn
1213                        (setq found (setq arts (get-text-property 
1214                                                (point) 'articles)))
1215                        ;; Found a match, update scores.
1216                        (while arts
1217                          (setq art (car arts)
1218                                arts (cdr arts))
1219                          (gnus-score-add-followups 
1220                           (car art) score all-scores)))))
1221             (while (funcall search-func match nil t)
1222               (end-of-line)
1223               (setq found (setq arts (get-text-property (point) 'articles)))
1224               ;; Found a match, update scores.
1225               (while arts
1226                 (setq art (car arts)
1227                       arts (cdr arts))
1228                 (gnus-score-add-followups (car art) score all-scores))))
1229           ;; Update expire date
1230           (cond ((null date))           ;Permanent entry.
1231                 (found                  ;Match, update date.
1232                  (gnus-score-set 'touched '(t) alist)
1233                  (setcar (nthcdr 2 kill) now))
1234                 ((< date expire)        ;Old entry, remove.
1235                  (gnus-score-set 'touched '(t) alist)
1236                  (setcdr entries (cdr rest))
1237                  (setq rest entries)))
1238           (setq entries rest))))
1239     ;; We change the score file back to the previous one.
1240     (gnus-score-load-file current-score-file)))
1241
1242 (defun gnus-score-add-followups (header score scores)
1243   (save-excursion
1244     (set-buffer gnus-summary-buffer)
1245     (let* ((id (mail-header-id header))
1246            (scores (car scores))
1247            entry dont)
1248       ;; Don't enter a score if there already is one.
1249       (while scores
1250         (setq entry (car scores))
1251         (and (equal "references" (car entry))
1252              (or (null (nth 3 (car (cdr entry))))
1253                  (eq 's (nth 3 (car (cdr entry)))))
1254              (progn
1255                (if (assoc id entry)
1256                    (setq dont t))))
1257         (setq scores (cdr scores)))
1258       (or dont
1259           (gnus-summary-score-entry 
1260            "references" id 's score (current-time-string) nil t)))))
1261
1262
1263 (defun gnus-score-string (score-list header now expire &optional trace)
1264   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1265   ;; Update matches entries to NOW and remove unmatched entried older
1266   ;; than EXPIRE.
1267   
1268   ;; Insert the unique article headers in the buffer.
1269   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1270         ;; gnus-score-index is used as a free variable.
1271         alike last this art entries alist articles scores fuzzy)
1272
1273     ;; Sorting the articles costs os O(N*log N) but will allow us to
1274     ;; only match with each unique header.  Thus the actual matching
1275     ;; will be O(M*U) where M is the number of strings to match with,
1276     ;; and U is the number of unique headers.  It is assumed (but
1277     ;; untested) this will be a net win because of the large constant
1278     ;; factor involved with string matching.
1279     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1280           articles gnus-scores-articles)
1281
1282     (erase-buffer)
1283     (while articles
1284       (setq art (car articles)
1285             this (aref (car art) gnus-score-index)
1286             articles (cdr articles))
1287       (if (equal last this)
1288           ;; O(N*H) cons-cells used here, where H is the number of
1289           ;; headers.
1290           (setq alike (cons art alike))
1291         (if last
1292             (progn
1293               ;; Insert the line, with a text property on the
1294               ;; terminating newline refering to the articles with
1295               ;; this line.
1296               (insert last ?\n)
1297               (put-text-property (1- (point)) (point) 'articles alike)))
1298         (setq alike (list art)
1299               last this)))
1300     (and last                           ; Bwadr, duplicate code.
1301          (progn
1302            (insert last ?\n)                    
1303            (put-text-property (1- (point)) (point) 'articles alike)))
1304
1305     ;; Find ordinary matches.
1306     (setq scores score-list) 
1307     (while scores
1308       (setq alist (car scores)
1309             scores (cdr scores)
1310             entries (assoc header alist))
1311       (while (cdr entries)              ;First entry is the header index.
1312         (let* ((rest (cdr entries))             
1313                (kill (car rest))
1314                (match (nth 0 kill))
1315                (type (or (nth 3 kill) 's))
1316                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1317                (date (nth 2 kill))
1318                (found nil)
1319                (mt (aref (symbol-name type) 0))
1320                (case-fold-search 
1321                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1322                (dmt (downcase mt))
1323                (search-func 
1324                 (cond ((= dmt ?r) 're-search-forward)
1325                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1326                       (t (error "Illegal match type: %s" type))))
1327                arts art)
1328           (if (= dmt ?f)
1329               (setq fuzzy t)
1330             ;; Do non-fuzzy matching.
1331             (goto-char (point-min))
1332             (if (= dmt ?e)
1333                 ;; Do exact matching.
1334                 (while (and (not (eobp)) 
1335                             (funcall search-func match nil t))
1336                   (and (= (progn (beginning-of-line) (point))
1337                           (match-beginning 0))
1338                        (= (progn (end-of-line) (point))
1339                           (match-end 0))
1340                        (progn
1341                          (setq found (setq arts (get-text-property 
1342                                                  (point) 'articles)))
1343                          ;; Found a match, update scores.
1344                          (if trace
1345                              (while arts
1346                                (setq art (car arts)
1347                                      arts (cdr arts))
1348                                (setcdr art (+ score (cdr art)))
1349                                (setq gnus-score-trace
1350                                      (cons
1351                                       (cons
1352                                        (car-safe
1353                                         (rassq alist gnus-score-cache))
1354                                        kill)
1355                                       gnus-score-trace)))
1356                            (while arts
1357                              (setq art (car arts)
1358                                    arts (cdr arts))
1359                              (setcdr art (+ score (cdr art)))))))
1360                   (forward-line 1))
1361               ;; Do regexp and substring matching.
1362               (and (string= match "") (setq match "\n"))
1363               (while (and (not (eobp))
1364                           (funcall search-func match nil t))
1365                 (goto-char (match-beginning 0))
1366                 (end-of-line)
1367                 (setq found (setq arts (get-text-property (point) 'articles)))
1368                 ;; Found a match, update scores.
1369                 (if trace
1370                     (while arts
1371                       (setq art (car arts)
1372                             arts (cdr arts))
1373                       (setcdr art (+ score (cdr art)))
1374                       (setq gnus-score-trace
1375                             (cons
1376                              (cons
1377                               (car-safe
1378                                (rassq alist gnus-score-cache))
1379                               kill)
1380                              gnus-score-trace)))
1381                   (while arts
1382                     (setq art (car arts)
1383                           arts (cdr arts))
1384                     (setcdr art (+ score (cdr art)))))
1385                 (forward-line 1)))
1386             ;; Update expire date
1387             (cond ((null date))         ;Permanent entry.
1388                   (found                ;Match, update date.
1389                    (gnus-score-set 'touched '(t) alist)
1390                    (setcar (nthcdr 2 kill) now))
1391                   ((< date expire)      ;Old entry, remove.
1392                    (gnus-score-set 'touched '(t) alist)
1393                    (setcdr entries (cdr rest))
1394                    (setq rest entries))))
1395           (setq entries rest))))
1396   
1397     ;; Find fuzzy matches.
1398     (setq scores (and fuzzy score-list))
1399     (if fuzzy (gnus-simplify-buffer-fuzzy))
1400     (while scores
1401       (setq alist (car scores)
1402             scores (cdr scores)
1403             entries (assoc header alist))
1404       (while (cdr entries)              ;First entry is the header index.
1405         (let* ((rest (cdr entries))             
1406                (kill (car rest))
1407                (match (nth 0 kill))
1408                (type (or (nth 3 kill) 's))
1409                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1410                (date (nth 2 kill))
1411                (found nil)
1412                (mt (aref (symbol-name type) 0))
1413                (case-fold-search 
1414                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1415                (dmt (downcase mt))
1416                (search-func 
1417                 (cond ((= dmt ?r) 're-search-forward)
1418                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1419                       (t (error "Illegal match type: %s" type))))
1420                arts art)
1421           (if (/= dmt ?f)
1422               ()
1423             (goto-char (point-min))
1424             (while (and (not (eobp)) 
1425                         (funcall search-func match nil t))
1426               (and (= (progn (beginning-of-line) (point))
1427                       (match-beginning 0))
1428                    (= (progn (end-of-line) (point))
1429                       (match-end 0))
1430                    (progn
1431                      (setq found (setq arts (get-text-property 
1432                                              (point) 'articles)))
1433                      ;; Found a match, update scores.
1434                      (if trace
1435                          (while arts
1436                            (setq art (car arts)
1437                                  arts (cdr arts))
1438                            (setcdr art (+ score (cdr art)))
1439                            (setq gnus-score-trace
1440                                  (cons
1441                                   (cons
1442                                    (car-safe
1443                                     (rassq alist gnus-score-cache))
1444                                    kill)
1445                                   gnus-score-trace)))
1446                        (while arts
1447                          (setq art (car arts)
1448                                arts (cdr arts))
1449                          (setcdr art (+ score (cdr art)))))))
1450               (forward-line 1))
1451             ;; Update expire date
1452             (cond ((null date))         ;Permanent entry.
1453                   (found                ;Match, update date.
1454                    (gnus-score-set 'touched '(t) alist)
1455                    (setcar (nthcdr 2 kill) now))
1456                   ((< date expire)      ;Old entry, remove.
1457                    (gnus-score-set 'touched '(t) alist)
1458                    (setcdr entries (cdr rest))
1459                    (setq rest entries))))
1460           (setq entries rest))))))
1461
1462 (defun gnus-score-string< (a1 a2)
1463   ;; Compare headers in articles A2 and A2.
1464   ;; The header index used is the free variable `gnus-score-index'.
1465   (string-lessp (aref (car a1) gnus-score-index)
1466                 (aref (car a2) gnus-score-index)))
1467
1468 (defun gnus-score-build-cons (article)
1469   ;; Build a `gnus-newsgroup-scored' type cons from ARTICLE.
1470   (cons (mail-header-number (car article)) (cdr article)))
1471
1472 (defconst gnus-header-index
1473   ;; Name to index alist.
1474   '(("number" 0 gnus-score-integer)
1475     ("subject" 1 gnus-score-string)
1476     ("from" 2 gnus-score-string)
1477     ("date" 3 gnus-score-date)
1478     ("message-id" 4 gnus-score-string) 
1479     ("references" 5 gnus-score-string) 
1480     ("chars" 6 gnus-score-integer) 
1481     ("lines" 7 gnus-score-integer) 
1482     ("xref" 8 gnus-score-string)
1483     ("head" -1 gnus-score-body)
1484     ("body" -1 gnus-score-body)
1485     ("all" -1 gnus-score-body)
1486     ("followup" 2 gnus-score-followup)))
1487
1488 (defun gnus-current-score-file-nondirectory (&optional score-file)
1489   (let ((score-file (or score-file gnus-current-score-file)))
1490     (if score-file 
1491         (gnus-short-group-name (file-name-nondirectory score-file))
1492       "none")))
1493
1494 (defun gnus-score-adaptive ()
1495   (save-excursion
1496     (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
1497            (alist malist)
1498            (date (current-time-string)) 
1499            (data gnus-newsgroup-data)
1500            elem headers match)
1501       ;; First we transform the adaptive rule alist into something
1502       ;; that's faster to process.
1503       (while malist
1504         (setq elem (car malist))
1505         (if (symbolp (car elem))
1506             (setcar elem (symbol-value (car elem))))
1507         (setq elem (cdr elem))
1508         (while elem
1509           (setcdr (car elem) 
1510                   (cons (if (eq (car (car elem)) 'followup)
1511                             "references"
1512                           (symbol-name (car (car elem))))
1513                         (cdr (car elem))))
1514           (setcar (car elem) 
1515                   (intern 
1516                    (concat "gnus-header-" 
1517                            (if (eq (car (car elem)) 'followup)
1518                                "message-id"
1519                              (downcase (symbol-name (car (car elem))))))))
1520           (setq elem (cdr elem)))
1521         (setq malist (cdr malist)))
1522       ;; We change the score file to the adaptive score file.
1523       (gnus-score-load-file (gnus-score-file-name 
1524                              gnus-newsgroup-name gnus-adaptive-file-suffix))
1525       ;; The we score away.
1526       (while data
1527         (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
1528         (if (or (not elem)
1529                 (gnus-data-pseudo-p (car data)))
1530             ()
1531           (when (setq headers (gnus-data-header (car data)))
1532             (while elem 
1533               (setq match (funcall (car (car elem)) headers))
1534               (gnus-summary-score-entry 
1535                (nth 1 (car elem)) match
1536                (cond
1537                 ((numberp match)
1538                  '=)
1539                 ((equal (nth 1 (car elem)) "date")
1540                  'a)
1541                 (t
1542                  ;; Whether we use substring or exact matches are controlled
1543                  ;; here.  
1544                  (if (or (not gnus-score-exact-adapt-limit)
1545                          (< (length match) gnus-score-exact-adapt-limit))
1546                      'e 
1547                    (if (equal (nth 1 (car elem)) "subject")
1548                        'f 's))))
1549                (nth 2 (car elem)) date nil t)
1550               (setq elem (cdr elem)))))
1551         (setq data (cdr data))))))
1552
1553 ;;;
1554 ;;; Score mode.
1555 ;;;
1556
1557 (defvar gnus-score-mode-map nil)
1558 (defvar gnus-score-mode-hook nil)
1559
1560 (if gnus-score-mode-map
1561     ()
1562   (setq gnus-score-mode-map (copy-keymap emacs-lisp-mode-map))
1563   (define-key gnus-score-mode-map "\C-c\C-c" 'gnus-score-edit-done)
1564   (define-key gnus-score-mode-map "\C-c\C-d" 'gnus-score-edit-insert-date))
1565
1566 (defun gnus-score-mode ()
1567   "Mode for editing score files.
1568 This mode is an extended emacs-lisp mode.
1569
1570 \\{gnus-score-mode-map}"
1571   (interactive)
1572   (kill-all-local-variables)
1573   (use-local-map gnus-score-mode-map)
1574   (set-syntax-table emacs-lisp-mode-syntax-table)
1575   (setq major-mode 'gnus-score-mode)
1576   (setq mode-name "Score")
1577   (lisp-mode-variables nil)
1578   (run-hooks 'emacs-lisp-mode-hook 'gnus-score-mode-hook))
1579
1580 (defun gnus-score-edit-insert-date ()
1581   "Insert date in numerical format."
1582   (interactive)
1583   (insert (int-to-string (gnus-day-number (current-time-string)))))
1584
1585 (defun gnus-score-edit-done ()
1586   "Save the score file and return to the summary buffer."
1587   (interactive)
1588   (let ((bufnam (buffer-file-name (current-buffer)))
1589         (winconf gnus-prev-winconf))
1590     (gnus-make-directory (file-name-directory (buffer-file-name)))
1591     (save-buffer)
1592     (kill-buffer (current-buffer))
1593     (gnus-score-remove-from-cache bufnam)
1594     (gnus-score-load-file bufnam)
1595     (and winconf (set-window-configuration winconf))))
1596
1597 (defun gnus-score-find-trace ()
1598   "Find all score rules applied to this article."
1599   (interactive)
1600   (let ((gnus-newsgroup-headers
1601          (list (gnus-summary-article-header)))
1602         (gnus-newsgroup-scored nil)
1603         (buf (current-buffer))
1604         trace)
1605     (setq gnus-score-trace nil)
1606     (gnus-possibly-score-headers 'trace)
1607     (or (setq trace gnus-score-trace)
1608         (error "No score rules apply to the current article."))
1609     (pop-to-buffer "*Gnus Scores*")
1610     (gnus-add-current-to-buffer-list)
1611     (erase-buffer)
1612     (while trace
1613       (insert (format "%S  ->  %s\n"  (cdr (car trace))
1614                       (file-name-nondirectory (car (car trace)))))
1615       (setq trace (cdr trace)))
1616     (goto-char (point-min))
1617     (pop-to-buffer buf)))
1618   
1619 (defun gnus-score-flush-cache ()
1620   "Flush the cache of score files."
1621   (interactive)
1622   (setq gnus-score-cache nil)
1623   (gnus-message 6 "The score cache is now flushed"))
1624
1625 (defun gnus-score-close ()
1626   "Clear all internal score variables."
1627   (setq gnus-score-cache nil
1628         gnus-internal-global-score-files nil))
1629
1630 (provide 'gnus-score)
1631
1632 ;;; gnus-score.el ends here