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