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