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