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