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