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