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