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