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