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