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