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