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