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