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