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