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