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