*** empty log message ***
[gnus] / lisp / gnus-score.el
1 ;;; gnus-score.el --- scoring code for Gnus
2 ;; Copyright (C) 1995,96 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 the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (require 'gnus-load)
30 (require 'gnus-sum)
31 (require 'gnus-range)
32
33 (defvar gnus-global-score-files nil
34   "*List of global score files and directories.
35 Set this variable if you want to use people's score files.  One entry
36 for each score file or each score file directory.  Gnus will decide
37 by itself what score files are applicable to which group.
38
39 Say you want to use the single score file
40 \"/ftp.ifi.uio.no@ftp:/pub/larsi/ding/score/soc.motss.SCORE\" and all
41 score files in the \"/ftp.some-where:/pub/score\" directory.
42
43  (setq gnus-global-score-files
44        '(\"/ftp.ifi.uio.no:/pub/larsi/ding/score/soc.motss.SCORE\"
45          \"/ftp.some-where:/pub/score\"))")
46
47 (defvar gnus-score-file-single-match-alist nil
48   "*Alist mapping regexps to lists of score files.
49 Each element of this alist should be of the form
50         (\"REGEXP\" [ \"SCORE-FILE-1\" ] [ \"SCORE-FILE-2\" ] ... )
51
52 If the name of a group is matched by REGEXP, the corresponding scorefiles
53 will be used for that group.
54 The first match found is used, subsequent matching entries are ignored (to
55 use multiple matches, see gnus-score-file-multiple-match-alist).
56
57 These score files are loaded in addition to any files returned by
58 gnus-score-find-score-files-function (which see).")
59
60 (defvar gnus-score-file-multiple-match-alist nil
61   "*Alist mapping regexps to lists of score files.
62 Each element of this alist should be of the form
63         (\"REGEXP\" [ \"SCORE-FILE-1\" ] [ \"SCORE-FILE-2\" ] ... )
64
65 If the name of a group is matched by REGEXP, the corresponding scorefiles
66 will be used for that group.
67 If multiple REGEXPs match a group, the score files corresponding to each
68 match will be used (for only one match to be used, see
69 gnus-score-file-single-match-alist).
70
71 These score files are loaded in addition to any files returned by
72 gnus-score-find-score-files-function (which see).")
73
74 (defvar gnus-score-file-suffix "SCORE"
75   "*Suffix of the score files.")
76
77 (defvar gnus-adaptive-file-suffix "ADAPT"
78   "*Suffix of the adaptive score files.")
79
80 (defvar gnus-score-find-score-files-function 'gnus-score-find-bnews
81   "*Function used to find score files.
82 The function will be called with the group name as the argument, and
83 should return a list of score files to apply to that group.  The score
84 files do not actually have to exist.
85
86 Predefined values are:
87
88 gnus-score-find-single: Only apply the group's own score file.
89 gnus-score-find-hierarchical: Also apply score files from parent groups.
90 gnus-score-find-bnews: Apply score files whose names matches.
91
92 See the documentation to these functions for more information.
93
94 This variable can also be a list of functions to be called.  Each
95 function should either return a list of score files, or a list of
96 score alists.")
97
98 (defvar gnus-score-interactive-default-score 1000
99   "*Scoring commands will raise/lower the score with this number as the default.")
100
101 (defvar gnus-score-expiry-days 7
102   "*Number of days before unused score file entries are expired.
103 If this variable is nil, no score file entries will be expired.")
104
105 (defvar gnus-update-score-entry-dates t
106   "*In non-nil, update matching score entry dates.
107 If this variable is nil, then score entries that provide matches
108 will be expired along with non-matching score entries.")
109
110 (defvar gnus-orphan-score nil
111   "*All orphans get this score added.  Set in the score file.")
112
113 (defvar gnus-decay-scores nil
114   "*If non-nil, decay non-permanent scores.")
115
116 (defvar gnus-decay-score-function 'gnus-decay-score
117   "*Function called to decay a score.
118 It is called with one parameter -- the score to be decayed.")
119
120 (defvar gnus-score-decay-constant 3
121   "*Decay all \"small\" scores with this amount.")
122
123 (defvar gnus-score-decay-scale .05
124   "*Decay all \"big\" scores with this factor.")
125
126 (defvar gnus-home-score-file nil
127   "Variable to control where interactive score entries are to go.
128 It can be:
129
130  * A string
131    This file file will be used as the home score file.
132
133  * A function
134    The result of this function will be used as the home score file.
135
136  * A list
137    The elements in this list can be:
138
139    * `(regexp file-name ...)'
140      If the `regexp' matches the group name, the first `file-name' will
141      will be used as the home score file.  (Multiple filenames are
142      allowed so that one may use gnus-score-file-single-match-alist to
143      set this variable.)
144
145    * A function.
146      If the function returns non-nil, the result will be used
147      as the home score file.
148
149    * A string.
150      Use the string as the home score file.
151
152    The list will be traversed from the beginning towards the end looking
153    for matches.")
154
155 (defvar gnus-home-adapt-file nil
156   "Variable to control where new adaptive score entries are to go.
157 This variable allows the same syntax as `gnus-home-score-file'.")
158
159 (defvar gnus-default-adaptive-score-alist  
160   '((gnus-kill-file-mark)
161     (gnus-unread-mark)
162     (gnus-read-mark (from 3) (subject 30))
163     (gnus-catchup-mark (subject -10))
164     (gnus-killed-mark (from -1) (subject -20))
165     (gnus-del-mark (from -2) (subject -15)))
166 "*Alist of marks and scores.")
167
168 (defvar gnus-ignored-adaptive-words nil
169   "*List of words to be ignored when doing adaptive word scoring.")
170
171 (defvar gnus-default-ignored-adaptive-words
172   '("a" "i" "the" "to" "of" "and" "in" "is" "it" "for" "that" "if" "you"
173     "this" "be" "on" "with" "not" "have" "are" "or" "as" "from" "can"
174     "but" "by" "at" "an" "will" "no" "all" "was" "do" "there" "my" "one"
175     "so" "we" "they" "what" "would" "any" "which" "about" "get" "your"
176     "use" "some" "me" "then" "name" "like" "out" "when" "up" "time"
177     "other" "more" "only" "just" "end" "also" "know" "how" "new" "should"
178     "been" "than" "them" "he" "who" "make" "may" "people" "these" "now"
179     "their" "here" "into" "first" "could" "way" "had" "see" "work" "well"
180     "were" "two" "very" "where" "while" "us" "because" "good" "same"
181     "even" "much" "most" "many" "such" "long" "his" "over" "last" "since"
182     "right" "before" "our" "without" "too" "those" "why" "must" "part"
183     "being" "current" "back" "still" "go" "point" "value" "each" "did"
184     "both" "true" "off" "say" "another" "state" "might" "under" "start"
185     "try"
186
187     "re")
188   "Default list of words to be ignored when doing adaptive word scoring.")
189
190 (defvar gnus-default-adaptive-word-score-alist  
191   `((,gnus-read-mark . 30)
192     (,gnus-catchup-mark . -10)
193     (,gnus-killed-mark . -20)
194     (,gnus-del-mark . -15))
195 "*Alist of marks and scores.")
196
197 (defvar gnus-score-mimic-keymap nil
198   "*Have the score entry functions pretend that they are a keymap.")
199
200 (defvar gnus-score-exact-adapt-limit 10
201   "*Number that says how long a match has to be before using substring matching.
202 When doing adaptive scoring, one normally uses fuzzy or substring
203 matching.  However, if the header one matches is short, the possibility
204 for false positives is great, so if the length of the match is less
205 than this variable, exact matching will be used.
206
207 If this variable is nil, exact matching will always be used.")
208
209 (defvar gnus-score-uncacheable-files "ADAPT$"
210   "*All score files that match this regexp will not be cached.")
211
212 (defvar gnus-score-default-header nil
213   "Default header when entering new scores.
214
215 Should be one of the following symbols.
216
217  a: from
218  s: subject
219  b: body
220  h: head
221  i: message-id
222  t: references
223  x: xref
224  l: lines
225  d: date
226  f: followup
227
228 If nil, the user will be asked for a header.")
229
230 (defvar gnus-score-default-type nil
231   "Default match type when entering new scores.
232
233 Should be one of the following symbols.
234
235  s: substring
236  e: exact string
237  f: fuzzy string
238  r: regexp string
239  b: before date
240  a: at date
241  n: this date
242  <: less than number
243  >: greater than number
244  =: equal to number
245
246 If nil, the user will be asked for a match type.")
247
248 (defvar gnus-score-default-fold nil
249   "Use case folding for new score file entries iff not nil.")
250
251 (defvar gnus-score-default-duration nil
252   "Default duration of effect when entering new scores.
253
254 Should be one of the following symbols.
255
256  t: temporary
257  p: permanent
258  i: immediate
259
260 If nil, the user will be asked for a duration.")
261
262 (defvar gnus-score-after-write-file-function nil
263   "*Function called with the name of the score file just written to disk.")
264
265 \f
266
267 ;; Internal variables.
268
269 (defvar gnus-adaptive-word-syntax-table
270   (let ((table (copy-syntax-table (standard-syntax-table)))
271         (numbers '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9)))
272     (while numbers
273       (modify-syntax-entry (pop numbers) " " table))
274     (modify-syntax-entry ?' "w" table)
275     table)
276   "Syntax table used when doing adaptive word scoring.")
277
278 (defvar gnus-scores-exclude-files nil)
279 (defvar gnus-internal-global-score-files nil)
280 (defvar gnus-score-file-list nil)
281
282 (defvar gnus-short-name-score-file-cache nil)
283
284 (defvar gnus-score-help-winconf nil)
285 (defvar gnus-adaptive-score-alist gnus-default-adaptive-score-alist)
286 (defvar gnus-adaptive-word-score-alist gnus-default-adaptive-word-score-alist)
287 (defvar gnus-score-trace nil)
288 (defvar gnus-score-edit-buffer nil)
289
290 (defvar gnus-score-alist nil
291   "Alist containing score information.
292 The keys can be symbols or strings.  The following symbols are defined. 
293
294 touched: If this alist has been modified.
295 mark:    Automatically mark articles below this.
296 expunge: Automatically expunge articles below this.
297 files:   List of other score files to load when loading this one.
298 eval:    Sexp to be evaluated when the score file is loaded.
299
300 String entries have the form (HEADER (MATCH TYPE SCORE DATE) ...) 
301 where HEADER is the header being scored, MATCH is the string we are
302 looking for, TYPE is a flag indicating whether it should use regexp or
303 substring matching, SCORE is the score to add and DATE is the date
304 of the last successful match.")
305
306 (defvar gnus-score-cache nil)
307 (defvar gnus-scores-articles nil)
308 (defvar gnus-score-index nil)
309
310
311 (defconst gnus-header-index
312   ;; Name to index alist.
313   '(("number" 0 gnus-score-integer)
314     ("subject" 1 gnus-score-string)
315     ("from" 2 gnus-score-string)
316     ("date" 3 gnus-score-date)
317     ("message-id" 4 gnus-score-string) 
318     ("references" 5 gnus-score-string) 
319     ("chars" 6 gnus-score-integer) 
320     ("lines" 7 gnus-score-integer) 
321     ("xref" 8 gnus-score-string)
322     ("head" -1 gnus-score-body)
323     ("body" -1 gnus-score-body)
324     ("all" -1 gnus-score-body)
325     ("followup" 2 gnus-score-followup)
326     ("thread" 5 gnus-score-thread)))
327
328 (eval-and-compile
329   (autoload 'gnus-uu-ctl-map "gnus-uu" nil nil 'keymap))
330
331 ;;; Summary mode score maps.
332
333 (gnus-define-keys (gnus-summary-score-map "V" gnus-summary-mode-map)
334   "s" gnus-summary-set-score
335   "a" gnus-summary-score-entry
336   "S" gnus-summary-current-score
337   "c" gnus-score-change-score-file
338   "m" gnus-score-set-mark-below
339   "x" gnus-score-set-expunge-below
340   "R" gnus-summary-rescore
341   "e" gnus-score-edit-current-scores
342   "f" gnus-score-edit-file
343   "F" gnus-score-flush-cache
344   "t" gnus-score-find-trace
345   "w" gnus-score-find-favourite-words
346   "C" gnus-score-customize)
347
348 ;; Summary score file commands
349
350 ;; Much modification of the kill (ahem, score) code and lots of the
351 ;; functions are written by Per Abrahamsen <amanda@iesd.auc.dk>.
352
353 (defun gnus-summary-lower-score (&optional score)
354   "Make a score entry based on the current article.
355 The user will be prompted for header to score on, match type,
356 permanence, and the string to be used.  The numerical prefix will be
357 used as score."
358   (interactive "P")
359   (gnus-summary-increase-score (- (gnus-score-default score))))
360
361 (defvar gnus-score-default-header nil
362   "*The default header to score on when entering a score rule interactively.")
363
364 (defvar gnus-score-default-type nil
365   "*The default score type to use when entering a score rule interactively.")
366
367 (defvar gnus-score-default-duration nil
368   "*The default score duration to use on when entering a score rule interactively.")
369
370 (defun gnus-score-kill-help-buffer ()
371   (when (get-buffer "*Score Help*")
372     (kill-buffer "*Score Help*")
373     (and gnus-score-help-winconf
374          (set-window-configuration gnus-score-help-winconf))))
375
376 (defun gnus-summary-increase-score (&optional score)
377   "Make a score entry based on the current article.
378 The user will be prompted for header to score on, match type,
379 permanence, and the string to be used.  The numerical prefix will be
380 used as score."
381   (interactive "P")
382   (gnus-set-global-variables)
383   (let* ((nscore (gnus-score-default score))
384          (prefix (if (< nscore 0) ?L ?I))
385          (increase (> nscore 0))
386          (char-to-header 
387           '((?a "from" nil nil string)
388             (?s "subject" nil nil string)
389             (?b "body" "" nil body-string)
390             (?h "head" "" nil body-string)
391             (?i "message-id" nil t string)
392             (?t "references" "message-id" nil string)
393             (?x "xref" nil nil string)
394             (?l "lines" nil nil number)
395             (?d "date" nil nil date)
396             (?f "followup" nil nil string)
397             (?T "thread" nil nil string)))
398          (char-to-type
399           '((?s s "substring" string)
400             (?e e "exact string" string)
401             (?f f "fuzzy string" string)
402             (?r r "regexp string" string)
403             (?z s "substring" body-string)
404             (?p s "regexp string" body-string)
405             (?b before "before date" date)
406             (?a at "at date" date) 
407             (?n now "this date" date)
408             (?< < "less than number" number)
409             (?> > "greater than number" number) 
410             (?= = "equal to number" number)))
411          (char-to-perm
412           (list (list ?t (current-time-string) "temporary") 
413                 '(?p perm "permanent") '(?i now "immediate")))
414          (mimic gnus-score-mimic-keymap)
415          (hchar (and gnus-score-default-header 
416                      (aref (symbol-name gnus-score-default-header) 0)))
417          (tchar (and gnus-score-default-type
418                      (aref (symbol-name gnus-score-default-type) 0)))
419          (pchar (and gnus-score-default-duration
420                      (aref (symbol-name gnus-score-default-duration) 0)))
421          entry temporary type match)
422     
423     (unwind-protect
424         (progn
425
426           ;; First we read the header to score.
427           (while (not hchar)
428             (if mimic
429                 (progn 
430                   (sit-for 1)
431                   (message "%c-" prefix))
432               (message "%s header (%s?): " (if increase "Increase" "Lower")
433                        (mapconcat (lambda (s) (char-to-string (car s)))
434                                   char-to-header "")))
435             (setq hchar (read-char))
436             (when (or (= hchar ??) (= hchar ?\C-h))
437               (setq hchar nil)
438               (gnus-score-insert-help "Match on header" char-to-header 1)))
439
440           (gnus-score-kill-help-buffer)
441           (unless (setq entry (assq (downcase hchar) char-to-header))
442             (if mimic (error "%c %c" prefix hchar) (error "")))
443
444           (when (/= (downcase hchar) hchar)
445             ;; This was a majuscule, so we end reading and set the defaults.
446             (if mimic (message "%c %c" prefix hchar) (message ""))
447             (setq tchar (or tchar ?s)
448                   pchar (or pchar ?t)))
449     
450           ;; We continue reading - the type.
451           (while (not tchar)
452             (if mimic
453                 (progn
454                   (sit-for 1) (message "%c %c-" prefix hchar))
455               (message "%s header '%s' with match type (%s?): "
456                        (if increase "Increase" "Lower")
457                        (nth 1 entry)
458                        (mapconcat (lambda (s) 
459                                     (if (eq (nth 4 entry) 
460                                             (nth 3 s))
461                                         (char-to-string (car s))
462                                       ""))
463                                   char-to-type "")))
464             (setq tchar (read-char))
465             (when (or (= tchar ??) (= tchar ?\C-h))
466               (setq tchar nil)
467               (gnus-score-insert-help
468                "Match type"
469                (delq nil
470                      (mapcar (lambda (s) 
471                                (if (eq (nth 4 entry) 
472                                        (nth 3 s))
473                                    s nil))
474                              char-to-type ))
475                2)))
476
477           (gnus-score-kill-help-buffer)
478           (unless (setq type (nth 1 (assq (downcase tchar) char-to-type)))
479             (if mimic (error "%c %c" prefix hchar) (error "")))
480
481           (when (/= (downcase tchar) tchar)
482             ;; It was a majuscule, so we end reading and use the default.
483             (if mimic (message "%c %c %c" prefix hchar tchar)
484               (message ""))
485             (setq pchar (or pchar ?p)))
486
487           ;; We continue reading.
488           (while (not pchar)
489             (if mimic
490                 (progn
491                   (sit-for 1) (message "%c %c %c-" prefix hchar tchar))
492               (message "%s permanence (%s?): " (if increase "Increase" "Lower")
493                        (mapconcat (lambda (s) (char-to-string (car s)))
494                                   char-to-perm "")))
495             (setq pchar (read-char))
496             (when (or (= pchar ??) (= pchar ?\C-h))
497               (setq pchar nil)
498               (gnus-score-insert-help "Match permanence" char-to-perm 2)))
499
500           (gnus-score-kill-help-buffer)
501           (if mimic (message "%c %c %c" prefix hchar tchar pchar)
502             (message ""))
503           (unless (setq temporary (cadr (assq pchar char-to-perm)))
504             (if mimic 
505                 (error "%c %c %c %c" prefix hchar tchar pchar)
506               (error ""))))
507       ;; Always kill the score help buffer.
508       (gnus-score-kill-help-buffer))
509
510     ;; We have all the data, so we enter this score.
511     (setq match (if (string= (nth 2 entry) "") ""
512                   (gnus-summary-header (or (nth 2 entry) (nth 1 entry)))))
513       
514     ;; Modify the match, perhaps.
515     (cond 
516      ((equal (nth 1 entry) "xref")
517       (when (string-match "^Xref: *" match)
518         (setq match (substring match (match-end 0))))
519       (when (string-match "^[^:]* +" match)
520         (setq match (substring match (match-end 0))))))
521     
522     (when (memq type '(r R regexp Regexp))
523       (setq match (regexp-quote match)))
524
525     (gnus-summary-score-entry
526      (nth 1 entry)                      ; Header
527      match                              ; Match
528      type                               ; Type
529      (if (eq 's score) nil score)       ; Score
530      (if (eq 'perm temporary)           ; Temp
531          nil
532        temporary)
533      (not (nth 3 entry)))               ; Prompt
534     ))
535   
536 (defun gnus-score-insert-help (string alist idx)
537   (setq gnus-score-help-winconf (current-window-configuration))
538   (save-excursion
539     (set-buffer (get-buffer-create "*Score Help*"))
540     (buffer-disable-undo (current-buffer))
541     (delete-windows-on (current-buffer))
542     (erase-buffer)
543     (insert string ":\n\n")
544     (let ((max -1)
545           (list alist)
546           (i 0)
547           n width pad format)
548       ;; find the longest string to display
549       (while list
550         (setq n (length (nth idx (car list))))
551         (or (> max n)
552             (setq max n))
553         (setq list (cdr list)))
554       (setq max (+ max 4))              ; %c, `:', SPACE, a SPACE at end
555       (setq n (/ (1- (window-width)) max)) ; items per line
556       (setq width (/ (1- (window-width)) n)) ; width of each item
557       ;; insert `n' items, each in a field of width `width' 
558       (while alist
559         (if (< i n)
560             ()
561           (setq i 0)
562           (delete-char -1)              ; the `\n' takes a char
563           (insert "\n"))
564         (setq pad (- width 3))
565         (setq format (concat "%c: %-" (int-to-string pad) "s"))
566         (insert (format format (caar alist) (nth idx (car alist))))
567         (setq alist (cdr alist))
568         (setq i (1+ i))))
569     ;; display ourselves in a small window at the bottom
570     (gnus-appt-select-lowest-window)
571     (split-window)
572     (pop-to-buffer "*Score Help*")
573     (let ((window-min-height 1))
574       (shrink-window-if-larger-than-buffer))
575     (select-window (get-buffer-window gnus-summary-buffer))))
576   
577 (defun gnus-summary-header (header &optional no-err)
578   ;; Return HEADER for current articles, or error.
579   (let ((article (gnus-summary-article-number))
580         headers)
581     (if article
582         (if (and (setq headers (gnus-summary-article-header article))
583                  (vectorp headers))
584             (aref headers (nth 1 (assoc header gnus-header-index)))
585           (if no-err
586               nil
587             (error "Pseudo-articles can't be scored")))
588       (if no-err
589           (error "No article on current line")
590         nil))))
591
592 (defun gnus-newsgroup-score-alist ()
593   (or
594    (let ((param-file (gnus-group-find-parameter 
595                       gnus-newsgroup-name 'score-file)))
596      (when param-file
597        (gnus-score-load param-file)))
598    (gnus-score-load
599     (gnus-score-file-name gnus-newsgroup-name)))
600   gnus-score-alist)
601
602 (defsubst gnus-score-get (symbol &optional alist)
603   ;; Get SYMBOL's definition in ALIST.
604   (cdr (assoc symbol 
605               (or alist 
606                   gnus-score-alist
607                   (gnus-newsgroup-score-alist)))))
608
609 (defun gnus-summary-score-entry (header match type score date
610                                         &optional prompt silent)
611   "Enter score file entry.
612 HEADER is the header being scored.
613 MATCH is the string we are looking for.
614 TYPE is the match type: substring, regexp, exact, fuzzy.
615 SCORE is the score to add.
616 DATE is the expire date, or nil for no expire, or 'now for immediate expire.
617 If optional argument `PROMPT' is non-nil, allow user to edit match.
618 If optional argument `SILENT' is nil, show effect of score entry."
619   (interactive
620    (list (completing-read "Header: "
621                           gnus-header-index
622                           (lambda (x) (fboundp (nth 2 x)))
623                           t)
624          (read-string "Match: ")
625          (if (y-or-n-p "Use regexp match? ") 'r 's)
626          (and current-prefix-arg
627               (prefix-numeric-value current-prefix-arg))
628          (cond ((not (y-or-n-p "Add to score file? "))
629                 'now)
630                ((y-or-n-p "Expire kill? ")
631                 (current-time-string))
632                (t nil))))
633   ;; Regexp is the default type.
634   (if (eq type t) (setq type 'r))
635   ;; Simplify matches...
636   (cond ((or (eq type 'r) (eq type 's) (eq type nil))
637          (setq match (if match (gnus-simplify-subject-re match) "")))
638         ((eq type 'f)
639          (setq match (gnus-simplify-subject-fuzzy match))))
640   (let ((score (gnus-score-default score))
641         (header (format "%s" (downcase header)))
642         new)
643     (when prompt
644       (setq match (read-string 
645                    (format "Match %s on %s, %s: " 
646                            (cond ((eq date 'now)
647                                   "now")
648                                  ((stringp date)
649                                   "temp")
650                                  (t "permanent"))
651                            header
652                            (if (< score 0) "lower" "raise"))
653                    (if (numberp match)
654                        (int-to-string match)
655                      match))))
656
657     ;; Get rid of string props.
658     (setq match (format "%s" match))
659
660     ;; If this is an integer comparison, we transform from string to int. 
661     (and (eq (nth 2 (assoc header gnus-header-index)) 'gnus-score-integer)
662          (setq match (string-to-int match)))
663
664     (unless (eq date 'now)
665       ;; Add the score entry to the score file.
666       (when (= score gnus-score-interactive-default-score)
667         (setq score nil))
668       (let ((old (gnus-score-get header))
669             elem)
670         (setq new
671               (cond 
672                (type
673                 (list match score
674                       (and date (if (numberp date) date
675                                   (gnus-day-number date)))
676                       type))
677                (date (list match score (gnus-day-number date)))
678                (score (list match score))
679                (t (list match))))
680         ;; We see whether we can collapse some score entries.
681         ;; This isn't quite correct, because there may be more elements
682         ;; later on with the same key that have matching elems...  Hm.
683         (if (and old
684                  (setq elem (assoc match old))
685                  (eq (nth 3 elem) (nth 3 new))
686                  (or (and (numberp (nth 2 elem)) (numberp (nth 2 new)))
687                      (and (not (nth 2 elem)) (not (nth 2 new)))))
688             ;; Yup, we just add this new score to the old elem.
689             (setcar (cdr elem) (+ (or (nth 1 elem) 
690                                       gnus-score-interactive-default-score)
691                                   (or (nth 1 new)
692                                       gnus-score-interactive-default-score)))
693           ;; Nope, we have to add a new elem.
694           (gnus-score-set header (if old (cons new old) (list new))))
695         (gnus-score-set 'touched '(t))))
696
697     ;; Score the current buffer.
698     (unless silent
699       (if (and (>= (nth 1 (assoc header gnus-header-index)) 0)
700                (eq (nth 2 (assoc header gnus-header-index))
701                    'gnus-score-string))
702           (gnus-summary-score-effect header match type score)
703         (gnus-summary-rescore)))
704
705     ;; Return the new scoring rule.
706     new))
707
708 (defun gnus-summary-score-effect (header match type score)
709   "Simulate the effect of a score file entry.
710 HEADER is the header being scored.
711 MATCH is the string we are looking for.
712 TYPE is a flag indicating if it is a regexp or substring.
713 SCORE is the score to add."
714   (interactive (list (completing-read "Header: "
715                                       gnus-header-index
716                                       (lambda (x) (fboundp (nth 2 x)))
717                                       t)
718                      (read-string "Match: ")
719                      (y-or-n-p "Use regexp match? ")
720                      (prefix-numeric-value current-prefix-arg)))
721   (save-excursion
722     (or (and (stringp match) (> (length match) 0))
723         (error "No match"))
724     (goto-char (point-min))
725     (let ((regexp (cond ((eq type 'f)
726                          (gnus-simplify-subject-fuzzy match))
727                         ((eq type 'r) 
728                          match)
729                         ((eq type 'e)
730                          (concat "\\`" (regexp-quote match) "\\'"))
731                         (t 
732                          (regexp-quote match)))))
733       (while (not (eobp))
734         (let ((content (gnus-summary-header header 'noerr))
735               (case-fold-search t))
736           (and content
737                (if (if (eq type 'f)
738                        (string-equal (gnus-simplify-subject-fuzzy content)
739                                      regexp)
740                      (string-match regexp content))
741                    (gnus-summary-raise-score score))))
742         (beginning-of-line 2)))))
743
744 (defun gnus-summary-score-crossposting (score date)
745   ;; Enter score file entry for current crossposting.
746   ;; SCORE is the score to add.
747   ;; DATE is the expire date.
748   (let ((xref (gnus-summary-header "xref"))
749         (start 0)
750         group)
751     (or xref (error "This article is not crossposted"))
752     (while (string-match " \\([^ \t]+\\):" xref start)
753       (setq start (match-end 0))
754       (if (not (string= 
755                 (setq group 
756                       (substring xref (match-beginning 1) (match-end 1)))
757                 gnus-newsgroup-name))
758           (gnus-summary-score-entry
759            "xref" (concat " " group ":") nil score date t)))))
760
761 \f
762 ;;;
763 ;;; Gnus Score Files
764 ;;;
765
766 ;; All score code written by Per Abrahamsen <abraham@iesd.auc.dk>.
767
768 ;; Added by Per Abrahamsen <amanda@iesd.auc.dk>.
769 (defun gnus-score-set-mark-below (score)
770   "Automatically mark articles with score below SCORE as read."
771   (interactive 
772    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
773              (string-to-int (read-string "Mark below: ")))))
774   (setq score (or score gnus-summary-default-score 0))
775   (gnus-score-set 'mark (list score))
776   (gnus-score-set 'touched '(t))
777   (setq gnus-summary-mark-below score)
778   (gnus-score-update-lines))
779
780 (defun gnus-score-update-lines ()
781   "Update all lines in the summary buffer."
782   (save-excursion
783     (goto-char (point-min))
784     (while (not (eobp))
785       (gnus-summary-update-line)
786       (forward-line 1))))
787
788 (defun gnus-score-update-all-lines ()
789   "Update all lines in the summary buffer, even the hidden ones."
790   (save-excursion
791     (goto-char (point-min))
792     (let (hidden)
793       (while (not (eobp))
794         (when (gnus-summary-show-thread)
795           (push (point) hidden))
796         (gnus-summary-update-line)
797         (forward-line 1))
798       ;; Re-hide the hidden threads.
799       (while hidden
800         (goto-char (pop hidden))
801         (gnus-summary-hide-thread)))))
802
803 (defun gnus-score-set-expunge-below (score)
804   "Automatically expunge articles with score below SCORE."
805   (interactive 
806    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
807              (string-to-int (read-string "Set expunge below: ")))))
808   (setq score (or score gnus-summary-default-score 0))
809   (gnus-score-set 'expunge (list score))
810   (gnus-score-set 'touched '(t)))
811
812 (defun gnus-score-followup-article (&optional score)
813   "Add SCORE to all followups to the article in the current buffer."
814   (interactive "P")
815   (setq score (gnus-score-default score))
816   (when (gnus-buffer-live-p gnus-summary-buffer)
817     (save-excursion
818       (save-restriction
819         (message-narrow-to-headers)
820         (let ((id (mail-fetch-field "message-id")))
821           (when id
822             (set-buffer gnus-summary-buffer)
823             (gnus-summary-score-entry
824              "references" (concat id "[ \t]*$") 'r
825              score (current-time-string) nil t)))))))
826
827 (defun gnus-score-followup-thread (&optional score)
828   "Add SCORE to all later articles in the thread the current buffer is part of."
829   (interactive "P")
830   (setq score (gnus-score-default score))
831   (when (gnus-buffer-live-p gnus-summary-buffer)
832     (save-excursion
833       (save-restriction
834         (goto-char (point-min))
835         (let ((id (mail-fetch-field "message-id")))
836           (when id
837             (set-buffer gnus-summary-buffer)
838             (gnus-summary-score-entry
839              "references" id 's
840              score (current-time-string))))))))
841
842 (defun gnus-score-set (symbol value &optional alist)
843   ;; Set SYMBOL to VALUE in ALIST.
844   (let* ((alist 
845           (or alist 
846               gnus-score-alist
847               (gnus-newsgroup-score-alist)))
848          (entry (assoc symbol alist)))
849     (cond ((gnus-score-get 'read-only alist)
850            ;; This is a read-only score file, so we do nothing.
851            )
852           (entry
853            (setcdr entry value))
854           ((null alist)
855            (error "Empty alist"))
856           (t
857            (setcdr alist
858                    (cons (cons symbol value) (cdr alist)))))))
859
860 (defun gnus-summary-raise-score (n)
861   "Raise the score of the current article by N."
862   (interactive "p")
863   (gnus-set-global-variables)
864   (gnus-summary-set-score (+ (gnus-summary-article-score) 
865                              (or n gnus-score-interactive-default-score ))))
866
867 (defun gnus-summary-set-score (n)
868   "Set the score of the current article to N."
869   (interactive "p")
870   (gnus-set-global-variables)
871   (save-excursion
872     (gnus-summary-show-thread)
873     (let ((buffer-read-only nil))
874       ;; Set score.
875       (gnus-summary-update-mark
876        (if (= n (or gnus-summary-default-score 0)) ? 
877          (if (< n (or gnus-summary-default-score 0))
878              gnus-score-below-mark gnus-score-over-mark)) 'score))
879     (let* ((article (gnus-summary-article-number))
880            (score (assq article gnus-newsgroup-scored)))
881       (if score (setcdr score n)
882         (setq gnus-newsgroup-scored
883               (cons (cons article n) gnus-newsgroup-scored))))
884     (gnus-summary-update-line)))
885
886 (defun gnus-summary-current-score ()
887   "Return the score of the current article."
888   (interactive)
889   (gnus-set-global-variables)
890   (gnus-message 1 "%s" (gnus-summary-article-score)))
891
892 (defun gnus-score-change-score-file (file)
893   "Change current score alist."
894   (interactive 
895    (list (read-file-name "Change to score file: " gnus-kill-files-directory)))
896   (gnus-score-load-file file)
897   (gnus-set-mode-line 'summary))
898
899 (defvar gnus-score-edit-exit-function)
900 (defun gnus-score-edit-current-scores (file)
901   "Edit the current score alist."
902   (interactive (list gnus-current-score-file))
903   (let ((winconf (current-window-configuration)))
904     (and (buffer-name gnus-summary-buffer) (gnus-score-save))
905     (gnus-make-directory (file-name-directory file))
906     (setq gnus-score-edit-buffer (find-file-noselect file))
907     (gnus-configure-windows 'edit-score)
908     (gnus-score-mode)
909     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
910     (make-local-variable 'gnus-prev-winconf)
911     (setq gnus-prev-winconf winconf))
912   (gnus-message 
913    4 (substitute-command-keys 
914       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
915   
916 (defun gnus-score-edit-file (file)
917   "Edit a score file."
918   (interactive 
919    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
920   (gnus-make-directory (file-name-directory file))
921   (and (buffer-name gnus-summary-buffer) (gnus-score-save))
922   (let ((winconf (current-window-configuration)))
923     (setq gnus-score-edit-buffer (find-file-noselect file))
924     (gnus-configure-windows 'edit-score)
925     (gnus-score-mode)
926     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
927     (make-local-variable 'gnus-prev-winconf)
928     (setq gnus-prev-winconf winconf))
929   (gnus-message 
930    4 (substitute-command-keys 
931       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
932   
933 (defun gnus-score-load-file (file)
934   ;; Load score file FILE.  Returns a list a retrieved score-alists.
935   (let* ((file (expand-file-name 
936                 (or (and (string-match
937                           (concat "^" (expand-file-name
938                                        gnus-kill-files-directory)) 
939                           (expand-file-name file))
940                          file)
941                     (concat (file-name-as-directory gnus-kill-files-directory)
942                             file))))
943          (cached (assoc file gnus-score-cache))
944          (global (member file gnus-internal-global-score-files))
945          lists alist)
946     (if cached
947         ;; The score file was already loaded.
948         (setq alist (cdr cached))
949       ;; We load the score file.
950       (setq gnus-score-alist nil)
951       (setq alist (gnus-score-load-score-alist file))
952       ;; We add '(touched) to the alist to signify that it hasn't been
953       ;; touched (yet). 
954       (or (assq 'touched alist) (setq alist (cons (list 'touched nil) alist)))
955       ;; If it is a global score file, we make it read-only.
956       (and global
957            (not (assq 'read-only alist))
958            (setq alist (cons (list 'read-only t) alist)))
959       (setq gnus-score-cache
960             (cons (cons file alist) gnus-score-cache)))
961     (let ((a alist)
962           found)
963       (while a
964         ;; Downcase all header names.
965         (when (stringp (caar a))
966           (setcar (car a) (downcase (caar a)))
967           (setq found t))
968         (pop a))
969       ;; If there are actual scores in the alist, we add it to the
970       ;; return value of this function.
971       (when found
972         (setq lists (list alist))))
973     ;; Treat the other possible atoms in the score alist.
974     (let ((mark (car (gnus-score-get 'mark alist)))
975           (expunge (car (gnus-score-get 'expunge alist)))
976           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
977           (files (gnus-score-get 'files alist))
978           (exclude-files (gnus-score-get 'exclude-files alist))
979           (orphan (car (gnus-score-get 'orphan alist)))
980           (adapt (gnus-score-get 'adapt alist))
981           (thread-mark-and-expunge
982            (car (gnus-score-get 'thread-mark-and-expunge alist)))
983           (adapt-file (car (gnus-score-get 'adapt-file alist)))
984           (local (gnus-score-get 'local alist))
985           (decay (car (gnus-score-get 'decay alist)))
986           (eval (car (gnus-score-get 'eval alist))))
987       ;; Perform possible decays.
988       (when (and gnus-decay-scores
989                  (gnus-decay-scores 
990                   alist (or decay (gnus-time-to-day (current-time)))))
991         (gnus-score-set 'touched '(t) alist)
992         (gnus-score-set 'decay (list (gnus-time-to-day (current-time)))))
993       ;; We do not respect eval and files atoms from global score
994       ;; files. 
995       (and files (not global)
996            (setq lists (apply 'append lists
997                               (mapcar (lambda (file)
998                                         (gnus-score-load-file file)) 
999                                       (if adapt-file (cons adapt-file files)
1000                                         files)))))
1001       (and eval (not global) (eval eval))
1002       ;; We then expand any exclude-file directives.
1003       (setq gnus-scores-exclude-files 
1004             (nconc 
1005              (mapcar 
1006               (lambda (sfile) 
1007                 (expand-file-name sfile (file-name-directory file)))
1008               exclude-files) gnus-scores-exclude-files))
1009       (if (not local)
1010           ()
1011         (save-excursion
1012           (set-buffer gnus-summary-buffer)
1013           (while local
1014             (and (consp (car local))
1015                  (symbolp (caar local))
1016                  (progn
1017                    (make-local-variable (caar local))
1018                    (set (caar local) (nth 1 (car local)))))
1019             (setq local (cdr local)))))
1020       (if orphan (setq gnus-orphan-score orphan))
1021       (setq gnus-adaptive-score-alist
1022             (cond ((equal adapt '(t))
1023                    (setq gnus-newsgroup-adaptive t)
1024                    gnus-default-adaptive-score-alist)
1025                   ((equal adapt '(ignore))
1026                    (setq gnus-newsgroup-adaptive nil))
1027                   ((consp adapt)
1028                    (setq gnus-newsgroup-adaptive t)
1029                    adapt)
1030                   (t
1031                    ;;(setq gnus-newsgroup-adaptive gnus-use-adaptive-scoring)
1032                    gnus-default-adaptive-score-alist)))
1033       (setq gnus-thread-expunge-below 
1034             (or thread-mark-and-expunge gnus-thread-expunge-below))
1035       (setq gnus-summary-mark-below 
1036             (or mark mark-and-expunge gnus-summary-mark-below))
1037       (setq gnus-summary-expunge-below 
1038             (or expunge mark-and-expunge gnus-summary-expunge-below))
1039       (setq gnus-newsgroup-adaptive-score-file 
1040             (or adapt-file gnus-newsgroup-adaptive-score-file)))
1041     (setq gnus-current-score-file file)
1042     (setq gnus-score-alist alist)
1043     lists))
1044
1045 (defun gnus-score-load (file)
1046   ;; Load score FILE.
1047   (let ((cache (assoc file gnus-score-cache)))
1048     (if cache
1049         (setq gnus-score-alist (cdr cache))
1050       (setq gnus-score-alist nil)
1051       (gnus-score-load-score-alist file)
1052       (or gnus-score-alist
1053           (setq gnus-score-alist (copy-alist '((touched nil)))))
1054       (setq gnus-score-cache
1055             (cons (cons file gnus-score-alist) gnus-score-cache)))))
1056
1057 (defun gnus-score-remove-from-cache (file)
1058   (setq gnus-score-cache 
1059         (delq (assoc file gnus-score-cache) gnus-score-cache)))
1060
1061 (defun gnus-score-load-score-alist (file)
1062   "Read score FILE."
1063   (let (alist)
1064     (if (not (file-readable-p file))
1065         ;; Couldn't read file.
1066         (setq gnus-score-alist nil)
1067       ;; Read file.
1068       (save-excursion
1069         (gnus-set-work-buffer)
1070         (insert-file-contents file)
1071         (goto-char (point-min))
1072         ;; Only do the loading if the score file isn't empty.
1073         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
1074           (setq alist
1075                 (condition-case ()
1076                     (read (current-buffer))
1077                   (error 
1078                    (gnus-error 3.2 "Problem with score file %s" file))))))
1079       (if (eq (car alist) 'setq)
1080           ;; This is an old-style score file.
1081           (setq gnus-score-alist (gnus-score-transform-old-to-new alist))
1082         (setq gnus-score-alist alist))
1083       ;; Check the syntax of the score file.
1084       (setq gnus-score-alist
1085             (gnus-score-check-syntax gnus-score-alist file)))))
1086
1087 (defun gnus-score-check-syntax (alist file)
1088   "Check the syntax of the score ALIST."
1089   (cond 
1090    ((null alist)
1091     nil)
1092    ((not (consp alist))
1093     (gnus-message 1 "Score file is not a list: %s" file)
1094     (ding)
1095     nil)
1096    (t
1097     (let ((a alist)
1098           sr err s type)
1099       (while (and a (not err))
1100         (setq
1101          err
1102          (cond
1103           ((not (listp (car a)))
1104            (format "Illegal score element %s in %s" (car a) file))
1105           ((stringp (caar a))
1106            (cond 
1107             ((not (listp (setq sr (cdar a))))
1108              (format "Illegal header match %s in %s" (nth 1 (car a)) file))
1109             (t
1110              (setq type (caar a))
1111              (while (and sr (not err))
1112                (setq s (pop sr))
1113                (setq 
1114                 err
1115                 (cond
1116                  ((if (member (downcase type) '("lines" "chars"))
1117                       (not (numberp (car s)))
1118                     (not (stringp (car s))))
1119                   (format "Illegal match %s in %s" (car s) file))
1120                  ((and (cadr s) (not (integerp (cadr s))))
1121                   (format "Non-integer score %s in %s" (cadr s) file))
1122                  ((and (caddr s) (not (integerp (caddr s))))
1123                   (format "Non-integer date %s in %s" (caddr s) file))
1124                  ((and (cadddr s) (not (symbolp (cadddr s))))
1125                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1126              err)))))
1127         (setq a (cdr a)))
1128       (if err
1129           (progn
1130             (ding)
1131             (gnus-message 3 err)
1132             (sit-for 2)
1133             nil)
1134         alist)))))    
1135
1136 (defun gnus-score-transform-old-to-new (alist)
1137   (let* ((alist (nth 2 alist))
1138          out entry)
1139     (if (eq (car alist) 'quote)
1140         (setq alist (nth 1 alist)))
1141     (while alist
1142       (setq entry (car alist))
1143       (if (stringp (car entry))
1144           (let ((scor (cdr entry)))
1145             (setq out (cons entry out))
1146             (while scor
1147               (setcar scor
1148                       (list (caar scor) (nth 2 (car scor))
1149                             (and (nth 3 (car scor))
1150                                  (gnus-day-number (nth 3 (car scor))))
1151                             (if (nth 1 (car scor)) 'r 's)))
1152               (setq scor (cdr scor))))
1153         (setq out (cons (if (not (listp (cdr entry))) 
1154                             (list (car entry) (cdr entry))
1155                           entry)
1156                         out)))
1157       (setq alist (cdr alist)))
1158     (cons (list 'touched t) (nreverse out))))
1159   
1160 (defun gnus-score-save ()
1161   ;; Save all score information.
1162   (let ((cache gnus-score-cache)
1163         entry score file)
1164     (save-excursion
1165       (setq gnus-score-alist nil)
1166       (nnheader-set-temp-buffer " *Gnus Scores*")
1167       (while cache
1168         (current-buffer)
1169         (setq entry (pop cache)
1170               file (car entry)
1171               score (cdr entry))
1172         (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1173                 (gnus-score-get 'read-only score)
1174                 (and (file-exists-p file)
1175                      (not (file-writable-p file))))
1176             ()
1177           (setq score (setcdr entry (delq (assq 'touched score) score)))
1178           (erase-buffer)
1179           (let (emacs-lisp-mode-hook)
1180             (if (string-match 
1181                  (concat (regexp-quote gnus-adaptive-file-suffix)
1182                          "$") file)
1183                 ;; This is an adaptive score file, so we do not run
1184                 ;; it through `pp'.  These files can get huge, and
1185                 ;; are not meant to be edited by human hands.
1186                 (gnus-prin1 score)
1187               ;; This is a normal score file, so we print it very
1188               ;; prettily. 
1189               (pp score (current-buffer))))
1190           (gnus-make-directory (file-name-directory file))
1191           ;; If the score file is empty, we delete it.
1192           (if (zerop (buffer-size))
1193               (delete-file file)
1194             ;; There are scores, so we write the file. 
1195             (when (file-writable-p file)
1196               (write-region (point-min) (point-max) file nil 'silent)
1197               (when gnus-score-after-write-file-function
1198                 (funcall gnus-score-after-write-file-function file)))))
1199         (and gnus-score-uncacheable-files
1200              (string-match gnus-score-uncacheable-files file)
1201              (gnus-score-remove-from-cache file)))
1202       (kill-buffer (current-buffer)))))
1203
1204 (defun gnus-score-load-files (score-files)
1205   "Load all score files in SCORE-FILES."
1206   ;; Load the score files.
1207   (let (scores)
1208     (while score-files
1209       (if (stringp (car score-files))
1210           ;; It is a string, which means that it's a score file name,
1211           ;; so we load the score file and add the score alist to
1212           ;; the list of alists.
1213           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1214         ;; It is an alist, so we just add it to the list directly.
1215         (setq scores (nconc (car score-files) scores)))
1216       (setq score-files (cdr score-files)))
1217     ;; Prune the score files that are to be excluded, if any.
1218     (when gnus-scores-exclude-files
1219       (let ((s scores)
1220             c)
1221         (while s
1222           (and (setq c (rassq (car s) gnus-score-cache))
1223                (member (car c) gnus-scores-exclude-files)
1224                (setq scores (delq (car s) scores)))
1225           (setq s (cdr s)))))
1226     scores))
1227
1228 (defun gnus-score-headers (score-files &optional trace)
1229   ;; Score `gnus-newsgroup-headers'.
1230   (let (scores news)
1231     ;; PLM: probably this is not the best place to clear orphan-score
1232     (setq gnus-orphan-score nil
1233           gnus-scores-articles nil
1234           gnus-scores-exclude-files nil
1235           scores (gnus-score-load-files score-files))
1236     (setq news scores)
1237     ;; Do the scoring.
1238     (while news
1239       (setq scores news
1240             news nil)
1241       (when (and gnus-summary-default-score
1242                  scores)
1243         (let* ((entries gnus-header-index)
1244                (now (gnus-day-number (current-time-string)))
1245                (expire (and gnus-score-expiry-days
1246                             (- now gnus-score-expiry-days)))
1247                (headers gnus-newsgroup-headers)
1248                (current-score-file gnus-current-score-file)
1249                entry header new)
1250           (gnus-message 5 "Scoring...")
1251           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1252           (while (setq header (pop headers))
1253             ;; WARNING: The assq makes the function O(N*S) while it could
1254             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1255             ;; and S is (length gnus-newsgroup-scored).
1256             (or (assq (mail-header-number header) gnus-newsgroup-scored)
1257                 (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1258                       (cons (cons header (or gnus-summary-default-score 0))
1259                             gnus-scores-articles))))
1260
1261           (save-excursion
1262             (set-buffer (get-buffer-create "*Headers*"))
1263             (buffer-disable-undo (current-buffer))
1264
1265             ;; Set the global variant of this variable.
1266             (setq gnus-current-score-file current-score-file)
1267             ;; score orphans
1268             (when gnus-orphan-score 
1269               (setq gnus-score-index 
1270                     (nth 1 (assoc "references" gnus-header-index)))
1271               (gnus-score-orphans gnus-orphan-score))
1272             ;; Run each header through the score process.
1273             (while entries
1274               (setq entry (pop entries)
1275                     header (nth 0 entry)
1276                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1277               (when (< 0 (apply 'max (mapcar
1278                                       (lambda (score)
1279                                         (length (gnus-score-get header score)))
1280                                       scores)))
1281                 ;; Call the scoring function for this type of "header".
1282                 (when (setq new (funcall (nth 2 entry) scores header
1283                                          now expire trace))
1284                   (push new news))))
1285             ;; Remove the buffer.
1286             (kill-buffer (current-buffer)))
1287
1288           ;; Add articles to `gnus-newsgroup-scored'.
1289           (while gnus-scores-articles
1290             (when (or (/= gnus-summary-default-score
1291                           (cdar gnus-scores-articles))
1292                       gnus-save-score)
1293               (push (cons (mail-header-number (caar gnus-scores-articles))
1294                           (cdar gnus-scores-articles))
1295                     gnus-newsgroup-scored))
1296             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1297
1298           (let (score)
1299             (while (setq score (pop scores))
1300               (while score
1301                 (when (listp (caar score))
1302                   (gnus-score-advanced (car score) trace))
1303                 (pop score))))
1304                 
1305           (gnus-message 5 "Scoring...done"))))))
1306
1307
1308 (defun gnus-get-new-thread-ids (articles)
1309   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
1310         (refind gnus-score-index)
1311         id-list art this tref)
1312     (while articles
1313       (setq art (car articles)
1314             this (aref (car art) index)
1315             tref (aref (car art) refind)
1316             articles (cdr articles))
1317       (if (string-equal tref "")        ;no references line
1318           (setq id-list (cons this id-list))))
1319     id-list))
1320
1321 ;; Orphan functions written by plm@atcmp.nl (Peter Mutsaers).
1322 (defun gnus-score-orphans (score)
1323   (let ((new-thread-ids (gnus-get-new-thread-ids gnus-scores-articles))
1324         alike articles art arts this last this-id)
1325     
1326     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1327           articles gnus-scores-articles)
1328
1329     ;;more or less the same as in gnus-score-string
1330     (erase-buffer)
1331     (while articles
1332       (setq art (car articles)
1333             this (aref (car art) gnus-score-index)
1334             articles (cdr articles))
1335       ;;completely skip if this is empty (not a child, so not an orphan)
1336       (if (not (string= this ""))
1337           (if (equal last this)
1338               ;; O(N*H) cons-cells used here, where H is the number of
1339               ;; headers.
1340               (setq alike (cons art alike))
1341             (if last
1342                 (progn
1343                   ;; Insert the line, with a text property on the
1344                   ;; terminating newline referring to the articles with
1345                   ;; this line.
1346                   (insert last ?\n)
1347                   (put-text-property (1- (point)) (point) 'articles alike)))
1348             (setq alike (list art)
1349                   last this))))
1350     (and last                           ; Bwadr, duplicate code.
1351          (progn
1352            (insert last ?\n)                    
1353            (put-text-property (1- (point)) (point) 'articles alike)))
1354
1355     ;; PLM: now delete those lines that contain an entry from new-thread-ids
1356     (while new-thread-ids
1357       (setq this-id (car new-thread-ids)
1358             new-thread-ids (cdr new-thread-ids))
1359       (goto-char (point-min))
1360       (while (search-forward this-id nil t)
1361         ;; found a match.  remove this line
1362         (beginning-of-line)
1363         (kill-line 1)))
1364
1365     ;; now for each line: update its articles with score by moving to
1366     ;; every end-of-line in the buffer and read the articles property
1367     (goto-char (point-min))
1368     (while (eq 0 (progn
1369                    (end-of-line)
1370                    (setq arts (get-text-property (point) 'articles))
1371                    (while arts
1372                      (setq art (car arts)
1373                            arts (cdr arts))
1374                      (setcdr art (+ score (cdr art))))
1375                    (forward-line))))))
1376              
1377
1378 (defun gnus-score-integer (scores header now expire &optional trace)
1379   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1380         entries alist)
1381
1382     ;; Find matches.
1383     (while scores
1384       (setq alist (car scores)
1385             scores (cdr scores)
1386             entries (assoc header alist))
1387       (while (cdr entries)              ;First entry is the header index.
1388         (let* ((rest (cdr entries))             
1389                (kill (car rest))
1390                (match (nth 0 kill))
1391                (type (or (nth 3 kill) '>))
1392                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1393                (date (nth 2 kill))
1394                (found nil)
1395                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1396                                    (eq type '>=) (eq type '=))
1397                                type
1398                              (error "Illegal match type: %s" type)))
1399                (articles gnus-scores-articles))
1400           ;; Instead of doing all the clever stuff that
1401           ;; `gnus-score-string' does to minimize searches and stuff,
1402           ;; I will assume that people generally will put so few
1403           ;; matches on numbers that any cleverness will take more
1404           ;; time than one would gain.
1405           (while articles
1406             (when (funcall match-func 
1407                            (or (aref (caar articles) gnus-score-index) 0)
1408                            match)
1409               (when trace 
1410                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1411                       gnus-score-trace))
1412               (setq found t)
1413               (setcdr (car articles) (+ score (cdar articles))))
1414             (setq articles (cdr articles)))
1415           ;; Update expire date
1416           (cond ((null date))           ;Permanent entry.
1417                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1418                  (gnus-score-set 'touched '(t) alist)
1419                  (setcar (nthcdr 2 kill) now))
1420                 ((and expire (< date expire)) ;Old entry, remove.
1421                  (gnus-score-set 'touched '(t) alist)
1422                  (setcdr entries (cdr rest))
1423                  (setq rest entries)))
1424           (setq entries rest)))))
1425   nil)
1426
1427 (defun gnus-score-date (scores header now expire &optional trace)
1428   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1429         entries alist match match-func article)
1430
1431     ;; Find matches.
1432     (while scores
1433       (setq alist (car scores)
1434             scores (cdr scores)
1435             entries (assoc header alist))
1436       (while (cdr entries)              ;First entry is the header index.
1437         (let* ((rest (cdr entries))             
1438                (kill (car rest))
1439                (type (or (nth 3 kill) 'before))
1440                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1441                (date (nth 2 kill))
1442                (found nil)
1443                (articles gnus-scores-articles)
1444                l)
1445           (cond
1446            ((eq type 'after)
1447             (setq match-func 'string<
1448                   match (gnus-date-iso8601 (nth 0 kill))))
1449            ((eq type 'before)
1450             (setq match-func 'gnus-string>
1451                   match (gnus-date-iso8601 (nth 0 kill))))
1452            ((eq type 'at)
1453             (setq match-func 'string=
1454                   match (gnus-date-iso8601 (nth 0 kill))))
1455            ((eq type 'regexp)
1456             (setq match-func 'string-match
1457                   match (nth 0 kill)))
1458            (t (error "Illegal match type: %s" type)))
1459           ;; Instead of doing all the clever stuff that
1460           ;; `gnus-score-string' does to minimize searches and stuff,
1461           ;; I will assume that people generally will put so few
1462           ;; matches on numbers that any cleverness will take more
1463           ;; time than one would gain.
1464           (while (setq article (pop articles))
1465             (when (and
1466                    (setq l (aref (car article) gnus-score-index))
1467                    (funcall match-func match (gnus-date-iso8601 l)))
1468               (when trace
1469                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1470                       gnus-score-trace))
1471               (setq found t)
1472               (setcdr article (+ score (cdr article)))))
1473           ;; Update expire date
1474           (cond ((null date))           ;Permanent entry.
1475                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1476                  (gnus-score-set 'touched '(t) alist)
1477                  (setcar (nthcdr 2 kill) now))
1478                 ((and expire (< date expire)) ;Old entry, remove.
1479                  (gnus-score-set 'touched '(t) alist)
1480                  (setcdr entries (cdr rest))
1481                  (setq rest entries)))
1482           (setq entries rest)))))
1483   nil)
1484
1485 (defun gnus-score-body (scores header now expire &optional trace)
1486   (save-excursion
1487     (set-buffer nntp-server-buffer)
1488     (setq gnus-scores-articles
1489           (sort gnus-scores-articles
1490                 (lambda (a1 a2)
1491                   (< (mail-header-number (car a1))
1492                      (mail-header-number (car a2))))))
1493     (save-restriction
1494       (let* ((buffer-read-only nil)
1495              (articles gnus-scores-articles)
1496              (all-scores scores)
1497              (request-func (cond ((string= "head" header)
1498                                   'gnus-request-head)
1499                                  ((string= "body" header)
1500                                   'gnus-request-body)
1501                                  (t 'gnus-request-article)))
1502              entries alist ofunc article last)
1503         (when articles
1504           (setq last (mail-header-number (caar (last articles))))
1505           ;; Not all backends support partial fetching.  In that case,
1506           ;; we just fetch the entire article.
1507           (unless (gnus-check-backend-function 
1508                    (and (string-match "^gnus-" (symbol-name request-func))
1509                         (intern (substring (symbol-name request-func)
1510                                            (match-end 0))))
1511                    gnus-newsgroup-name)
1512             (setq ofunc request-func)
1513             (setq request-func 'gnus-request-article))
1514           (while articles
1515             (setq article (mail-header-number (caar articles)))
1516             (gnus-message 7 "Scoring on article %s of %s..." article last)
1517             (when (funcall request-func article gnus-newsgroup-name)
1518               (widen)
1519               (goto-char (point-min))
1520               ;; If just parts of the article is to be searched, but the
1521               ;; backend didn't support partial fetching, we just narrow
1522               ;; to the relevant parts.
1523               (if ofunc
1524                   (if (eq ofunc 'gnus-request-head)
1525                       (narrow-to-region
1526                        (point)
1527                        (or (search-forward "\n\n" nil t) (point-max)))
1528                     (narrow-to-region
1529                      (or (search-forward "\n\n" nil t) (point))
1530                      (point-max))))
1531               (setq scores all-scores)
1532               ;; Find matches.
1533               (while scores
1534                 (setq alist (car scores)
1535                       scores (cdr scores)
1536                       entries (assoc header alist))
1537                 (while (cdr entries)    ;First entry is the header index.
1538                   (let* ((rest (cdr entries))           
1539                          (kill (car rest))
1540                          (match (nth 0 kill))
1541                          (type (or (nth 3 kill) 's))
1542                          (score (or (nth 1 kill) 
1543                                     gnus-score-interactive-default-score))
1544                          (date (nth 2 kill))
1545                          (found nil)
1546                          (case-fold-search 
1547                           (not (or (eq type 'R) (eq type 'S)
1548                                    (eq type 'Regexp) (eq type 'String))))
1549                          (search-func 
1550                           (cond ((or (eq type 'r) (eq type 'R)
1551                                      (eq type 'regexp) (eq type 'Regexp))
1552                                  're-search-forward)
1553                                 ((or (eq type 's) (eq type 'S)
1554                                      (eq type 'string) (eq type 'String))
1555                                  'search-forward)
1556                                 (t
1557                                  (error "Illegal match type: %s" type)))))
1558                     (goto-char (point-min))
1559                     (if (funcall search-func match nil t)
1560                         ;; Found a match, update scores.
1561                         (progn
1562                           (setcdr (car articles) (+ score (cdar articles)))
1563                           (setq found t)
1564                           (and trace (setq gnus-score-trace 
1565                                            (cons
1566                                             (cons
1567                                              (car-safe
1568                                               (rassq alist gnus-score-cache))
1569                                              kill)
1570                                             gnus-score-trace)))))
1571                     ;; Update expire date
1572                     (cond
1573                      ((null date))      ;Permanent entry.
1574                      ((and found gnus-update-score-entry-dates) ;Match, update date.
1575                       (gnus-score-set 'touched '(t) alist)
1576                       (setcar (nthcdr 2 kill) now))
1577                      ((and expire (< date expire)) ;Old entry, remove.
1578                       (gnus-score-set 'touched '(t) alist)
1579                       (setcdr entries (cdr rest))
1580                       (setq rest entries)))
1581                     (setq entries rest)))))
1582             (setq articles (cdr articles)))))))
1583   nil)
1584
1585 (defun gnus-score-followup (scores header now expire &optional trace thread)
1586   ;; Insert the unique article headers in the buffer.
1587   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1588         (current-score-file gnus-current-score-file)
1589         (all-scores scores)
1590         ;; gnus-score-index is used as a free variable.
1591         alike last this art entries alist articles
1592         new news)
1593
1594     ;; Change score file to the adaptive score file.  All entries that
1595     ;; this function makes will be put into this file.
1596     (save-excursion
1597       (set-buffer gnus-summary-buffer)
1598       (gnus-score-load-file
1599        (or gnus-newsgroup-adaptive-score-file
1600            (gnus-score-file-name 
1601             gnus-newsgroup-name gnus-adaptive-file-suffix))))
1602
1603     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1604           articles gnus-scores-articles)
1605
1606     (erase-buffer)
1607     (while articles
1608       (setq art (car articles)
1609             this (aref (car art) gnus-score-index)
1610             articles (cdr articles))
1611       (if (equal last this)
1612           (setq alike (cons art alike))
1613         (if last
1614             (progn
1615               (insert last ?\n)
1616               (put-text-property (1- (point)) (point) 'articles alike)))
1617         (setq alike (list art)
1618               last this)))
1619     (and last                           ; Bwadr, duplicate code.
1620          (progn
1621            (insert last ?\n)                    
1622            (put-text-property (1- (point)) (point) 'articles alike)))
1623   
1624     ;; Find matches.
1625     (while scores
1626       (setq alist (car scores)
1627             scores (cdr scores)
1628             entries (assoc header alist))
1629       (while (cdr entries)              ;First entry is the header index.
1630         (let* ((rest (cdr entries))             
1631                (kill (car rest))
1632                (match (nth 0 kill))
1633                (type (or (nth 3 kill) 's))
1634                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1635                (date (nth 2 kill))
1636                (found nil)
1637                (mt (aref (symbol-name type) 0))
1638                (case-fold-search 
1639                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1640                (dmt (downcase mt))
1641                (search-func 
1642                 (cond ((= dmt ?r) 're-search-forward)
1643                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1644                       (t (error "Illegal match type: %s" type))))
1645                arts art)
1646           (goto-char (point-min))
1647           (if (= dmt ?e)
1648               (while (funcall search-func match nil t)
1649                 (and (= (progn (beginning-of-line) (point))
1650                         (match-beginning 0))
1651                      (= (progn (end-of-line) (point))
1652                         (match-end 0))
1653                      (progn
1654                        (setq found (setq arts (get-text-property 
1655                                                (point) 'articles)))
1656                        ;; Found a match, update scores.
1657                        (while arts
1658                          (setq art (car arts)
1659                                arts (cdr arts))
1660                          (gnus-score-add-followups 
1661                           (car art) score all-scores thread))))
1662                 (end-of-line))
1663             (while (funcall search-func match nil t)
1664               (end-of-line)
1665               (setq found (setq arts (get-text-property (point) 'articles)))
1666               ;; Found a match, update scores.
1667               (while (setq art (pop arts))
1668                 (when (setq new (gnus-score-add-followups
1669                                  (car art) score all-scores thread))
1670                   (push new news)))))
1671           ;; Update expire date
1672           (cond ((null date))           ;Permanent entry.
1673                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1674                  (gnus-score-set 'touched '(t) alist)
1675                  (setcar (nthcdr 2 kill) now))
1676                 ((and expire (< date expire)) ;Old entry, remove.
1677                  (gnus-score-set 'touched '(t) alist)
1678                  (setcdr entries (cdr rest))
1679                  (setq rest entries)))
1680           (setq entries rest))))
1681     ;; We change the score file back to the previous one.
1682     (save-excursion
1683       (set-buffer gnus-summary-buffer)
1684       (gnus-score-load-file current-score-file))
1685     (list (cons "references" news))))
1686
1687 (defun gnus-score-add-followups (header score scores &optional thread)
1688   "Add a score entry to the adapt file."
1689   (save-excursion
1690     (set-buffer gnus-summary-buffer)
1691     (let* ((id (mail-header-id header))
1692            (scores (car scores))
1693            entry dont)
1694       ;; Don't enter a score if there already is one.
1695       (while (setq entry (pop scores))
1696         (and (equal "references" (car entry))
1697              (or (null (nth 3 (cadr entry)))
1698                  (eq 's (nth 3 (cadr entry))))
1699              (assoc id entry)
1700              (setq dont t)))
1701       (unless dont
1702         (gnus-summary-score-entry 
1703          (if thread "thread" "references")
1704          id 's score (current-time-string) nil t)))))
1705
1706 (defun gnus-score-string (score-list header now expire &optional trace)
1707   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1708   ;; Update matching entries to NOW and remove unmatched entries older
1709   ;; than EXPIRE.
1710   
1711   ;; Insert the unique article headers in the buffer.
1712   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1713         ;; gnus-score-index is used as a free variable.
1714         alike last this art entries alist articles 
1715         fuzzies arts words kill)
1716
1717     ;; Sorting the articles costs os O(N*log N) but will allow us to
1718     ;; only match with each unique header.  Thus the actual matching
1719     ;; will be O(M*U) where M is the number of strings to match with,
1720     ;; and U is the number of unique headers.  It is assumed (but
1721     ;; untested) this will be a net win because of the large constant
1722     ;; factor involved with string matching.
1723     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1724           articles gnus-scores-articles)
1725
1726     (erase-buffer)
1727     (while (setq art (pop articles))
1728       (setq this (aref (car art) gnus-score-index))
1729       (if (equal last this)
1730           ;; O(N*H) cons-cells used here, where H is the number of
1731           ;; headers.
1732           (setq alike (cons art alike))
1733         (when last
1734           ;; Insert the line, with a text property on the
1735           ;; terminating newline referring to the articles with
1736           ;; this line.
1737           (insert last ?\n)
1738           (put-text-property (1- (point)) (point) 'articles alike))
1739         (setq alike (list art)
1740               last this)))
1741     (when last                          ; Bwadr, duplicate code.
1742       (insert last ?\n)                 
1743       (put-text-property (1- (point)) (point) 'articles alike))
1744
1745     ;; Go through all the score alists and pick out the entries
1746     ;; for this header.
1747     (while score-list
1748       (setq alist (pop score-list)
1749             ;; There's only one instance of this header for
1750             ;; each score alist.
1751             entries (assoc header alist))
1752       (while (cdr entries)              ;First entry is the header index.
1753         (let* ((kill (cadr entries))
1754                (match (nth 0 kill))
1755                (type (or (nth 3 kill) 's))
1756                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1757                (date (nth 2 kill))
1758                (found nil)
1759                (mt (aref (symbol-name type) 0))
1760                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
1761                (dmt (downcase mt))
1762                (search-func 
1763                 (cond ((= dmt ?r) 're-search-forward)
1764                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1765                       ((= dmt ?w) nil)
1766                       (t (error "Illegal match type: %s" type)))))
1767           (cond
1768            ;; Fuzzy matches.  We save these for later.
1769            ((= dmt ?f)
1770             (push entries fuzzies))
1771            ;; Word matches.  Save these for even later.
1772            ((= dmt ?w)
1773             (push entries words))
1774            ;; Exact matches.
1775            ((= dmt ?e)
1776             ;; Do exact matching.
1777             (goto-char (point-min))
1778             (while (and (not (eobp)) 
1779                         (funcall search-func match nil t))
1780               ;; Is it really exact?
1781               (and (eolp)
1782                    (= (gnus-point-at-bol) (match-beginning 0))
1783                    ;; Yup.
1784                    (progn
1785                      (setq found (setq arts (get-text-property 
1786                                              (point) 'articles)))
1787                      ;; Found a match, update scores.
1788                      (if trace
1789                          (while (setq art (pop arts))
1790                            (setcdr art (+ score (cdr art)))
1791                            (setq gnus-score-trace
1792                                  (cons
1793                                   (cons
1794                                    (car-safe
1795                                     (rassq alist gnus-score-cache))
1796                                    kill)
1797                                   gnus-score-trace)))
1798                        (while (setq art (pop arts))
1799                          (setcdr art (+ score (cdr art)))))))
1800               (forward-line 1)))
1801            ;; Regexp and substring matching.
1802            (t
1803             (goto-char (point-min))
1804             (when (string= match "")
1805               (setq match "\n"))
1806             (while (and (not (eobp))
1807                         (funcall search-func match nil t))
1808               (goto-char (match-beginning 0))
1809               (end-of-line)
1810               (setq found (setq arts (get-text-property (point) 'articles)))
1811               ;; Found a match, update scores.
1812               (if trace
1813                   (while (setq art (pop arts))
1814                     (setcdr art (+ score (cdr art)))
1815                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1816                           gnus-score-trace))
1817                 (while (setq art (pop arts))
1818                   (setcdr art (+ score (cdr art)))))
1819               (forward-line 1))))
1820           ;; Update expiry date
1821           (if trace
1822               (setq entries (cdr entries))
1823             (cond 
1824              ;; Permanent entry.
1825              ((null date)
1826               (setq entries (cdr entries)))
1827              ;; We have a match, so we update the date.
1828              ((and found gnus-update-score-entry-dates)
1829               (gnus-score-set 'touched '(t) alist)
1830               (setcar (nthcdr 2 kill) now)
1831               (setq entries (cdr entries)))
1832              ;; This entry has expired, so we remove it.
1833              ((and expire (< date expire))
1834               (gnus-score-set 'touched '(t) alist)
1835               (setcdr entries (cddr entries)))
1836              ;; No match; go to next entry.
1837              (t
1838               (setq entries (cdr entries))))))))
1839
1840     ;; Find fuzzy matches.
1841     (when fuzzies
1842       ;; Simplify the entire buffer for easy matching.
1843       (gnus-simplify-buffer-fuzzy)
1844       (while (setq kill (cadar fuzzies))
1845         (let* ((match (nth 0 kill))
1846                (type (nth 3 kill))
1847                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1848                (date (nth 2 kill))
1849                (mt (aref (symbol-name type) 0))
1850                (case-fold-search (not (= mt ?F)))
1851                found)
1852           (goto-char (point-min))
1853           (while (and (not (eobp)) 
1854                       (search-forward match nil t))
1855             (when (and (= (gnus-point-at-bol) (match-beginning 0))
1856                        (eolp))
1857               (setq found (setq arts (get-text-property (point) 'articles)))
1858               (if trace
1859                   (while (setq art (pop arts))
1860                     (setcdr art (+ score (cdr art)))
1861                     (push (cons
1862                            (car-safe (rassq alist gnus-score-cache)) kill)
1863                           gnus-score-trace))
1864                 ;; Found a match, update scores.
1865                 (while (setq art (pop arts))
1866                   (setcdr art (+ score (cdr art))))))
1867             (forward-line 1))
1868           ;; Update expiry date
1869           (cond
1870            ;; Permanent.
1871            ((null date)
1872             )
1873            ;; Match, update date.
1874            ((and found gnus-update-score-entry-dates)
1875             (gnus-score-set 'touched '(t) alist)
1876             (setcar (nthcdr 2 kill) now))
1877            ;; Old entry, remove.
1878            ((and expire (< date expire)) 
1879             (gnus-score-set 'touched '(t) alist)
1880             (setcdr (car fuzzies) (cddar fuzzies))))
1881           (setq fuzzies (cdr fuzzies)))))
1882
1883     (when words
1884       ;; Enter all words into the hashtb.
1885       (let ((hashtb (gnus-make-hashtable
1886                      (* 10 (count-lines (point-min) (point-max))))))
1887         (gnus-enter-score-words-into-hashtb hashtb)
1888         (while (setq kill (cadar words))
1889           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
1890                  (date (nth 2 kill))
1891                  found)
1892             (when (setq arts (intern-soft (nth 0 kill) hashtb))
1893               (setq arts (symbol-value arts))
1894               (setq found t)
1895               (if trace
1896                   (while (setq art (pop arts))
1897                     (setcdr art (+ score (cdr art)))
1898                     (push (cons
1899                            (car-safe (rassq alist gnus-score-cache)) kill)
1900                           gnus-score-trace))
1901                 ;; Found a match, update scores.
1902                 (while (setq art (pop arts))
1903                   (setcdr art (+ score (cdr art))))))
1904             ;; Update expiry date
1905             (cond
1906              ;; Permanent.
1907              ((null date)
1908               )
1909              ;; Match, update date.
1910              ((and found gnus-update-score-entry-dates)
1911               (gnus-score-set 'touched '(t) alist)
1912               (setcar (nthcdr 2 kill) now))
1913              ;; Old entry, remove.
1914              ((and expire (< date expire)) 
1915               (gnus-score-set 'touched '(t) alist)
1916               (setcdr (car words) (cddar words))))
1917             (setq words (cdr words))))))
1918     nil))
1919
1920 (defun gnus-enter-score-words-into-hashtb (hashtb)
1921   ;; Find all the words in the buffer and enter them into
1922   ;; the hashtable.
1923   (let ((syntab (syntax-table))
1924         word val)
1925     (goto-char (point-min))
1926     (unwind-protect
1927         (progn
1928           (set-syntax-table gnus-adaptive-word-syntax-table)
1929           (while (re-search-forward "\\b\\w+\\b" nil t)
1930             (setq val
1931                   (gnus-gethash 
1932                    (setq word (downcase (buffer-substring
1933                                          (match-beginning 0) (match-end 0))))
1934                    hashtb))
1935             (gnus-sethash
1936              word
1937              (append (get-text-property (gnus-point-at-eol) 'articles) val)
1938              hashtb)))
1939       (set-syntax-table syntab))
1940     ;; Make all the ignorable words ignored.
1941     (let ((ignored (append gnus-ignored-adaptive-words
1942                            gnus-default-ignored-adaptive-words)))
1943       (while ignored
1944         (gnus-sethash (pop ignored) nil hashtb)))))
1945
1946 (defun gnus-score-string< (a1 a2)
1947   ;; Compare headers in articles A2 and A2.
1948   ;; The header index used is the free variable `gnus-score-index'.
1949   (string-lessp (aref (car a1) gnus-score-index)
1950                 (aref (car a2) gnus-score-index)))
1951
1952 (defun gnus-current-score-file-nondirectory (&optional score-file)
1953   (let ((score-file (or score-file gnus-current-score-file)))
1954     (if score-file 
1955         (gnus-short-group-name (file-name-nondirectory score-file))
1956       "none")))
1957
1958 (defun gnus-score-adaptive ()
1959   "Create adaptive score rules for this newsgroup."
1960   (when gnus-use-adaptive-scoring
1961     ;; We change the score file to the adaptive score file.
1962     (save-excursion
1963       (set-buffer gnus-summary-buffer)
1964       (gnus-score-load-file 
1965        (or gnus-newsgroup-adaptive-score-file
1966            (gnus-score-file-name 
1967             gnus-newsgroup-name gnus-adaptive-file-suffix))))
1968     (cond
1969      ;; Perform ordinary line scoring.
1970      ((or (not (listp gnus-use-adaptive-scoring))
1971           (memq 'line gnus-use-adaptive-scoring))
1972       (save-excursion
1973         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
1974                (alist malist)
1975                (date (current-time-string)) 
1976                (data gnus-newsgroup-data)
1977                elem headers match)
1978           ;; First we transform the adaptive rule alist into something
1979           ;; that's faster to process.
1980           (while malist
1981             (setq elem (car malist))
1982             (if (symbolp (car elem))
1983                 (setcar elem (symbol-value (car elem))))
1984             (setq elem (cdr elem))
1985             (while elem
1986               (setcdr (car elem) 
1987                       (cons (if (eq (caar elem) 'followup)
1988                                 "references"
1989                               (symbol-name (caar elem)))
1990                             (cdar elem)))
1991               (setcar (car elem) 
1992                       `(lambda (h)
1993                          (,(intern 
1994                             (concat "mail-header-" 
1995                                     (if (eq (caar elem) 'followup)
1996                                         "message-id"
1997                                       (downcase (symbol-name (caar elem))))))
1998                           h)))
1999               (setq elem (cdr elem)))
2000             (setq malist (cdr malist)))
2001           ;; Then we score away.
2002           (while data
2003             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2004             (if (or (not elem)
2005                     (gnus-data-pseudo-p (car data)))
2006                 ()
2007               (when (setq headers (gnus-data-header (car data)))
2008                 (while elem 
2009                   (setq match (funcall (caar elem) headers))
2010                   (gnus-summary-score-entry 
2011                    (nth 1 (car elem)) match
2012                    (cond
2013                     ((numberp match)
2014                      '=)
2015                     ((equal (nth 1 (car elem)) "date")
2016                      'a)
2017                     (t
2018                      ;; Whether we use substring or exact matches is
2019                      ;; controlled here.  
2020                      (if (or (not gnus-score-exact-adapt-limit)
2021                              (< (length match) gnus-score-exact-adapt-limit))
2022                          'e 
2023                        (if (equal (nth 1 (car elem)) "subject")
2024                            'f 's))))
2025                    (nth 2 (car elem)) date nil t)
2026                   (setq elem (cdr elem)))))
2027             (setq data (cdr data))))))
2028
2029      ;; Perform adaptive word scoring.
2030      ((memq 'word gnus-use-adaptive-scoring)
2031       (nnheader-temp-write nil
2032         (let* ((hashtb (gnus-make-hashtable 1000))
2033                (date (gnus-day-number (current-time-string)))
2034                (data gnus-newsgroup-data)
2035                (syntab (syntax-table))
2036                word d score val)
2037           (unwind-protect
2038               (progn
2039                 (set-syntax-table syntab)
2040                 ;; Go through all articles.
2041                 (while (setq d (pop data))
2042                   (when (and
2043                          (not (gnus-data-pseudo-p d))
2044                          (setq score
2045                                (cdr (assq 
2046                                      (gnus-data-mark d)
2047                                      gnus-default-adaptive-word-score-alist))))
2048                     ;; This article has a mark that should lead to
2049                     ;; adaptive word rules, so we insert the subject
2050                     ;; and find all words in that string.
2051                     (insert (mail-header-subject (gnus-data-header d)))
2052                     (downcase-region (point-min) (point-max))
2053                     (goto-char (point-min))
2054                     (while (re-search-forward "\\b\\w+\\b" nil t)
2055                       ;; Put the word and score into the hashtb.
2056                       (setq val (gnus-gethash (setq word (match-string 0))
2057                                               hashtb))
2058                       (gnus-sethash word (+ (or val 0) score) hashtb))
2059                     (erase-buffer))))
2060             (set-syntax-table syntab))
2061           ;; Make all the ignorable words ignored.
2062           (let ((ignored (append gnus-ignored-adaptive-words
2063                                  gnus-default-ignored-adaptive-words)))
2064             (while ignored
2065               (gnus-sethash (pop ignored) nil hashtb)))
2066           ;; Now we have all the words and scores, so we
2067           ;; add these rules to the ADAPT file.
2068           (set-buffer gnus-summary-buffer)
2069           (mapatoms
2070            (lambda (word)
2071              (when (symbol-value word)
2072                (gnus-summary-score-entry
2073                 "subject" (symbol-name word) 'w (symbol-value word)
2074                 date nil t)))
2075            hashtb)))))))
2076
2077 (defun gnus-score-edit-done ()
2078   (let ((bufnam (buffer-file-name (current-buffer)))
2079         (winconf gnus-prev-winconf))
2080     (and winconf (set-window-configuration winconf))
2081     (gnus-score-remove-from-cache bufnam)
2082     (gnus-score-load-file bufnam)))
2083
2084 (defun gnus-score-find-trace ()
2085   "Find all score rules that applies to the current article."
2086   (interactive)
2087   (let ((gnus-newsgroup-headers
2088          (list (gnus-summary-article-header)))
2089         (gnus-newsgroup-scored nil)
2090         trace)
2091     (save-excursion
2092       (nnheader-set-temp-buffer "*Score Trace*"))
2093     (setq gnus-score-trace nil)
2094     (gnus-possibly-score-headers 'trace)
2095     (if (not (setq trace gnus-score-trace))
2096         (gnus-error 1 "No score rules apply to the current article.")
2097       (set-buffer "*Score Trace*")
2098       (gnus-add-current-to-buffer-list)
2099       (while trace
2100         (insert (format "%S  ->  %s\n" (cdar trace)
2101                         (file-name-nondirectory (caar trace))))
2102         (setq trace (cdr trace)))
2103       (goto-char (point-min))
2104       (gnus-configure-windows 'score-trace))))
2105
2106 (defun gnus-score-find-favourite-words ()
2107   "List words used in scoring."
2108   (interactive)
2109   (let ((alists (gnus-score-load-files (gnus-all-score-files)))
2110         alist rule rules kill)
2111     ;; Go through all the score alists for this group
2112     ;; and find all `w' rules.
2113     (while (setq alist (pop alists))
2114       (while (setq rule (pop alist))
2115         (when (and (stringp (car rule))
2116                    (equal "subject" (downcase (pop rule))))
2117           (while (setq kill (pop rule))
2118             (when (memq (nth 3 kill) '(w W word Word))
2119               (push (cons (or (nth 1 kill)
2120                               gnus-score-interactive-default-score)
2121                           (car kill))
2122                     rules))))))
2123     (setq rules (sort rules (lambda (r1 r2)
2124                               (string-lessp (cdr r1) (cdr r2)))))
2125     ;; Add up words that have appeared several times.
2126     (let ((r rules))
2127       (while (cdr r)
2128         (if (equal (cdar r) (cdadr r))
2129             (progn
2130               (setcar (car r) (+ (caar r) (caadr r)))
2131               (setcdr r (cddr r)))
2132           (pop r))))
2133     ;; Insert the words.
2134     (nnheader-set-temp-buffer "*Score Words*")
2135     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2136         (gnus-error 3 "No word score rules")
2137       (while rules
2138         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2139         (pop rules))
2140       (gnus-add-current-to-buffer-list)
2141       (gnus-configure-windows 'score-words))))
2142
2143 (defun gnus-summary-rescore ()
2144   "Redo the entire scoring process in the current summary."
2145   (interactive)
2146   (gnus-score-save)
2147   (setq gnus-score-cache nil)
2148   (setq gnus-newsgroup-scored nil)
2149   (gnus-possibly-score-headers)
2150   (gnus-score-update-all-lines))
2151   
2152 (defun gnus-score-flush-cache ()
2153   "Flush the cache of score files."
2154   (interactive)
2155   (gnus-score-save)
2156   (setq gnus-score-cache nil
2157         gnus-score-alist nil
2158         gnus-short-name-score-file-cache nil)
2159   (gnus-message 6 "The score cache is now flushed"))
2160
2161 (gnus-add-shutdown 'gnus-score-close 'gnus)
2162
2163 (defvar gnus-score-file-alist-cache nil)
2164
2165 (defun gnus-score-close ()
2166   "Clear all internal score variables."
2167   (setq gnus-score-cache nil
2168         gnus-internal-global-score-files nil
2169         gnus-score-file-list nil
2170         gnus-score-file-alist-cache nil))
2171
2172 ;; Summary score marking commands.
2173
2174 (defun gnus-summary-raise-same-subject-and-select (score)
2175   "Raise articles which has the same subject with SCORE and select the next."
2176   (interactive "p")
2177   (let ((subject (gnus-summary-article-subject)))
2178     (gnus-summary-raise-score score)
2179     (while (gnus-summary-find-subject subject)
2180       (gnus-summary-raise-score score))
2181     (gnus-summary-next-article t)))
2182
2183 (defun gnus-summary-raise-same-subject (score)
2184   "Raise articles which has the same subject with SCORE."
2185   (interactive "p")
2186   (let ((subject (gnus-summary-article-subject)))
2187     (gnus-summary-raise-score score)
2188     (while (gnus-summary-find-subject subject)
2189       (gnus-summary-raise-score score))
2190     (gnus-summary-next-subject 1 t)))
2191
2192 (defun gnus-score-default (level)
2193   (if level (prefix-numeric-value level) 
2194     gnus-score-interactive-default-score))
2195
2196 (defun gnus-summary-raise-thread (&optional score)
2197   "Raise the score of the articles in the current thread with SCORE."
2198   (interactive "P")
2199   (setq score (gnus-score-default score))
2200   (let (e)
2201     (save-excursion
2202       (let ((articles (gnus-summary-articles-in-thread)))
2203         (while articles
2204           (gnus-summary-goto-subject (car articles))
2205           (gnus-summary-raise-score score)
2206           (setq articles (cdr articles))))
2207       (setq e (point)))
2208     (let ((gnus-summary-check-current t))
2209       (or (zerop (gnus-summary-next-subject 1 t))
2210           (goto-char e))))
2211   (gnus-summary-recenter)
2212   (gnus-summary-position-point)
2213   (gnus-set-mode-line 'summary))
2214
2215 (defun gnus-summary-lower-same-subject-and-select (score)
2216   "Raise articles which has the same subject with SCORE and select the next."
2217   (interactive "p")
2218   (gnus-summary-raise-same-subject-and-select (- score)))
2219
2220 (defun gnus-summary-lower-same-subject (score)
2221   "Raise articles which has the same subject with SCORE."
2222   (interactive "p")
2223   (gnus-summary-raise-same-subject (- score)))
2224
2225 (defun gnus-summary-lower-thread (&optional score)
2226   "Lower score of articles in the current thread with SCORE."
2227   (interactive "P")
2228   (gnus-summary-raise-thread (- (1- (gnus-score-default score)))))
2229
2230 ;;; Finding score files. 
2231
2232 (defun gnus-score-score-files (group)
2233   "Return a list of all possible score files."
2234   ;; Search and set any global score files.
2235   (and gnus-global-score-files 
2236        (or gnus-internal-global-score-files
2237            (gnus-score-search-global-directories gnus-global-score-files)))
2238   ;; Fix the kill-file dir variable.
2239   (setq gnus-kill-files-directory 
2240         (file-name-as-directory gnus-kill-files-directory))
2241   ;; If we can't read it, there are no score files.
2242   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2243       (setq gnus-score-file-list nil)
2244     (if (not (gnus-use-long-file-name 'not-score))
2245         ;; We do not use long file names, so we have to do some
2246         ;; directory traversing.  
2247         (setq gnus-score-file-list 
2248               (cons nil 
2249                     (or gnus-short-name-score-file-cache
2250                         (prog2
2251                             (gnus-message 6 "Finding all score files...")
2252                             (setq gnus-short-name-score-file-cache
2253                                   (gnus-score-score-files-1
2254                                    gnus-kill-files-directory))
2255                           (gnus-message 6 "Finding all score files...done")))))
2256       ;; We want long file names.
2257       (when (or (not gnus-score-file-list)
2258                 (not (car gnus-score-file-list))
2259                 (gnus-file-newer-than gnus-kill-files-directory
2260                                       (car gnus-score-file-list)))
2261         (setq gnus-score-file-list 
2262               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2263                     (nreverse 
2264                      (directory-files 
2265                       gnus-kill-files-directory t 
2266                       (gnus-score-file-regexp)))))))
2267     (cdr gnus-score-file-list)))
2268
2269 (defun gnus-score-score-files-1 (dir)
2270   "Return all possible score files under DIR."
2271   (let ((files (directory-files (expand-file-name dir) t nil t))
2272         (regexp (gnus-score-file-regexp))
2273         (case-fold-search nil)
2274         out file)
2275     (while (setq file (pop files))
2276       (cond 
2277        ;; Ignore "." and "..".
2278        ((member (file-name-nondirectory file) '("." ".."))
2279         nil)
2280        ;; Recurse down directories.
2281        ((file-directory-p file)
2282         (setq out (nconc (gnus-score-score-files-1 file) out)))
2283        ;; Add files to the list of score files.
2284        ((string-match regexp file)
2285         (push file out))))
2286     (or out
2287         ;; Return a dummy value.
2288         (list "~/News/this.file.does.not.exist.SCORE"))))
2289        
2290 (defun gnus-score-file-regexp ()
2291   "Return a regexp that match all score files."
2292   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2293           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2294         
2295 (defun gnus-score-find-bnews (group)
2296   "Return a list of score files for GROUP.
2297 The score files are those files in the ~/News/ directory which matches
2298 GROUP using BNews sys file syntax."
2299   (let* ((sfiles (append (gnus-score-score-files group)
2300                          gnus-internal-global-score-files))
2301          (kill-dir (file-name-as-directory 
2302                     (expand-file-name gnus-kill-files-directory)))
2303          (klen (length kill-dir))
2304          (score-regexp (gnus-score-file-regexp))
2305          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2306          ofiles not-match regexp)
2307     (save-excursion
2308       (set-buffer (get-buffer-create "*gnus score files*"))
2309       (buffer-disable-undo (current-buffer))
2310       ;; Go through all score file names and create regexp with them
2311       ;; as the source.  
2312       (while sfiles
2313         (erase-buffer)
2314         (insert (car sfiles))
2315         (goto-char (point-min))
2316         ;; First remove the suffix itself.
2317         (when (re-search-forward (concat "." score-regexp) nil t)
2318           (replace-match "" t t) 
2319           (goto-char (point-min))
2320           (if (looking-at (regexp-quote kill-dir))
2321               ;; If the file name was just "SCORE", `klen' is one character
2322               ;; too much.
2323               (delete-char (min (1- (point-max)) klen))
2324             (goto-char (point-max))
2325             (search-backward "/")
2326             (delete-region (1+ (point)) (point-min)))
2327           ;; If short file names were used, we have to translate slashes.
2328           (goto-char (point-min))
2329           (let ((regexp (concat
2330                          "[/:" (if trans (char-to-string trans) "") "]")))
2331             (while (re-search-forward regexp nil t)
2332               (replace-match "." t t)))
2333           ;; Kludge to get rid of "nntp+" problems.
2334           (goto-char (point-min))
2335           (and (looking-at "nn[a-z]+\\+")
2336                (progn
2337                  (search-forward "+")
2338                  (forward-char -1)
2339                  (insert "\\")))
2340           ;; Kludge to deal with "++".
2341           (goto-char (point-min))
2342           (while (search-forward "++" nil t)
2343             (replace-match "\\+\\+" t t))
2344           ;; Translate "all" to ".*".
2345           (goto-char (point-min))
2346           (while (search-forward "all" nil t)
2347             (replace-match ".*" t t))
2348           (goto-char (point-min))
2349           ;; Deal with "not."s.
2350           (if (looking-at "not.")
2351               (progn
2352                 (setq not-match t)
2353                 (setq regexp (buffer-substring 5 (point-max))))
2354             (setq regexp (buffer-substring 1 (point-max)))
2355             (setq not-match nil))
2356           ;; Finally - if this resulting regexp matches the group name,
2357           ;; we add this score file to the list of score files
2358           ;; applicable to this group.
2359           (if (or (and not-match
2360                        (not (string-match regexp group)))
2361                   (and (not not-match)
2362                        (string-match regexp group)))
2363               (setq ofiles (cons (car sfiles) ofiles))))
2364         (setq sfiles (cdr sfiles)))
2365       (kill-buffer (current-buffer))
2366       ;; Slight kludge here - the last score file returned should be
2367       ;; the local score file, whether it exists or not.  This is so
2368       ;; that any score commands the user enters will go to the right
2369       ;; file, and not end up in some global score file.
2370       (let ((localscore (gnus-score-file-name group)))
2371         (setq ofiles (cons localscore (delete localscore ofiles))))
2372       (gnus-sort-score-files (nreverse ofiles)))))
2373
2374 (defun gnus-score-find-single (group)
2375   "Return list containing the score file for GROUP."
2376   (list (or gnus-newsgroup-adaptive-score-file
2377             (gnus-score-file-name group gnus-adaptive-file-suffix))
2378         (gnus-score-file-name group)))
2379
2380 (defun gnus-score-find-hierarchical (group)
2381   "Return list of score files for GROUP.
2382 This includes the score file for the group and all its parents."
2383   (let ((all (copy-sequence '(nil)))
2384         (start 0))
2385     (while (string-match "\\." group (1+ start))
2386       (setq start (match-beginning 0))
2387       (setq all (cons (substring group 0 start) all)))
2388     (setq all (cons group all))
2389     (nconc
2390      (mapcar (lambda (newsgroup)
2391                (gnus-score-file-name newsgroup gnus-adaptive-file-suffix))
2392              (setq all (nreverse all)))
2393      (mapcar 'gnus-score-file-name all))))
2394
2395 (defun gnus-score-file-rank (file)
2396   "Return a number that says how specific score FILE is.
2397 Destroys the current buffer."
2398   (when (string-match
2399          (concat "^" (regexp-quote
2400                       (expand-file-name
2401                        (file-name-as-directory gnus-kill-files-directory))))
2402          file)
2403     (setq file (substring file (match-end 0))))
2404   (insert file)
2405   (goto-char (point-min))
2406   (let ((beg (point))
2407         elems)
2408     (while (re-search-forward "[./]" nil t)
2409       (push (buffer-substring beg (1- (point))) 
2410             elems))
2411     (erase-buffer)
2412     (setq elems (delete "all" elems))
2413     (length elems)))
2414     
2415 (defun gnus-sort-score-files (files)
2416   "Sort FILES so that the most general files come first."
2417   (nnheader-temp-write nil
2418     (let ((alist
2419            (mapcar
2420             (lambda (file)
2421               (cons (inline (gnus-score-file-rank file)) file))
2422             files)))
2423       (mapcar
2424        (lambda (f) (cdr f))
2425        (sort alist (lambda (f1 f2) (< (car f1) (car f2))))))))
2426
2427 (defun gnus-score-find-alist (group)
2428   "Return list of score files for GROUP.
2429 The list is determined from the variable gnus-score-file-alist."
2430   (let ((alist gnus-score-file-multiple-match-alist)
2431         score-files)
2432     ;; if this group has been seen before, return the cached entry
2433     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2434         (cdr score-files)               ;ensures caching groups with no matches
2435       ;; handle the multiple match alist
2436       (while alist
2437         (and (string-match (caar alist) group)
2438              (setq score-files
2439                    (nconc score-files (copy-sequence (cdar alist)))))
2440         (setq alist (cdr alist)))
2441       (setq alist gnus-score-file-single-match-alist)
2442       ;; handle the single match alist
2443       (while alist
2444         (and (string-match (caar alist) group)
2445              ;; progn used just in case ("regexp") has no files
2446              ;; and score-files is still nil.  -sj
2447              ;; this can be construed as a "stop searching here" feature :>
2448              ;; and used to simplify regexps in the single-alist 
2449              (progn
2450                (setq score-files
2451                      (nconc score-files (copy-sequence (cdar alist))))
2452                (setq alist nil)))
2453         (setq alist (cdr alist)))
2454       ;; cache the score files
2455       (setq gnus-score-file-alist-cache
2456             (cons (cons group score-files) gnus-score-file-alist-cache))
2457       score-files)))
2458
2459 (defun gnus-all-score-files ()
2460   "Return a list of all score files for the current group."
2461   (let ((funcs gnus-score-find-score-files-function)
2462         (group gnus-newsgroup-name)
2463         score-files)
2464     ;; Make sure funcs is a list.
2465     (and funcs
2466          (not (listp funcs))
2467          (setq funcs (list funcs)))
2468     ;; Get the initial score files for this group.
2469     (when funcs 
2470       (setq score-files (gnus-score-find-alist group)))
2471     ;; Add any home adapt files.
2472     (let ((home (gnus-home-score-file group t)))
2473       (when home
2474         (push home score-files)
2475         (setq gnus-newsgroup-adaptive-score-file home)))
2476     ;; Check whether there is a `adapt-file' group parameter.
2477     (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2478       (when param-file
2479         (push param-file score-files)
2480         (setq gnus-newsgroup-adaptive-score-file param-file)))
2481     ;; Go through all the functions for finding score files (or actual
2482     ;; scores) and add them to a list.
2483     (while funcs
2484       (when (gnus-functionp (car funcs))
2485         (setq score-files 
2486               (nconc score-files (funcall (car funcs) group))))
2487       (setq funcs (cdr funcs)))
2488     ;; Add any home score files.
2489     (let ((home (gnus-home-score-file group)))
2490       (when home
2491         (push home score-files)))
2492     ;; Check whether there is a `score-file' group parameter.
2493     (let ((param-file (gnus-group-find-parameter group 'score-file)))
2494       (when param-file
2495         (push param-file score-files)))
2496     ;; Do the scoring if there are any score files for this group.
2497     score-files))
2498     
2499 (defun gnus-possibly-score-headers (&optional trace)
2500   "Do scoring if scoring is required."
2501   (let ((score-files (gnus-all-score-files)))
2502     (when score-files
2503       (gnus-score-headers score-files trace))))
2504
2505 (defun gnus-score-file-name (newsgroup &optional suffix)
2506   "Return the name of a score file for NEWSGROUP."
2507   (let ((suffix (or suffix gnus-score-file-suffix)))
2508     (nnheader-translate-file-chars
2509      (cond
2510       ((or (null newsgroup)
2511            (string-equal newsgroup ""))
2512        ;; The global score file is placed at top of the directory.
2513        (expand-file-name 
2514         suffix gnus-kill-files-directory))
2515       ((gnus-use-long-file-name 'not-score)
2516        ;; Append ".SCORE" to newsgroup name.
2517        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2518                                  "." suffix)
2519                          gnus-kill-files-directory))
2520       (t
2521        ;; Place "SCORE" under the hierarchical directory.
2522        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2523                                  "/" suffix)
2524                          gnus-kill-files-directory))))))
2525
2526 (defun gnus-score-search-global-directories (files)
2527   "Scan all global score directories for score files."
2528   ;; Set the variable `gnus-internal-global-score-files' to all
2529   ;; available global score files.
2530   (interactive (list gnus-global-score-files))
2531   (let (out)
2532     (while files
2533       (if (string-match "/$" (car files))
2534           (setq out (nconc (directory-files 
2535                             (car files) t
2536                             (concat (gnus-score-file-regexp) "$"))))
2537         (setq out (cons (car files) out)))
2538       (setq files (cdr files)))
2539     (setq gnus-internal-global-score-files out)))
2540
2541 (defun gnus-score-default-fold-toggle ()
2542   "Toggle folding for new score file entries."
2543   (interactive)
2544   (setq gnus-score-default-fold (not gnus-score-default-fold))
2545   (if gnus-score-default-fold
2546       (gnus-message 1 "New score file entries will be case insensitive.")
2547     (gnus-message 1 "New score file entries will be case sensitive.")))
2548
2549 ;;; Home score file.
2550
2551 (defun gnus-home-score-file (group &optional adapt)
2552   "Return the home score file for GROUP.
2553 If ADAPT, return the home adaptive file instead."
2554   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2555         elem found)
2556     ;; Make sure we have a list.
2557     (unless (listp list)
2558       (setq list (list list)))
2559     ;; Go through the list and look for matches.
2560     (while (and (not found)
2561                 (setq elem (pop list)))
2562       (setq found
2563             (cond
2564              ;; Simple string.
2565              ((stringp elem)
2566               elem)
2567              ;; Function.
2568              ((gnus-functionp elem)
2569               (funcall elem group))
2570              ;; Regexp-file cons
2571              ((consp elem)
2572               (when (string-match (car elem) group)
2573                 (cadr elem))))))
2574     (when found
2575       (nnheader-concat gnus-kill-files-directory found))))
2576
2577 (defun gnus-hierarchial-home-score-file (group)
2578   "Return the score file of the top-level hierarchy of GROUP."
2579   (if (string-match "^[^.]+\\." group)
2580       (concat (match-string 0 group) gnus-score-file-suffix)
2581     ;; Group name without any dots.
2582     (concat group "." gnus-score-file-suffix)))
2583       
2584 (defun gnus-hierarchial-home-adapt-file (group)
2585   "Return the adapt file of the top-level hierarchy of GROUP."
2586   (if (string-match "^[^.]+\\." group)
2587       (concat (match-string 0 group) gnus-adaptive-file-suffix)
2588     ;; Group name without any dots.
2589     (concat group "." gnus-adaptive-file-suffix)))
2590
2591 ;;;
2592 ;;; Score decays
2593 ;;;
2594
2595 (defun gnus-decay-score (score)
2596   "Decay SCORE."
2597   (floor
2598    (- score
2599       (* (if (< score 0) 1 -1)
2600          (min score
2601               (max gnus-score-decay-constant
2602                    (* (abs score)
2603                       gnus-score-decay-scale)))))))
2604
2605 (defun gnus-decay-scores (alist day)
2606   "Decay non-permanent scores in ALIST."
2607   (let ((times (- (gnus-time-to-day (current-time)) day))
2608         kill entry updated score n)
2609     (unless (zerop times)               ;Done decays today already?
2610       (while (setq entry (pop alist))
2611         (when (stringp (car entry))
2612           (setq entry (cdr entry))
2613           (while (setq kill (pop entry))
2614             (when (nth 2 kill)
2615               (setq updated t)
2616               (setq score (or (car kill) gnus-score-interactive-default-score)
2617                     n times)
2618               (while (natnump (decf n))
2619                 (setq score (funcall gnus-decay-score-function score)))
2620               (setcar kill score))))))
2621     ;; Return whether this score file needs to be saved.  By Je-haysuss!
2622     updated))
2623
2624 (provide 'gnus-score)
2625
2626 ;;; gnus-score.el ends here