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