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