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