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