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