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