*** 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     ;; Load the score files.
793     (while score-files
794       (if (stringp (car score-files))
795           ;; It is a string, which means that it's a score file name,
796           ;; so we load the score file and add the score alist to
797           ;; the list of alists.
798           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
799         ;; It is an alist, so we just add it to the list directly.
800         (setq scores (nconc (car score-files) scores)))
801       (setq score-files (cdr score-files)))
802     ;; Prune the score files that are to be excluded, if any.
803     (if (not gnus-scores-exclude-files)
804         ()
805       (let ((s scores)
806             c)
807         (while s
808           (and (setq c (rassq (car s) gnus-score-cache))
809                (member (car c) gnus-scores-exclude-files)
810                (setq scores (delq (car s) scores)))
811           (setq s (cdr s)))))
812     (if (not (and gnus-summary-default-score
813                   scores
814                   (> (length gnus-newsgroup-headers)
815                      (length gnus-newsgroup-scored))))
816         ()
817       (let* ((entries gnus-header-index)
818              (now (gnus-day-number (current-time-string)))
819              (expire (- now gnus-score-expiry-days))
820              (headers gnus-newsgroup-headers)
821              (current-score-file gnus-current-score-file)
822              entry header)
823         (gnus-message 5 "Scoring...")
824         ;; Create articles, an alist of the form `(HEADER . SCORE)'.
825         (while headers
826           (setq header (car headers)
827                 headers (cdr headers))
828           ;; WARNING: The assq makes the function O(N*S) while it could
829           ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
830           ;; and S is (length gnus-newsgroup-scored).
831           (or (assq (mail-header-number header) gnus-newsgroup-scored)
832               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
833                     (cons (cons header (or gnus-summary-default-score 0))
834                           gnus-scores-articles))))
835
836         (save-excursion
837           (set-buffer (get-buffer-create "*Headers*"))
838           (buffer-disable-undo (current-buffer))
839
840           ;; Set the global variant of this variable.
841           (setq gnus-current-score-file current-score-file)
842           ;; score orphans
843           (if gnus-orphan-score 
844               (progn
845                 (setq gnus-score-index 
846                       (nth 1 (assoc "references" gnus-header-index)))
847                 (gnus-score-orphans gnus-orphan-score)))
848           ;; Run each header through the score process.
849           (while entries
850             (setq entry (car entries)
851                   header (nth 0 entry)
852                   entries (cdr entries))
853             (setq gnus-score-index (nth 1 (assoc header gnus-header-index)))
854             (if (< 0 (apply 'max (mapcar
855                                   (lambda (score)
856                                     (length (gnus-score-get header score)))
857                                   scores)))
858                 (funcall (nth 2 entry) scores header now expire trace)))
859           ;; Remove the buffer.
860           (kill-buffer (current-buffer)))
861
862         ;; Add articles to `gnus-newsgroup-scored'.
863         (while gnus-scores-articles
864           (or (= gnus-summary-default-score (cdr (car gnus-scores-articles)))
865               (setq gnus-newsgroup-scored
866                     (cons (cons (mail-header-number 
867                                  (car (car gnus-scores-articles)))
868                                 (cdr (car gnus-scores-articles)))
869                           gnus-newsgroup-scored)))
870           (setq gnus-scores-articles (cdr gnus-scores-articles)))
871
872         (gnus-message 5 "Scoring...done")))))
873
874
875 (defun gnus-get-new-thread-ids (articles)
876   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
877         (refind gnus-score-index)
878         id-list art this tref)
879     (while articles
880       (setq art (car articles)
881             this (aref (car art) index)
882             tref (aref (car art) refind)
883             articles (cdr articles))
884       (if (string-equal tref "")        ;no references line
885           (setq id-list (cons this id-list))))
886     id-list))
887
888 ;; Orphan functions written by plm@atcmp.nl (Peter Mutsaers).
889 (defun gnus-score-orphans (score)
890   (let ((new-thread-ids (gnus-get-new-thread-ids gnus-scores-articles))
891         alike articles art arts this last this-id)
892     
893     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
894           articles gnus-scores-articles)
895
896     ;;more or less the same as in gnus-score-string
897     (erase-buffer)
898     (while articles
899       (setq art (car articles)
900             this (aref (car art) gnus-score-index)
901             articles (cdr articles))
902       ;;completely skip if this is empty (not a child, so not an orphan)
903       (if (not (string= this ""))
904           (if (equal last this)
905               ;; O(N*H) cons-cells used here, where H is the number of
906               ;; headers.
907               (setq alike (cons art alike))
908             (if last
909                 (progn
910                   ;; Insert the line, with a text property on the
911                   ;; terminating newline refering to the articles with
912                   ;; this line.
913                   (insert last ?\n)
914                   (put-text-property (1- (point)) (point) 'articles alike)))
915             (setq alike (list art)
916                   last this))))
917     (and last                           ; Bwadr, duplicate code.
918          (progn
919            (insert last ?\n)                    
920            (put-text-property (1- (point)) (point) 'articles alike)))
921
922     ;; PLM: now delete those lines that contain an entry from new-thread-ids
923     (while new-thread-ids
924       (setq this-id (car new-thread-ids)
925             new-thread-ids (cdr new-thread-ids))
926       (goto-char (point-min))
927       (while (search-forward this-id nil t)
928         ;; found a match. remove this line
929         (beginning-of-line)
930         (kill-line 1)))
931
932     ;; now for each line: update its articles with score by moving to
933     ;; every end-of-line in the buffer and read the articles property
934     (goto-char (point-min))
935     (while (eq 0 (progn
936                    (end-of-line)
937                    (setq arts (get-text-property (point) 'articles))
938                    (while arts
939                      (setq art (car arts)
940                            arts (cdr arts))
941                      (setcdr art (+ score (cdr art))))
942                    (forward-line))))))
943              
944
945 (defun gnus-score-integer (scores header now expire &optional trace)
946   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
947         entries alist)
948
949     ;; Find matches.
950     (while scores
951       (setq alist (car scores)
952             scores (cdr scores)
953             entries (assoc header alist))
954       (while (cdr entries)              ;First entry is the header index.
955         (let* ((rest (cdr entries))             
956                (kill (car rest))
957                (match (nth 0 kill))
958                (type (or (nth 3 kill) '>))
959                (score (or (nth 1 kill) gnus-score-interactive-default-score))
960                (date (nth 2 kill))
961                (found nil)
962                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
963                                    (eq type '>=) (eq type '=))
964                                type
965                              (error "Illegal match type: %s" type)))
966                (articles gnus-scores-articles))
967           ;; Instead of doing all the clever stuff that
968           ;; `gnus-score-string' does to minimize searches and stuff,
969           ;; I will assume that people generally will put so few
970           ;; matches on numbers that any cleverness will take more
971           ;; time than one would gain.
972           (while articles
973             (and (funcall match-func 
974                           (or (aref (car (car articles)) gnus-score-index) 0)
975                           match)
976                  (progn
977                    (and trace (setq gnus-score-trace 
978                                     (cons
979                                      (cons
980                                       (car-safe (rassq alist gnus-score-cache))
981                                       kill)
982                                      gnus-score-trace)))
983                    (setq found t)
984                    (setcdr (car articles) (+ score (cdr (car articles))))))
985             (setq articles (cdr articles)))
986           ;; Update expire date
987           (cond ((null date))           ;Permanent entry.
988                 (found                  ;Match, update date.
989                  (gnus-score-set 'touched '(t) alist)
990                  (setcar (nthcdr 2 kill) now))
991                 ((< date expire)        ;Old entry, remove.
992                  (gnus-score-set 'touched '(t) alist)
993                  (setcdr entries (cdr rest))
994                  (setq rest entries)))
995           (setq entries rest))))))
996
997 (defun gnus-score-date (scores header now expire &optional trace)
998   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
999         entries alist)
1000
1001     ;; Find matches.
1002     (while scores
1003       (setq alist (car scores)
1004             scores (cdr scores)
1005             entries (assoc header alist))
1006       (while (cdr entries)              ;First entry is the header index.
1007         (let* ((rest (cdr entries))             
1008                (kill (car rest))
1009                (match (timezone-make-date-sortable (nth 0 kill)))
1010                (type (or (nth 3 kill) 'before))
1011                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1012                (date (nth 2 kill))
1013                (found nil)
1014                (match-func 
1015                 (cond ((eq type 'after) 'string<)
1016                       ((eq type 'before) 'gnus-string>)
1017                       ((eq type 'at) 'string=)
1018                       (t (error "Illegal match type: %s" type))))
1019                (articles gnus-scores-articles)
1020                l)
1021           ;; Instead of doing all the clever stuff that
1022           ;; `gnus-score-string' does to minimize searches and stuff,
1023           ;; I will assume that people generally will put so few
1024           ;; matches on numbers that any cleverness will take more
1025           ;; time than one would gain.
1026           (while articles
1027             (and
1028              (setq l (aref (car (car articles)) gnus-score-index))
1029              (funcall match-func match (timezone-make-date-sortable l))
1030              (progn
1031                (and trace (setq gnus-score-trace 
1032                                 (cons
1033                                  (cons
1034                                   (car-safe (rassq alist gnus-score-cache))
1035                                   kill)
1036                                  gnus-score-trace)))
1037                (setq found t)
1038                (setcdr (car articles) (+ score (cdr (car articles))))))
1039             (setq articles (cdr articles)))
1040           ;; Update expire date
1041           (cond ((null date))           ;Permanent entry.
1042                 (found                  ;Match, update date.
1043                  (gnus-score-set 'touched '(t) alist)
1044                  (setcar (nthcdr 2 kill) now))
1045                 ((< date expire)        ;Old entry, remove.
1046                  (gnus-score-set 'touched '(t) alist)
1047                  (setcdr entries (cdr rest))
1048                  (setq rest entries)))
1049           (setq entries rest))))))
1050
1051 (defun gnus-score-body (scores header now expire &optional trace)
1052   (save-excursion
1053     (set-buffer nntp-server-buffer)
1054     (save-restriction
1055       (let* ((buffer-read-only nil)
1056              (articles gnus-scores-articles)
1057              (last (mail-header-number (car (car gnus-scores-articles))))
1058              (all-scores scores)
1059              (request-func (cond ((string= "head" (downcase header))
1060                                   'gnus-request-head)
1061                                  ((string= "body" (downcase header))
1062                                   'gnus-request-body)
1063                                  (t 'gnus-request-article)))
1064              entries alist ofunc article)
1065         ;; Not all backends support partial fetching.  In that case,
1066         ;; we just fetch the entire article.
1067         (or (gnus-check-backend-function 
1068              (and (string-match "^gnus-" (symbol-name request-func))
1069                   (intern (substring (symbol-name request-func)
1070                                      (match-end 0))))
1071              gnus-newsgroup-name)
1072             (progn
1073               (setq ofunc request-func)
1074               (setq request-func 'gnus-request-article)))
1075         (while articles
1076           (setq article (mail-header-number (car (car articles))))
1077           (gnus-message 7 "Scoring on article %s of %s..." article last)
1078           (if (not (funcall request-func article gnus-newsgroup-name))
1079               ()
1080             (widen)
1081             (goto-char (point-min))
1082             ;; If just parts of the article is to be searched, but the
1083             ;; backend didn't support partial fetching, we just narrow
1084             ;; to the relevant parts.
1085             (if ofunc
1086                 (if (eq ofunc 'gnus-request-head)
1087                     (narrow-to-region
1088                      (point)
1089                      (or (search-forward "\n\n" nil t) (point-max)))
1090                   (narrow-to-region
1091                    (or (search-forward "\n\n" nil t) (point))
1092                    (point-max))))
1093             (setq scores all-scores)
1094             ;; Find matches.
1095             (while scores
1096               (setq alist (car scores)
1097                     scores (cdr scores)
1098                     entries (assoc header alist))
1099               (while (cdr entries)      ;First entry is the header index.
1100                 (let* ((rest (cdr entries))             
1101                        (kill (car rest))
1102                        (match (nth 0 kill))
1103                        (type (or (nth 3 kill) 's))
1104                        (score (or (nth 1 kill) 
1105                                   gnus-score-interactive-default-score))
1106                        (date (nth 2 kill))
1107                        (found nil)
1108                        (case-fold-search 
1109                         (not (or (eq type 'R) (eq type 'S)
1110                                  (eq type 'Regexp) (eq type 'String))))
1111                        (search-func 
1112                         (cond ((or (eq type 'r) (eq type 'R)
1113                                    (eq type 'regexp) (eq type 'Regexp))
1114                                're-search-forward)
1115                               ((or (eq type 's) (eq type 'S)
1116                                    (eq type 'string) (eq type 'String))
1117                                'search-forward)
1118                               (t
1119                                (error "Illegal match type: %s" type)))))
1120                   (goto-char (point-min))
1121                   (if (funcall search-func match nil t)
1122                       ;; Found a match, update scores.
1123                       (progn
1124                         (setcdr (car articles) (+ score (cdr (car articles))))
1125                         (setq found t)
1126                         (and trace (setq gnus-score-trace 
1127                                          (cons
1128                                           (cons
1129                                            (car-safe
1130                                             (rassq alist gnus-score-cache))
1131                                            kill)
1132                                           gnus-score-trace)))))
1133                   ;; Update expire date
1134                   (cond ((null date))   ;Permanent entry.
1135                         (found          ;Match, update date.
1136                          (gnus-score-set 'touched '(t) alist)
1137                          (setcar (nthcdr 2 kill) now))
1138                         ((< date expire) ;Old entry, remove.
1139                          (gnus-score-set 'touched '(t) alist)
1140                          (setcdr entries (cdr rest))
1141                          (setq rest entries)))
1142                   (setq entries rest)))))
1143           (setq articles (cdr articles)))))))
1144
1145
1146
1147 (defun gnus-score-followup (scores header now expire &optional trace)
1148   ;; Insert the unique article headers in the buffer.
1149   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1150         (current-score-file gnus-current-score-file)
1151         (all-scores scores)
1152         ;; gnus-score-index is used as a free variable.
1153         alike last this art entries alist articles)
1154
1155     ;; Change score file to the adaptive score file.  All entries that
1156     ;; this function makes will be put into this file.
1157     (gnus-score-load-file (gnus-score-file-name 
1158                            gnus-newsgroup-name gnus-adaptive-file-suffix))
1159
1160     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1161           articles gnus-scores-articles)
1162
1163     (erase-buffer)
1164     (while articles
1165       (setq art (car articles)
1166             this (aref (car art) gnus-score-index)
1167             articles (cdr articles))
1168       (if (equal last this)
1169           (setq alike (cons art alike))
1170         (if last
1171             (progn
1172               (insert last ?\n)
1173               (put-text-property (1- (point)) (point) 'articles alike)))
1174         (setq alike (list art)
1175               last this)))
1176     (and last                           ; Bwadr, duplicate code.
1177          (progn
1178            (insert last ?\n)                    
1179            (put-text-property (1- (point)) (point) 'articles alike)))
1180   
1181     ;; Find matches.
1182     (while scores
1183       (setq alist (car scores)
1184             scores (cdr scores)
1185             entries (assoc header alist))
1186       (while (cdr entries)              ;First entry is the header index.
1187         (let* ((rest (cdr entries))             
1188                (kill (car rest))
1189                (match (nth 0 kill))
1190                (type (or (nth 3 kill) 's))
1191                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1192                (date (nth 2 kill))
1193                (found nil)
1194                (mt (aref (symbol-name type) 0))
1195                (case-fold-search 
1196                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1197                (dmt (downcase mt))
1198                (search-func 
1199                 (cond ((= dmt ?r) 're-search-forward)
1200                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1201                       (t (error "Illegal match type: %s" type))))
1202                arts art)
1203           (goto-char (point-min))
1204           (if (= dmt ?e)
1205               (while (funcall search-func match nil t)
1206                 (and (= (progn (beginning-of-line) (point))
1207                         (match-beginning 0))
1208                      (= (progn (end-of-line) (point))
1209                         (match-end 0))
1210                      (progn
1211                        (setq found (setq arts (get-text-property 
1212                                                (point) 'articles)))
1213                        ;; Found a match, update scores.
1214                        (while arts
1215                          (setq art (car arts)
1216                                arts (cdr arts))
1217                          (gnus-score-add-followups 
1218                           (car art) score all-scores)))))
1219             (while (funcall search-func match nil t)
1220               (end-of-line)
1221               (setq found (setq arts (get-text-property (point) 'articles)))
1222               ;; Found a match, update scores.
1223               (while arts
1224                 (setq art (car arts)
1225                       arts (cdr arts))
1226                 (gnus-score-add-followups (car art) score all-scores))))
1227           ;; Update expire date
1228           (cond ((null date))           ;Permanent entry.
1229                 (found                  ;Match, update date.
1230                  (gnus-score-set 'touched '(t) alist)
1231                  (setcar (nthcdr 2 kill) now))
1232                 ((< date expire)        ;Old entry, remove.
1233                  (gnus-score-set 'touched '(t) alist)
1234                  (setcdr entries (cdr rest))
1235                  (setq rest entries)))
1236           (setq entries rest))))
1237     ;; We change the score file back to the previous one.
1238     (gnus-score-load-file current-score-file)))
1239
1240 (defun gnus-score-add-followups (header score scores)
1241   (save-excursion
1242     (set-buffer gnus-summary-buffer)
1243     (let* ((id (mail-header-id header))
1244            (scores (car scores))
1245            entry dont)
1246       ;; Don't enter a score if there already is one.
1247       (while scores
1248         (setq entry (car scores))
1249         (and (equal "references" (car entry))
1250              (or (null (nth 3 (car (cdr entry))))
1251                  (eq 's (nth 3 (car (cdr entry)))))
1252              (progn
1253                (if (assoc id entry)
1254                    (setq dont t))))
1255         (setq scores (cdr scores)))
1256       (or dont
1257           (gnus-summary-score-entry 
1258            "references" id 's score (current-time-string) nil t)))))
1259
1260
1261 (defun gnus-score-string (score-list header now expire &optional trace)
1262   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1263   ;; Update matches entries to NOW and remove unmatched entried older
1264   ;; than EXPIRE.
1265   
1266   ;; Insert the unique article headers in the buffer.
1267   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1268         ;; gnus-score-index is used as a free variable.
1269         alike last this art entries alist articles scores fuzzy)
1270
1271     ;; Sorting the articles costs os O(N*log N) but will allow us to
1272     ;; only match with each unique header.  Thus the actual matching
1273     ;; will be O(M*U) where M is the number of strings to match with,
1274     ;; and U is the number of unique headers.  It is assumed (but
1275     ;; untested) this will be a net win because of the large constant
1276     ;; factor involved with string matching.
1277     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1278           articles gnus-scores-articles)
1279
1280     (erase-buffer)
1281     (while articles
1282       (setq art (car articles)
1283             this (aref (car art) gnus-score-index)
1284             articles (cdr articles))
1285       (if (equal last this)
1286           ;; O(N*H) cons-cells used here, where H is the number of
1287           ;; headers.
1288           (setq alike (cons art alike))
1289         (if last
1290             (progn
1291               ;; Insert the line, with a text property on the
1292               ;; terminating newline refering to the articles with
1293               ;; this line.
1294               (insert last ?\n)
1295               (put-text-property (1- (point)) (point) 'articles alike)))
1296         (setq alike (list art)
1297               last this)))
1298     (and last                           ; Bwadr, duplicate code.
1299          (progn
1300            (insert last ?\n)                    
1301            (put-text-property (1- (point)) (point) 'articles alike)))
1302
1303     ;; Find ordinary matches.
1304     (setq scores score-list) 
1305     (while scores
1306       (setq alist (car scores)
1307             scores (cdr scores)
1308             entries (assoc header alist))
1309       (while (cdr entries)              ;First entry is the header index.
1310         (let* ((rest (cdr entries))             
1311                (kill (car rest))
1312                (match (nth 0 kill))
1313                (type (or (nth 3 kill) 's))
1314                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1315                (date (nth 2 kill))
1316                (found nil)
1317                (mt (aref (symbol-name type) 0))
1318                (case-fold-search 
1319                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1320                (dmt (downcase mt))
1321                (search-func 
1322                 (cond ((= dmt ?r) 're-search-forward)
1323                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1324                       (t (error "Illegal match type: %s" type))))
1325                arts art)
1326           (if (= dmt ?f)
1327               (setq fuzzy t)
1328             ;; Do non-fuzzy matching.
1329             (goto-char (point-min))
1330             (if (= dmt ?e)
1331                 ;; Do exact matching.
1332                 (while (and (not (eobp)) 
1333                             (funcall search-func match nil t))
1334                   (and (= (progn (beginning-of-line) (point))
1335                           (match-beginning 0))
1336                        (= (progn (end-of-line) (point))
1337                           (match-end 0))
1338                        (progn
1339                          (setq found (setq arts (get-text-property 
1340                                                  (point) 'articles)))
1341                          ;; Found a match, update scores.
1342                          (if trace
1343                              (while arts
1344                                (setq art (car arts)
1345                                      arts (cdr arts))
1346                                (setcdr art (+ score (cdr art)))
1347                                (setq gnus-score-trace
1348                                      (cons
1349                                       (cons
1350                                        (car-safe
1351                                         (rassq alist gnus-score-cache))
1352                                        kill)
1353                                       gnus-score-trace)))
1354                            (while arts
1355                              (setq art (car arts)
1356                                    arts (cdr arts))
1357                              (setcdr art (+ score (cdr art)))))))
1358                   (forward-line 1))
1359               ;; Do regexp and substring matching.
1360               (and (string= match "") (setq match "\n"))
1361               (while (and (not (eobp))
1362                           (funcall search-func match nil t))
1363                 (goto-char (match-beginning 0))
1364                 (end-of-line)
1365                 (setq found (setq arts (get-text-property (point) 'articles)))
1366                 ;; Found a match, update scores.
1367                 (if trace
1368                     (while arts
1369                       (setq art (car arts)
1370                             arts (cdr arts))
1371                       (setcdr art (+ score (cdr art)))
1372                       (setq gnus-score-trace
1373                             (cons
1374                              (cons
1375                               (car-safe
1376                                (rassq alist gnus-score-cache))
1377                               kill)
1378                              gnus-score-trace)))
1379                   (while arts
1380                     (setq art (car arts)
1381                           arts (cdr arts))
1382                     (setcdr art (+ score (cdr art)))))
1383                 (forward-line 1)))
1384             ;; Update expire date
1385             (cond ((null date))         ;Permanent entry.
1386                   (found                ;Match, update date.
1387                    (gnus-score-set 'touched '(t) alist)
1388                    (setcar (nthcdr 2 kill) now))
1389                   ((< date expire)      ;Old entry, remove.
1390                    (gnus-score-set 'touched '(t) alist)
1391                    (setcdr entries (cdr rest))
1392                    (setq rest entries))))
1393           (setq entries rest))))
1394   
1395     ;; Find fuzzy matches.
1396     (setq scores (and fuzzy score-list))
1397     (if fuzzy (gnus-simplify-buffer-fuzzy))
1398     (while scores
1399       (setq alist (car scores)
1400             scores (cdr scores)
1401             entries (assoc header alist))
1402       (while (cdr entries)              ;First entry is the header index.
1403         (let* ((rest (cdr entries))             
1404                (kill (car rest))
1405                (match (nth 0 kill))
1406                (type (or (nth 3 kill) 's))
1407                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1408                (date (nth 2 kill))
1409                (found nil)
1410                (mt (aref (symbol-name type) 0))
1411                (case-fold-search 
1412                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1413                (dmt (downcase mt))
1414                (search-func 
1415                 (cond ((= dmt ?r) 're-search-forward)
1416                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1417                       (t (error "Illegal match type: %s" type))))
1418                arts art)
1419           (if (/= dmt ?f)
1420               ()
1421             (goto-char (point-min))
1422             (while (and (not (eobp)) 
1423                         (funcall search-func match nil t))
1424               (and (= (progn (beginning-of-line) (point))
1425                       (match-beginning 0))
1426                    (= (progn (end-of-line) (point))
1427                       (match-end 0))
1428                    (progn
1429                      (setq found (setq arts (get-text-property 
1430                                              (point) 'articles)))
1431                      ;; Found a match, update scores.
1432                      (if trace
1433                          (while arts
1434                            (setq art (car arts)
1435                                  arts (cdr arts))
1436                            (setcdr art (+ score (cdr art)))
1437                            (setq gnus-score-trace
1438                                  (cons
1439                                   (cons
1440                                    (car-safe
1441                                     (rassq alist gnus-score-cache))
1442                                    kill)
1443                                   gnus-score-trace)))
1444                        (while arts
1445                          (setq art (car arts)
1446                                arts (cdr arts))
1447                          (setcdr art (+ score (cdr art)))))))
1448               (forward-line 1))
1449             ;; Update expire date
1450             (cond ((null date))         ;Permanent entry.
1451                   (found                ;Match, update date.
1452                    (gnus-score-set 'touched '(t) alist)
1453                    (setcar (nthcdr 2 kill) now))
1454                   ((< date expire)      ;Old entry, remove.
1455                    (gnus-score-set 'touched '(t) alist)
1456                    (setcdr entries (cdr rest))
1457                    (setq rest entries))))
1458           (setq entries rest))))))
1459
1460 (defun gnus-score-string< (a1 a2)
1461   ;; Compare headers in articles A2 and A2.
1462   ;; The header index used is the free variable `gnus-score-index'.
1463   (string-lessp (aref (car a1) gnus-score-index)
1464                 (aref (car a2) gnus-score-index)))
1465
1466 (defun gnus-score-build-cons (article)
1467   ;; Build a `gnus-newsgroup-scored' type cons from ARTICLE.
1468   (cons (mail-header-number (car article)) (cdr article)))
1469
1470 (defconst gnus-header-index
1471   ;; Name to index alist.
1472   '(("number" 0 gnus-score-integer)
1473     ("subject" 1 gnus-score-string)
1474     ("from" 2 gnus-score-string)
1475     ("date" 3 gnus-score-date)
1476     ("message-id" 4 gnus-score-string) 
1477     ("references" 5 gnus-score-string) 
1478     ("chars" 6 gnus-score-integer) 
1479     ("lines" 7 gnus-score-integer) 
1480     ("xref" 8 gnus-score-string)
1481     ("head" -1 gnus-score-body)
1482     ("body" -1 gnus-score-body)
1483     ("all" -1 gnus-score-body)
1484     ("followup" 2 gnus-score-followup)))
1485
1486 (defun gnus-current-score-file-nondirectory (&optional score-file)
1487   (let ((score-file (or score-file gnus-current-score-file)))
1488     (if score-file 
1489         (gnus-short-group-name (file-name-nondirectory score-file))
1490       "none")))
1491
1492 (defun gnus-score-adaptive ()
1493   (save-excursion
1494     (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
1495            (alist malist)
1496            (date (current-time-string)) 
1497            elem headers match)
1498       ;; First we transform the adaptive rule alist into something
1499       ;; that's faster to process.
1500       (while malist
1501         (setq elem (car malist))
1502         (if (symbolp (car elem))
1503             (setcar elem (symbol-value (car elem))))
1504         (setq elem (cdr elem))
1505         (while elem
1506           (setcdr (car elem) 
1507                   (cons (symbol-name (car (car elem))) (cdr (car elem))))
1508           (setcar (car elem) 
1509                   (intern 
1510                    (concat "gnus-header-" 
1511                            (downcase (symbol-name (car (car elem)))))))
1512           (setq elem (cdr elem)))
1513         (setq malist (cdr malist)))
1514       ;; We change the score file to the adaptive score file.
1515       (gnus-score-load-file (gnus-score-file-name 
1516                              gnus-newsgroup-name gnus-adaptive-file-suffix))
1517       ;; The we score away.
1518       (goto-char (point-min))
1519       (while (not (eobp))
1520         (setq elem (cdr (assq (gnus-summary-article-mark) alist)))
1521         (if (or (not elem)
1522                 (get-text-property (point) 'gnus-pseudo))
1523             ()
1524           (setq headers (gnus-summary-article-header))
1525           (while (and elem headers)
1526             (setq match (funcall (car (car elem)) headers))
1527             (gnus-summary-score-entry 
1528              (nth 1 (car elem)) match
1529              (cond
1530               ((numberp match)
1531                '=)
1532               ((equal (nth 1 (car elem)) "date")
1533                'a)
1534               (t
1535                ;; Whether we use substring or exact matches are controlled
1536                ;; here.  
1537                (if (or (not gnus-score-exact-adapt-limit)
1538                        (< (length match) gnus-score-exact-adapt-limit))
1539                    'e 
1540                  (if (equal (nth 1 (car elem)) "subject")
1541                      'f 's))))
1542              (nth 2 (car elem)) date nil t)
1543             (setq elem (cdr elem))))
1544         (forward-line 1)))))
1545
1546 (defun gnus-score-remove-lines-adaptive (marks)
1547   (save-excursion
1548     (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
1549            (alist malist)
1550            (date (current-time-string)) 
1551            (cur-score gnus-current-score-file)
1552            elem headers match)
1553       ;; First we transform the adaptive rule alist into something
1554       ;; that's faster to process.
1555       (while malist
1556         (setq elem (car malist))
1557         (if (symbolp (car elem))
1558             (setcar elem (symbol-value (car elem))))
1559         (setq elem (cdr elem))
1560         (while elem
1561           (setcdr (car elem) 
1562                   (cons (symbol-name (car (car elem))) (cdr (car elem))))
1563           (setcar (car elem) 
1564                   (intern 
1565                    (concat "gnus-header-" 
1566                            (downcase (symbol-name (car (car elem)))))))
1567           (setq elem (cdr elem)))
1568         (setq malist (cdr malist)))
1569       ;; The we score away.
1570       (goto-char (point-min))
1571       ;; We change the score file to the adaptive score file.
1572       (gnus-score-load-file (gnus-score-file-name 
1573                              gnus-newsgroup-name gnus-adaptive-file-suffix))
1574       (while (re-search-forward marks nil t)
1575         (beginning-of-line)
1576         (setq elem (cdr (assq (gnus-summary-article-mark) alist)))
1577         (if (or (not elem)
1578                 (get-text-property (gnus-point-at-bol) 'gnus-pseudo))
1579             ()
1580           (setq headers (gnus-summary-article-header))
1581           (while elem
1582             (setq match (funcall (car (car elem)) headers))
1583             (gnus-summary-score-entry 
1584              (nth 1 (car elem)) match
1585              (if (or (not gnus-score-exact-adapt-limit)
1586                      (< (length match) gnus-score-exact-adapt-limit))
1587                  'e 's) 
1588              (nth 2 (car elem)) date nil t)
1589             (setq elem (cdr elem)))))
1590       ;; Switch back to the old score file.
1591       (gnus-score-load-file cur-score))))
1592
1593 ;;;
1594 ;;; Score mode.
1595 ;;;
1596
1597 (defvar gnus-score-mode-map nil)
1598 (defvar gnus-score-mode-hook nil)
1599
1600 (if gnus-score-mode-map
1601     ()
1602   (setq gnus-score-mode-map (copy-keymap emacs-lisp-mode-map))
1603   (define-key gnus-score-mode-map "\C-c\C-c" 'gnus-score-edit-done)
1604   (define-key gnus-score-mode-map "\C-c\C-d" 'gnus-score-edit-insert-date))
1605
1606 (defun gnus-score-mode ()
1607   "Mode for editing score files.
1608 This mode is an extended emacs-lisp mode.
1609
1610 \\{gnus-score-mode-map}"
1611   (interactive)
1612   (kill-all-local-variables)
1613   (use-local-map gnus-score-mode-map)
1614   (set-syntax-table emacs-lisp-mode-syntax-table)
1615   (setq major-mode 'gnus-score-mode)
1616   (setq mode-name "Score")
1617   (lisp-mode-variables nil)
1618   (run-hooks 'emacs-lisp-mode-hook 'gnus-score-mode-hook))
1619
1620 (defun gnus-score-edit-insert-date ()
1621   "Insert date in numerical format."
1622   (interactive)
1623   (insert (int-to-string (gnus-day-number (current-time-string)))))
1624
1625 (defun gnus-score-edit-done ()
1626   "Save the score file and return to the summary buffer."
1627   (interactive)
1628   (let ((bufnam (buffer-file-name (current-buffer)))
1629         (winconf gnus-prev-winconf))
1630     (gnus-make-directory (file-name-directory (buffer-file-name)))
1631     (save-buffer)
1632     (kill-buffer (current-buffer))
1633     (gnus-score-remove-from-cache bufnam)
1634     (gnus-score-load-file bufnam)
1635     (and winconf (set-window-configuration winconf))))
1636
1637 (defun gnus-score-find-trace ()
1638   "Find all score rules applied to this article."
1639   (interactive)
1640   (let ((gnus-newsgroup-headers
1641          (list (gnus-summary-article-header)))
1642         (gnus-newsgroup-scored nil)
1643         (buf (current-buffer))
1644         trace)
1645     (setq gnus-score-trace nil)
1646     (gnus-possibly-score-headers 'trace)
1647     (or (setq trace gnus-score-trace)
1648         (error "No score rules apply to the current article."))
1649     (pop-to-buffer "*Gnus Scores*")
1650     (gnus-add-current-to-buffer-list)
1651     (erase-buffer)
1652     (while trace
1653       (insert (format "%S  ->  %s\n"  (cdr (car trace))
1654                       (file-name-nondirectory (car (car trace)))))
1655       (setq trace (cdr trace)))
1656     (goto-char (point-min))
1657     (pop-to-buffer buf)))
1658   
1659 (defun gnus-score-flush-cache ()
1660   "Flush the cache of score files."
1661   (interactive)
1662   (setq gnus-score-cache nil)
1663   (gnus-message 6 "The score cache is now flushed"))
1664
1665 (defun gnus-score-close ()
1666   "Clear all internal score variables."
1667   (setq gnus-score-cache nil
1668         gnus-internal-global-score-files nil))
1669
1670 (provide 'gnus-score)
1671
1672 ;;; gnus-score.el ends here