*** 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-default-adaptive-word-score-alist  
191   `((,gnus-read-mark . 30)
192     (,gnus-catchup-mark . -10)
193     (,gnus-killed-mark . -20)
194     (,gnus-del-mark . -15))
195 "*Alist of marks and scores.")
196
197 (defvar gnus-score-mimic-keymap nil
198   "*Have the score entry functions pretend that they are a keymap.")
199
200 (defvar gnus-score-exact-adapt-limit 10
201   "*Number that says how long a match has to be before using substring matching.
202 When doing adaptive scoring, one normally uses fuzzy or substring
203 matching.  However, if the header one matches is short, the possibility
204 for false positives is great, so if the length of the match is less
205 than this variable, exact matching will be used.
206
207 If this variable is nil, exact matching will always be used.")
208
209 (defvar gnus-score-uncacheable-files "ADAPT$"
210   "*All score files that match this regexp will not be cached.")
211
212 (defvar gnus-score-default-header nil
213   "Default header when entering new scores.
214
215 Should be one of the following symbols.
216
217  a: from
218  s: subject
219  b: body
220  h: head
221  i: message-id
222  t: references
223  x: xref
224  l: lines
225  d: date
226  f: followup
227
228 If nil, the user will be asked for a header.")
229
230 (defvar gnus-score-default-type nil
231   "Default match type when entering new scores.
232
233 Should be one of the following symbols.
234
235  s: substring
236  e: exact string
237  f: fuzzy string
238  r: regexp string
239  b: before date
240  a: at date
241  n: this date
242  <: less than number
243  >: greater than number
244  =: equal to number
245
246 If nil, the user will be asked for a match type.")
247
248 (defvar gnus-score-default-fold nil
249   "Use case folding for new score file entries iff not nil.")
250
251 (defvar gnus-score-default-duration nil
252   "Default duration of effect when entering new scores.
253
254 Should be one of the following symbols.
255
256  t: temporary
257  p: permanent
258  i: immediate
259
260 If nil, the user will be asked for a duration.")
261
262 (defvar gnus-score-after-write-file-function nil
263   "*Function called with the name of the score file just written to disk.")
264
265 \f
266
267 ;; Internal variables.
268
269 (defvar gnus-adaptive-word-syntax-table
270   (let ((table (copy-syntax-table (standard-syntax-table)))
271         (numbers '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9)))
272     (while numbers
273       (modify-syntax-entry (pop numbers) " " table))
274     table)
275   "Syntax table used when doing adaptive word scoring.")
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-adaptive-word-score-alist gnus-default-adaptive-word-score-alist)
286 (defvar gnus-score-trace nil)
287 (defvar gnus-score-edit-buffer nil)
288
289 (defvar gnus-score-alist nil
290   "Alist containing score information.
291 The keys can be symbols or strings.  The following symbols are defined. 
292
293 touched: If this alist has been modified.
294 mark:    Automatically mark articles below this.
295 expunge: Automatically expunge articles below this.
296 files:   List of other score files to load when loading this one.
297 eval:    Sexp to be evaluated when the score file is loaded.
298
299 String entries have the form (HEADER (MATCH TYPE SCORE DATE) ...) 
300 where HEADER is the header being scored, MATCH is the string we are
301 looking for, TYPE is a flag indicating whether it should use regexp or
302 substring matching, SCORE is the score to add and DATE is the date
303 of the last successful match.")
304
305 (defvar gnus-score-cache nil)
306 (defvar gnus-scores-articles nil)
307 (defvar gnus-score-index nil)
308
309
310 (defconst gnus-header-index
311   ;; Name to index alist.
312   '(("number" 0 gnus-score-integer)
313     ("subject" 1 gnus-score-string)
314     ("from" 2 gnus-score-string)
315     ("date" 3 gnus-score-date)
316     ("message-id" 4 gnus-score-string) 
317     ("references" 5 gnus-score-string) 
318     ("chars" 6 gnus-score-integer) 
319     ("lines" 7 gnus-score-integer) 
320     ("xref" 8 gnus-score-string)
321     ("head" -1 gnus-score-body)
322     ("body" -1 gnus-score-body)
323     ("all" -1 gnus-score-body)
324     ("followup" 2 gnus-score-followup)
325     ("thread" 5 gnus-score-thread)))
326
327 (eval-and-compile
328   (autoload 'gnus-uu-ctl-map "gnus-uu" nil nil 'keymap))
329
330 ;;; Summary mode score maps.
331
332 (gnus-define-keys (gnus-summary-score-map "V" gnus-summary-mode-map)
333   "s" gnus-summary-set-score
334   "a" gnus-summary-score-entry
335   "S" gnus-summary-current-score
336   "c" gnus-score-change-score-file
337   "m" gnus-score-set-mark-below
338   "x" gnus-score-set-expunge-below
339   "R" gnus-summary-rescore
340   "e" gnus-score-edit-current-scores
341   "f" gnus-score-edit-file
342   "F" gnus-score-flush-cache
343   "t" gnus-score-find-trace
344   "w" gnus-score-find-favourite-words
345   "C" gnus-score-customize)
346
347 ;; Summary score file commands
348
349 ;; Much modification of the kill (ahem, score) code and lots of the
350 ;; functions are written by Per Abrahamsen <amanda@iesd.auc.dk>.
351
352 (defun gnus-summary-lower-score (&optional score)
353   "Make a score entry based on the current article.
354 The user will be prompted for header to score on, match type,
355 permanence, and the string to be used.  The numerical prefix will be
356 used as score."
357   (interactive "P")
358   (gnus-summary-increase-score (- (gnus-score-default score))))
359
360 (defvar gnus-score-default-header nil
361   "*The default header to score on when entering a score rule interactively.")
362
363 (defvar gnus-score-default-type nil
364   "*The default score type to use when entering a score rule interactively.")
365
366 (defvar gnus-score-default-duration nil
367   "*The default score duration to use on when entering a score rule interactively.")
368
369 (defun gnus-score-kill-help-buffer ()
370   (when (get-buffer "*Score Help*")
371     (kill-buffer "*Score Help*")
372     (and gnus-score-help-winconf
373          (set-window-configuration gnus-score-help-winconf))))
374
375 (defun gnus-summary-increase-score (&optional score)
376   "Make a score entry based on the current article.
377 The user will be prompted for header to score on, match type,
378 permanence, and the string to be used.  The numerical prefix will be
379 used as score."
380   (interactive "P")
381   (gnus-set-global-variables)
382   (let* ((nscore (gnus-score-default score))
383          (prefix (if (< nscore 0) ?L ?I))
384          (increase (> nscore 0))
385          (char-to-header 
386           '((?a "from" nil nil string)
387             (?s "subject" nil nil string)
388             (?b "body" "" nil body-string)
389             (?h "head" "" nil body-string)
390             (?i "message-id" nil t string)
391             (?t "references" "message-id" nil string)
392             (?x "xref" nil nil string)
393             (?l "lines" nil nil number)
394             (?d "date" nil nil date)
395             (?f "followup" nil nil string)
396             (?T "thread" nil nil string)))
397          (char-to-type
398           '((?s s "substring" string)
399             (?e e "exact string" string)
400             (?f f "fuzzy string" string)
401             (?r r "regexp string" string)
402             (?z s "substring" body-string)
403             (?p s "regexp string" body-string)
404             (?b before "before date" date)
405             (?a at "at date" date) 
406             (?n now "this date" date)
407             (?< < "less than number" number)
408             (?> > "greater than number" number) 
409             (?= = "equal to number" number)))
410          (char-to-perm
411           (list (list ?t (current-time-string) "temporary") 
412                 '(?p perm "permanent") '(?i now "immediate")))
413          (mimic gnus-score-mimic-keymap)
414          (hchar (and gnus-score-default-header 
415                      (aref (symbol-name gnus-score-default-header) 0)))
416          (tchar (and gnus-score-default-type
417                      (aref (symbol-name gnus-score-default-type) 0)))
418          (pchar (and gnus-score-default-duration
419                      (aref (symbol-name gnus-score-default-duration) 0)))
420          entry temporary type match)
421     
422     (unwind-protect
423         (progn
424
425           ;; First we read the header to score.
426           (while (not hchar)
427             (if mimic
428                 (progn 
429                   (sit-for 1)
430                   (message "%c-" prefix))
431               (message "%s header (%s?): " (if increase "Increase" "Lower")
432                        (mapconcat (lambda (s) (char-to-string (car s)))
433                                   char-to-header "")))
434             (setq hchar (read-char))
435             (when (or (= hchar ??) (= hchar ?\C-h))
436               (setq hchar nil)
437               (gnus-score-insert-help "Match on header" char-to-header 1)))
438
439           (gnus-score-kill-help-buffer)
440           (unless (setq entry (assq (downcase hchar) char-to-header))
441             (if mimic (error "%c %c" prefix hchar) (error "")))
442
443           (when (/= (downcase hchar) hchar)
444             ;; This was a majuscle, so we end reading and set the defaults.
445             (if mimic (message "%c %c" prefix hchar) (message ""))
446             (setq tchar (or tchar ?s)
447                   pchar (or pchar ?t)))
448     
449           ;; We continue reading - the type.
450           (while (not tchar)
451             (if mimic
452                 (progn
453                   (sit-for 1) (message "%c %c-" prefix hchar))
454               (message "%s header '%s' with match type (%s?): "
455                        (if increase "Increase" "Lower")
456                        (nth 1 entry)
457                        (mapconcat (lambda (s) 
458                                     (if (eq (nth 4 entry) 
459                                             (nth 3 s))
460                                         (char-to-string (car s))
461                                       ""))
462                                   char-to-type "")))
463             (setq tchar (read-char))
464             (when (or (= tchar ??) (= tchar ?\C-h))
465               (setq tchar nil)
466               (gnus-score-insert-help
467                "Match type"
468                (delq nil
469                      (mapcar (lambda (s) 
470                                (if (eq (nth 4 entry) 
471                                        (nth 3 s))
472                                    s nil))
473                              char-to-type ))
474                2)))
475
476           (gnus-score-kill-help-buffer)
477           (unless (setq type (nth 1 (assq (downcase tchar) char-to-type)))
478             (if mimic (error "%c %c" prefix hchar) (error "")))
479
480           (when (/= (downcase tchar) tchar)
481             ;; It was a majuscle, so we end reading and use the default.
482             (if mimic (message "%c %c %c" prefix hchar tchar)
483               (message ""))
484             (setq pchar (or pchar ?p)))
485
486           ;; We continue reading.
487           (while (not pchar)
488             (if mimic
489                 (progn
490                   (sit-for 1) (message "%c %c %c-" prefix hchar tchar))
491               (message "%s permanence (%s?): " (if increase "Increase" "Lower")
492                        (mapconcat (lambda (s) (char-to-string (car s)))
493                                   char-to-perm "")))
494             (setq pchar (read-char))
495             (when (or (= pchar ??) (= pchar ?\C-h))
496               (setq pchar nil)
497               (gnus-score-insert-help "Match permanence" char-to-perm 2)))
498
499           (gnus-score-kill-help-buffer)
500           (if mimic (message "%c %c %c" prefix hchar tchar pchar)
501             (message ""))
502           (unless (setq temporary (cadr (assq pchar char-to-perm)))
503             (if mimic 
504                 (error "%c %c %c %c" prefix hchar tchar pchar)
505               (error ""))))
506       ;; Always kill the score help buffer.
507       (gnus-score-kill-help-buffer))
508
509     ;; We have all the data, so we enter this score.
510     (setq match (if (string= (nth 2 entry) "") ""
511                   (gnus-summary-header (or (nth 2 entry) (nth 1 entry)))))
512       
513     ;; Modify the match, perhaps.
514     (cond 
515      ((equal (nth 1 entry) "xref")
516       (when (string-match "^Xref: *" match)
517         (setq match (substring match (match-end 0))))
518       (when (string-match "^[^:]* +" match)
519         (setq match (substring match (match-end 0))))))
520     
521     (when (memq type '(r R regexp Regexp))
522       (setq match (regexp-quote match)))
523
524     (gnus-summary-score-entry
525      (nth 1 entry)                      ; Header
526      match                              ; Match
527      type                               ; Type
528      (if (eq 's score) nil score)       ; Score
529      (if (eq 'perm temporary)           ; Temp
530          nil
531         temporary)
532      (not (nth 3 entry)))               ; Prompt
533     ))
534   
535 (defun gnus-score-insert-help (string alist idx)
536   (setq gnus-score-help-winconf (current-window-configuration))
537   (save-excursion
538     (set-buffer (get-buffer-create "*Score Help*"))
539     (buffer-disable-undo (current-buffer))
540     (delete-windows-on (current-buffer))
541     (erase-buffer)
542     (insert string ":\n\n")
543     (let ((max -1)
544           (list alist)
545           (i 0)
546           n width pad format)
547       ;; find the longest string to display
548       (while list
549         (setq n (length (nth idx (car list))))
550         (or (> max n)
551             (setq max n))
552         (setq list (cdr list)))
553       (setq max (+ max 4))              ; %c, `:', SPACE, a SPACE at end
554       (setq n (/ (1- (window-width)) max))      ; items per line
555       (setq width (/ (1- (window-width)) n)) ; width of each item
556       ;; insert `n' items, each in a field of width `width' 
557       (while alist
558         (if (< i n)
559             ()
560           (setq i 0)
561           (delete-char -1)              ; the `\n' takes a char
562           (insert "\n"))
563         (setq pad (- width 3))
564         (setq format (concat "%c: %-" (int-to-string pad) "s"))
565         (insert (format format (caar alist) (nth idx (car alist))))
566         (setq alist (cdr alist))
567         (setq i (1+ i))))
568     ;; display ourselves in a small window at the bottom
569     (gnus-appt-select-lowest-window)
570     (split-window)
571     (pop-to-buffer "*Score Help*")
572     (let ((window-min-height 1))
573       (shrink-window-if-larger-than-buffer))
574     (select-window (get-buffer-window gnus-summary-buffer))))
575   
576 (defun gnus-summary-header (header &optional no-err)
577   ;; Return HEADER for current articles, or error.
578   (let ((article (gnus-summary-article-number))
579         headers)
580     (if article
581         (if (and (setq headers (gnus-summary-article-header article))
582                  (vectorp headers))
583             (aref headers (nth 1 (assoc header gnus-header-index)))
584           (if no-err
585               nil
586             (error "Pseudo-articles can't be scored")))
587       (if no-err
588           (error "No article on current line")
589         nil))))
590
591 (defun gnus-newsgroup-score-alist ()
592   (or
593    (let ((param-file (gnus-group-find-parameter 
594                       gnus-newsgroup-name 'score-file)))
595      (when param-file
596        (gnus-score-load param-file)))
597    (gnus-score-load
598     (gnus-score-file-name gnus-newsgroup-name)))
599   gnus-score-alist)
600
601 (defsubst gnus-score-get (symbol &optional alist)
602   ;; Get SYMBOL's definition in ALIST.
603   (cdr (assoc symbol 
604               (or alist 
605                   gnus-score-alist
606                   (gnus-newsgroup-score-alist)))))
607
608 (defun gnus-summary-score-entry (header match type score date
609                                         &optional prompt silent)
610   "Enter score file entry.
611 HEADER is the header being scored.
612 MATCH is the string we are looking for.
613 TYPE is the match type: substring, regexp, exact, fuzzy.
614 SCORE is the score to add.
615 DATE is the expire date, or nil for no expire, or 'now for immediate expire.
616 If optional argument `PROMPT' is non-nil, allow user to edit match.
617 If optional argument `SILENT' is nil, show effect of score entry."
618   (interactive
619    (list (completing-read "Header: "
620                           gnus-header-index
621                           (lambda (x) (fboundp (nth 2 x)))
622                           t)
623          (read-string "Match: ")
624          (if (y-or-n-p "Use regexp match? ") 'r 's)
625          (and current-prefix-arg
626               (prefix-numeric-value current-prefix-arg))
627          (cond ((not (y-or-n-p "Add to score file? "))
628                 'now)
629                ((y-or-n-p "Expire kill? ")
630                 (current-time-string))
631                (t nil))))
632   ;; Regexp is the default type.
633   (if (eq type t) (setq type 'r))
634   ;; Simplify matches...
635   (cond ((or (eq type 'r) (eq type 's) (eq type nil))
636          (setq match (if match (gnus-simplify-subject-re match) "")))
637         ((eq type 'f)
638          (setq match (gnus-simplify-subject-fuzzy match))))
639   (let ((score (gnus-score-default score))
640         (header (format "%s" (downcase header)))
641         new)
642     (when prompt
643       (setq match (read-string 
644                    (format "Match %s on %s, %s: " 
645                            (cond ((eq date 'now)
646                                   "now")
647                                  ((stringp date)
648                                   "temp")
649                                  (t "permanent"))
650                            header
651                            (if (< score 0) "lower" "raise"))
652                    (if (numberp match)
653                        (int-to-string match)
654                      match))))
655
656     ;; Get rid of string props.
657     (setq match (format "%s" match))
658
659     ;; If this is an integer comparison, we transform from string to int. 
660     (and (eq (nth 2 (assoc header gnus-header-index)) 'gnus-score-integer)
661          (setq match (string-to-int match)))
662
663     (unless (eq date 'now)
664       ;; Add the score entry to the score file.
665       (when (= score gnus-score-interactive-default-score)
666            (setq score nil))
667       (let ((old (gnus-score-get header))
668             elem)
669         (setq new
670               (cond 
671                (type
672                 (list match score
673                       (and date (if (numberp date) date
674                                   (gnus-day-number date)))
675                       type))
676                (date (list match score (gnus-day-number date)))
677                (score (list match score))
678                (t (list match))))
679         ;; We see whether we can collapse some score entries.
680         ;; This isn't quite correct, because there may be more elements
681         ;; later on with the same key that have matching elems... Hm.
682         (if (and old
683                  (setq elem (assoc match old))
684                  (eq (nth 3 elem) (nth 3 new))
685                  (or (and (numberp (nth 2 elem)) (numberp (nth 2 new)))
686                      (and (not (nth 2 elem)) (not (nth 2 new)))))
687             ;; Yup, we just add this new score to the old elem.
688             (setcar (cdr elem) (+ (or (nth 1 elem) 
689                                       gnus-score-interactive-default-score)
690                                   (or (nth 1 new)
691                                       gnus-score-interactive-default-score)))
692           ;; Nope, we have to add a new elem.
693           (gnus-score-set header (if old (cons new old) (list new))))
694         (gnus-score-set 'touched '(t))))
695
696     ;; Score the current buffer.
697     (unless silent
698       (if (and (>= (nth 1 (assoc header gnus-header-index)) 0)
699                (eq (nth 2 (assoc header gnus-header-index))
700                    'gnus-score-string))
701           (gnus-summary-score-effect header match type score)
702         (gnus-summary-rescore)))
703
704     ;; Return the new scoring rule.
705     new))
706
707 (defun gnus-summary-score-effect (header match type score)
708   "Simulate the effect of a score file entry.
709 HEADER is the header being scored.
710 MATCH is the string we are looking for.
711 TYPE is a flag indicating if it is a regexp or substring.
712 SCORE is the score to add."
713   (interactive (list (completing-read "Header: "
714                                       gnus-header-index
715                                       (lambda (x) (fboundp (nth 2 x)))
716                                       t)
717                      (read-string "Match: ")
718                      (y-or-n-p "Use regexp match? ")
719                      (prefix-numeric-value current-prefix-arg)))
720   (save-excursion
721     (or (and (stringp match) (> (length match) 0))
722         (error "No match"))
723     (goto-char (point-min))
724     (let ((regexp (cond ((eq type 'f)
725                          (gnus-simplify-subject-fuzzy match))
726                         ((eq type 'r) 
727                          match)
728                         ((eq type 'e)
729                          (concat "\\`" (regexp-quote match) "\\'"))
730                         (t 
731                          (regexp-quote match)))))
732       (while (not (eobp))
733         (let ((content (gnus-summary-header header 'noerr))
734               (case-fold-search t))
735           (and content
736                (if (if (eq type 'f)
737                        (string-equal (gnus-simplify-subject-fuzzy content)
738                                      regexp)
739                      (string-match regexp content))
740                    (gnus-summary-raise-score score))))
741         (beginning-of-line 2)))))
742
743 (defun gnus-summary-score-crossposting (score date)
744   ;; Enter score file entry for current crossposting.
745   ;; SCORE is the score to add.
746   ;; DATE is the expire date.
747   (let ((xref (gnus-summary-header "xref"))
748         (start 0)
749         group)
750     (or xref (error "This article is not crossposted"))
751     (while (string-match " \\([^ \t]+\\):" xref start)
752       (setq start (match-end 0))
753       (if (not (string= 
754                 (setq group 
755                       (substring xref (match-beginning 1) (match-end 1)))
756                 gnus-newsgroup-name))
757           (gnus-summary-score-entry
758            "xref" (concat " " group ":") nil score date t)))))
759
760 \f
761 ;;;
762 ;;; Gnus Score Files
763 ;;;
764
765 ;; All score code written by Per Abrahamsen <abraham@iesd.auc.dk>.
766
767 ;; Added by Per Abrahamsen <amanda@iesd.auc.dk>.
768 (defun gnus-score-set-mark-below (score)
769   "Automatically mark articles with score below SCORE as read."
770   (interactive 
771    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
772              (string-to-int (read-string "Mark below: ")))))
773   (setq score (or score gnus-summary-default-score 0))
774   (gnus-score-set 'mark (list score))
775   (gnus-score-set 'touched '(t))
776   (setq gnus-summary-mark-below score)
777   (gnus-score-update-lines))
778
779 (defun gnus-score-update-lines ()
780   "Update all lines in the summary buffer."
781   (save-excursion
782     (goto-char (point-min))
783     (while (not (eobp))
784       (gnus-summary-update-line)
785       (forward-line 1))))
786
787 (defun gnus-score-update-all-lines ()
788   "Update all lines in the summary buffer, even the hidden ones."
789   (save-excursion
790     (goto-char (point-min))
791     (let (hidden)
792       (while (not (eobp))
793         (when (gnus-summary-show-thread)
794           (push (point) hidden))
795         (gnus-summary-update-line)
796         (forward-line 1))
797       ;; Re-hide the hidden threads.
798       (while hidden
799         (goto-char (pop hidden))
800         (gnus-summary-hide-thread)))))
801
802 (defun gnus-score-set-expunge-below (score)
803   "Automatically expunge articles with score below SCORE."
804   (interactive 
805    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
806              (string-to-int (read-string "Set expunge below: ")))))
807   (setq score (or score gnus-summary-default-score 0))
808   (gnus-score-set 'expunge (list score))
809   (gnus-score-set 'touched '(t)))
810
811 (defun gnus-score-followup-article (&optional score)
812   "Add SCORE to all followups to the article in the current buffer."
813   (interactive "P")
814   (setq score (gnus-score-default score))
815   (when (gnus-buffer-live-p gnus-summary-buffer)
816     (save-excursion
817       (save-restriction
818         (message-narrow-to-headers)
819         (let ((id (mail-fetch-field "message-id")))
820           (when id
821             (set-buffer gnus-summary-buffer)
822             (gnus-summary-score-entry
823              "references" (concat id "[ \t]*$") 'r
824              score (current-time-string) nil t)))))))
825
826 (defun gnus-score-followup-thread (&optional score)
827   "Add SCORE to all later articles in the thread the current buffer is part of."
828   (interactive "P")
829   (setq score (gnus-score-default score))
830   (when (gnus-buffer-live-p gnus-summary-buffer)
831     (save-excursion
832       (save-restriction
833         (goto-char (point-min))
834         (let ((id (mail-fetch-field "message-id")))
835           (when id
836             (set-buffer gnus-summary-buffer)
837             (gnus-summary-score-entry
838              "references" id 's
839              score (current-time-string))))))))
840
841 (defun gnus-score-set (symbol value &optional alist)
842   ;; Set SYMBOL to VALUE in ALIST.
843   (let* ((alist 
844           (or alist 
845               gnus-score-alist
846               (gnus-newsgroup-score-alist)))
847          (entry (assoc symbol alist)))
848     (cond ((gnus-score-get 'read-only alist)
849            ;; This is a read-only score file, so we do nothing.
850            )
851           (entry
852            (setcdr entry value))
853           ((null alist)
854            (error "Empty alist"))
855           (t
856            (setcdr alist
857                    (cons (cons symbol value) (cdr alist)))))))
858
859 (defun gnus-summary-raise-score (n)
860   "Raise the score of the current article by N."
861   (interactive "p")
862   (gnus-set-global-variables)
863   (gnus-summary-set-score (+ (gnus-summary-article-score) 
864                              (or n gnus-score-interactive-default-score ))))
865
866 (defun gnus-summary-set-score (n)
867   "Set the score of the current article to N."
868   (interactive "p")
869   (gnus-set-global-variables)
870   (save-excursion
871     (gnus-summary-show-thread)
872     (let ((buffer-read-only nil))
873       ;; Set score.
874       (gnus-summary-update-mark
875        (if (= n (or gnus-summary-default-score 0)) ? 
876          (if (< n (or gnus-summary-default-score 0))
877              gnus-score-below-mark gnus-score-over-mark)) 'score))
878     (let* ((article (gnus-summary-article-number))
879            (score (assq article gnus-newsgroup-scored)))
880       (if score (setcdr score n)
881         (setq gnus-newsgroup-scored
882               (cons (cons article n) gnus-newsgroup-scored))))
883     (gnus-summary-update-line)))
884
885 (defun gnus-summary-current-score ()
886   "Return the score of the current article."
887   (interactive)
888   (gnus-set-global-variables)
889   (gnus-message 1 "%s" (gnus-summary-article-score)))
890
891 (defun gnus-score-change-score-file (file)
892   "Change current score alist."
893   (interactive 
894    (list (read-file-name "Change to score file: " gnus-kill-files-directory)))
895   (gnus-score-load-file file)
896   (gnus-set-mode-line 'summary))
897
898 (defvar gnus-score-edit-exit-function)
899 (defun gnus-score-edit-current-scores (file)
900   "Edit the current score alist."
901   (interactive (list gnus-current-score-file))
902   (let ((winconf (current-window-configuration)))
903     (and (buffer-name gnus-summary-buffer) (gnus-score-save))
904     (gnus-make-directory (file-name-directory file))
905     (setq gnus-score-edit-buffer (find-file-noselect file))
906     (gnus-configure-windows 'edit-score)
907     (gnus-score-mode)
908     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
909     (make-local-variable 'gnus-prev-winconf)
910     (setq gnus-prev-winconf winconf))
911   (gnus-message 
912    4 (substitute-command-keys 
913       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
914   
915 (defun gnus-score-edit-file (file)
916   "Edit a score file."
917   (interactive 
918    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
919   (gnus-make-directory (file-name-directory file))
920   (and (buffer-name gnus-summary-buffer) (gnus-score-save))
921   (let ((winconf (current-window-configuration)))
922     (setq gnus-score-edit-buffer (find-file-noselect file))
923     (gnus-configure-windows 'edit-score)
924     (gnus-score-mode)
925     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
926     (make-local-variable 'gnus-prev-winconf)
927     (setq gnus-prev-winconf winconf))
928   (gnus-message 
929    4 (substitute-command-keys 
930       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
931   
932 (defun gnus-score-load-file (file)
933   ;; Load score file FILE.  Returns a list a retrieved score-alists.
934   (let* ((file (expand-file-name 
935                 (or (and (string-match
936                           (concat "^" (expand-file-name
937                                        gnus-kill-files-directory)) 
938                           (expand-file-name file))
939                          file)
940                     (concat (file-name-as-directory gnus-kill-files-directory)
941                             file))))
942          (cached (assoc file gnus-score-cache))
943          (global (member file gnus-internal-global-score-files))
944          lists alist)
945     (if cached
946         ;; The score file was already loaded.
947         (setq alist (cdr cached))
948       ;; We load the score file.
949       (setq gnus-score-alist nil)
950       (setq alist (gnus-score-load-score-alist file))
951       ;; We add '(touched) to the alist to signify that it hasn't been
952       ;; touched (yet). 
953       (or (assq 'touched alist) (setq alist (cons (list 'touched nil) alist)))
954       ;; If it is a global score file, we make it read-only.
955       (and global
956            (not (assq 'read-only alist))
957            (setq alist (cons (list 'read-only t) alist)))
958       (setq gnus-score-cache
959             (cons (cons file alist) gnus-score-cache)))
960     (let ((a alist)
961           found)
962       (while a
963         ;; Downcase all header names.
964         (when (stringp (caar a))
965           (setcar (car a) (downcase (caar a)))
966           (setq found t))
967         (pop a))
968       ;; If there are actual scores in the alist, we add it to the
969       ;; return value of this function.
970       (when found
971         (setq lists (list alist))))
972     ;; Treat the other possible atoms in the score alist.
973     (let ((mark (car (gnus-score-get 'mark alist)))
974           (expunge (car (gnus-score-get 'expunge alist)))
975           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
976           (files (gnus-score-get 'files alist))
977           (exclude-files (gnus-score-get 'exclude-files alist))
978           (orphan (car (gnus-score-get 'orphan alist)))
979           (adapt (gnus-score-get 'adapt alist))
980           (thread-mark-and-expunge
981            (car (gnus-score-get 'thread-mark-and-expunge alist)))
982           (adapt-file (car (gnus-score-get 'adapt-file alist)))
983           (local (gnus-score-get 'local alist))
984           (decay (car (gnus-score-get 'decay alist)))
985           (eval (car (gnus-score-get 'eval alist))))
986       ;; Perform possible decays.
987       (when (and gnus-decay-scores
988                  (gnus-decay-scores 
989                   alist (or decay (gnus-time-to-day (current-time)))))
990         (gnus-score-set 'touched '(t) alist)
991         (gnus-score-set 'decay (list (gnus-time-to-day (current-time)))))
992       ;; We do not respect eval and files atoms from global score
993       ;; files. 
994       (and files (not global)
995            (setq lists (apply 'append lists
996                               (mapcar (lambda (file)
997                                         (gnus-score-load-file file)) 
998                                       (if adapt-file (cons adapt-file files)
999                                         files)))))
1000       (and eval (not global) (eval eval))
1001       ;; We then expand any exclude-file directives.
1002       (setq gnus-scores-exclude-files 
1003             (nconc 
1004              (mapcar 
1005               (lambda (sfile) 
1006                 (expand-file-name sfile (file-name-directory file)))
1007               exclude-files) gnus-scores-exclude-files))
1008       (if (not local)
1009           ()
1010         (save-excursion
1011           (set-buffer gnus-summary-buffer)
1012           (while local
1013             (and (consp (car local))
1014                  (symbolp (caar local))
1015                  (progn
1016                    (make-local-variable (caar local))
1017                    (set (caar local) (nth 1 (car local)))))
1018             (setq local (cdr local)))))
1019       (if orphan (setq gnus-orphan-score orphan))
1020       (setq gnus-adaptive-score-alist
1021             (cond ((equal adapt '(t))
1022                    (setq gnus-newsgroup-adaptive t)
1023                    gnus-default-adaptive-score-alist)
1024                   ((equal adapt '(ignore))
1025                    (setq gnus-newsgroup-adaptive nil))
1026                   ((consp adapt)
1027                    (setq gnus-newsgroup-adaptive t)
1028                    adapt)
1029                   (t
1030                    ;;(setq gnus-newsgroup-adaptive gnus-use-adaptive-scoring)
1031                    gnus-default-adaptive-score-alist)))
1032       (setq gnus-thread-expunge-below 
1033             (or thread-mark-and-expunge gnus-thread-expunge-below))
1034       (setq gnus-summary-mark-below 
1035             (or mark mark-and-expunge gnus-summary-mark-below))
1036       (setq gnus-summary-expunge-below 
1037             (or expunge mark-and-expunge gnus-summary-expunge-below))
1038       (setq gnus-newsgroup-adaptive-score-file 
1039             (or adapt-file gnus-newsgroup-adaptive-score-file)))
1040     (setq gnus-current-score-file file)
1041     (setq gnus-score-alist alist)
1042     lists))
1043
1044 (defun gnus-score-load (file)
1045   ;; Load score FILE.
1046   (let ((cache (assoc file gnus-score-cache)))
1047     (if cache
1048         (setq gnus-score-alist (cdr cache))
1049       (setq gnus-score-alist nil)
1050       (gnus-score-load-score-alist file)
1051       (or gnus-score-alist
1052           (setq gnus-score-alist (copy-alist '((touched nil)))))
1053       (setq gnus-score-cache
1054             (cons (cons file gnus-score-alist) gnus-score-cache)))))
1055
1056 (defun gnus-score-remove-from-cache (file)
1057   (setq gnus-score-cache 
1058         (delq (assoc file gnus-score-cache) gnus-score-cache)))
1059
1060 (defun gnus-score-load-score-alist (file)
1061   "Read score FILE."
1062   (let (alist)
1063     (if (not (file-readable-p file))
1064         ;; Couldn't read file.
1065         (setq gnus-score-alist nil)
1066       ;; Read file.
1067       (save-excursion
1068         (gnus-set-work-buffer)
1069         (insert-file-contents file)
1070         (goto-char (point-min))
1071         ;; Only do the loading if the score file isn't empty.
1072         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
1073           (setq alist
1074                 (condition-case ()
1075                     (read (current-buffer))
1076                   (error 
1077                    (gnus-error 3.2 "Problem with score file %s" file))))))
1078       (if (eq (car alist) 'setq)
1079           ;; This is an old-style score file.
1080           (setq gnus-score-alist (gnus-score-transform-old-to-new alist))
1081         (setq gnus-score-alist alist))
1082       ;; Check the syntax of the score file.
1083       (setq gnus-score-alist
1084             (gnus-score-check-syntax gnus-score-alist file)))))
1085
1086 (defun gnus-score-check-syntax (alist file)
1087   "Check the syntax of the score ALIST."
1088   (cond 
1089    ((null alist)
1090     nil)
1091    ((not (consp alist))
1092     (gnus-message 1 "Score file is not a list: %s" file)
1093     (ding)
1094     nil)
1095    (t
1096     (let ((a alist)
1097           sr err s type)
1098       (while (and a (not err))
1099         (setq
1100          err
1101          (cond
1102           ((not (listp (car a)))
1103            (format "Illegal score element %s in %s" (car a) file))
1104           ((stringp (caar a))
1105            (cond 
1106             ((not (listp (setq sr (cdar a))))
1107              (format "Illegal header match %s in %s" (nth 1 (car a)) file))
1108             (t
1109              (setq type (caar a))
1110              (while (and sr (not err))
1111                (setq s (pop sr))
1112                (setq 
1113                 err
1114                 (cond
1115                  ((if (member (downcase type) '("lines" "chars"))
1116                       (not (numberp (car s)))
1117                     (not (stringp (car s))))
1118                   (format "Illegal match %s in %s" (car s) file))
1119                  ((and (cadr s) (not (integerp (cadr s))))
1120                   (format "Non-integer score %s in %s" (cadr s) file))
1121                  ((and (caddr s) (not (integerp (caddr s))))
1122                   (format "Non-integer date %s in %s" (caddr s) file))
1123                  ((and (cadddr s) (not (symbolp (cadddr s))))
1124                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1125              err)))))
1126         (setq a (cdr a)))
1127       (if err
1128           (progn
1129             (ding)
1130             (gnus-message 3 err)
1131             (sit-for 2)
1132             nil)
1133         alist)))))    
1134
1135 (defun gnus-score-transform-old-to-new (alist)
1136   (let* ((alist (nth 2 alist))
1137          out entry)
1138     (if (eq (car alist) 'quote)
1139         (setq alist (nth 1 alist)))
1140     (while alist
1141       (setq entry (car alist))
1142       (if (stringp (car entry))
1143           (let ((scor (cdr entry)))
1144             (setq out (cons entry out))
1145             (while scor
1146               (setcar scor
1147                       (list (caar scor) (nth 2 (car scor))
1148                             (and (nth 3 (car scor))
1149                                  (gnus-day-number (nth 3 (car scor))))
1150                             (if (nth 1 (car scor)) 'r 's)))
1151               (setq scor (cdr scor))))
1152         (setq out (cons (if (not (listp (cdr entry))) 
1153                             (list (car entry) (cdr entry))
1154                           entry)
1155                         out)))
1156       (setq alist (cdr alist)))
1157     (cons (list 'touched t) (nreverse out))))
1158   
1159 (defun gnus-score-save ()
1160   ;; Save all score information.
1161   (let ((cache gnus-score-cache)
1162         entry score file)
1163     (save-excursion
1164       (setq gnus-score-alist nil)
1165       (nnheader-set-temp-buffer "*Score*")
1166       (while cache
1167         (current-buffer)
1168         (setq entry (pop cache)
1169               file (car entry)
1170               score (cdr entry))
1171         (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1172                 (gnus-score-get 'read-only score)
1173                 (and (file-exists-p file)
1174                      (not (file-writable-p file))))
1175             ()
1176           (setq score (setcdr entry (delq (assq 'touched score) score)))
1177           (erase-buffer)
1178           (let (emacs-lisp-mode-hook)
1179             (if (string-match 
1180                  (concat (regexp-quote gnus-adaptive-file-suffix)
1181                          "$") file)
1182                 ;; This is an adaptive score file, so we do not run
1183                 ;; it through `pp'.  These files can get huge, and
1184                 ;; are not meant to be edited by human hands.
1185                 (gnus-prin1 score)
1186               ;; This is a normal score file, so we print it very
1187               ;; prettily. 
1188               (pp score (current-buffer))))
1189           (if (not (gnus-make-directory (file-name-directory file)))
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 
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 kill)
2110     ;; Go through all the score alists for this group
2111     ;; and find all `w' rules.
2112     (while (setq alist (pop alists))
2113       (while (setq rule (pop alist))
2114         (when (and (stringp (car rule))
2115                    (equal "subject" (downcase (pop rule))))
2116           (while (setq kill (pop rule))
2117             (when (memq (nth 3 kill) '(w W word Word))
2118               (push (cons (or (nth 1 kill)
2119                               gnus-score-interactive-default-score)
2120                           (car kill))
2121                     rules))))))
2122     (setq rules (sort rules (lambda (r1 r2)
2123                               (string-lessp (cdr r1) (cdr r2)))))
2124     ;; Add up words that have appeared several times.
2125     (let ((r rules))
2126       (while (cdr r)
2127         (if (equal (cdar r) (cdadr r))
2128             (progn
2129               (setcar (car r) (+ (caar r) (caadr r)))
2130               (setcdr r (cddr r)))
2131           (pop r))))
2132     ;; Insert the words.
2133     (nnheader-set-temp-buffer "*Score Words*")
2134     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2135         (gnus-error 3 "No word score rules")
2136       (while rules
2137         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2138         (pop rules))
2139       (gnus-add-current-to-buffer-list)
2140       (gnus-configure-windows 'score-words))))
2141
2142 (defun gnus-summary-rescore ()
2143   "Redo the entire scoring process in the current summary."
2144   (interactive)
2145   (gnus-score-save)
2146   (setq gnus-score-cache nil)
2147   (setq gnus-newsgroup-scored nil)
2148   (gnus-possibly-score-headers)
2149   (gnus-score-update-all-lines))
2150   
2151 (defun gnus-score-flush-cache ()
2152   "Flush the cache of score files."
2153   (interactive)
2154   (gnus-score-save)
2155   (setq gnus-score-cache nil
2156         gnus-score-alist nil
2157         gnus-short-name-score-file-cache nil)
2158   (gnus-message 6 "The score cache is now flushed"))
2159
2160 (gnus-add-shutdown 'gnus-score-close 'gnus)
2161
2162 (defvar gnus-score-file-alist-cache nil)
2163
2164 (defun gnus-score-close ()
2165   "Clear all internal score variables."
2166   (setq gnus-score-cache nil
2167         gnus-internal-global-score-files nil
2168         gnus-score-file-list nil
2169         gnus-score-file-alist-cache nil))
2170
2171 ;; Summary score marking commands.
2172
2173 (defun gnus-summary-raise-same-subject-and-select (score)
2174   "Raise articles which has the same subject with SCORE and select the next."
2175   (interactive "p")
2176   (let ((subject (gnus-summary-article-subject)))
2177     (gnus-summary-raise-score score)
2178     (while (gnus-summary-find-subject subject)
2179       (gnus-summary-raise-score score))
2180     (gnus-summary-next-article t)))
2181
2182 (defun gnus-summary-raise-same-subject (score)
2183   "Raise articles which has the same subject with SCORE."
2184   (interactive "p")
2185   (let ((subject (gnus-summary-article-subject)))
2186     (gnus-summary-raise-score score)
2187     (while (gnus-summary-find-subject subject)
2188       (gnus-summary-raise-score score))
2189     (gnus-summary-next-subject 1 t)))
2190
2191 (defun gnus-score-default (level)
2192   (if level (prefix-numeric-value level) 
2193     gnus-score-interactive-default-score))
2194
2195 (defun gnus-summary-raise-thread (&optional score)
2196   "Raise the score of the articles in the current thread with SCORE."
2197   (interactive "P")
2198   (setq score (gnus-score-default score))
2199   (let (e)
2200     (save-excursion
2201       (let ((articles (gnus-summary-articles-in-thread)))
2202         (while articles
2203           (gnus-summary-goto-subject (car articles))
2204           (gnus-summary-raise-score score)
2205           (setq articles (cdr articles))))
2206       (setq e (point)))
2207     (let ((gnus-summary-check-current t))
2208       (or (zerop (gnus-summary-next-subject 1 t))
2209           (goto-char e))))
2210   (gnus-summary-recenter)
2211   (gnus-summary-position-point)
2212   (gnus-set-mode-line 'summary))
2213
2214 (defun gnus-summary-lower-same-subject-and-select (score)
2215   "Raise articles which has the same subject with SCORE and select the next."
2216   (interactive "p")
2217   (gnus-summary-raise-same-subject-and-select (- score)))
2218
2219 (defun gnus-summary-lower-same-subject (score)
2220   "Raise articles which has the same subject with SCORE."
2221   (interactive "p")
2222   (gnus-summary-raise-same-subject (- score)))
2223
2224 (defun gnus-summary-lower-thread (&optional score)
2225   "Lower score of articles in the current thread with SCORE."
2226   (interactive "P")
2227   (gnus-summary-raise-thread (- (1- (gnus-score-default score)))))
2228
2229 ;;; Finding score files. 
2230
2231 (defun gnus-score-score-files (group)
2232   "Return a list of all possible score files."
2233   ;; Search and set any global score files.
2234   (and gnus-global-score-files 
2235        (or gnus-internal-global-score-files
2236            (gnus-score-search-global-directories gnus-global-score-files)))
2237   ;; Fix the kill-file dir variable.
2238   (setq gnus-kill-files-directory 
2239         (file-name-as-directory gnus-kill-files-directory))
2240   ;; If we can't read it, there are no score files.
2241   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2242       (setq gnus-score-file-list nil)
2243     (if (not (gnus-use-long-file-name 'not-score))
2244         ;; We do not use long file names, so we have to do some
2245         ;; directory traversing.  
2246         (setq gnus-score-file-list 
2247               (cons nil 
2248                     (or gnus-short-name-score-file-cache
2249                         (prog2
2250                             (gnus-message 6 "Finding all score files...")
2251                             (setq gnus-short-name-score-file-cache
2252                                   (gnus-score-score-files-1
2253                                    gnus-kill-files-directory))
2254                           (gnus-message 6 "Finding all score files...done")))))
2255       ;; We want long file names.
2256       (when (or (not gnus-score-file-list)
2257                 (not (car gnus-score-file-list))
2258                 (gnus-file-newer-than gnus-kill-files-directory
2259                                       (car gnus-score-file-list)))
2260         (setq gnus-score-file-list 
2261               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2262                     (nreverse 
2263                      (directory-files 
2264                       gnus-kill-files-directory t 
2265                       (gnus-score-file-regexp)))))))
2266     (cdr gnus-score-file-list)))
2267
2268 (defun gnus-score-score-files-1 (dir)
2269   "Return all possible score files under DIR."
2270   (let ((files (directory-files (expand-file-name dir) t nil t))
2271         (regexp (gnus-score-file-regexp))
2272         (case-fold-search nil)
2273         out file)
2274     (while (setq file (pop files))
2275       (cond 
2276        ;; Ignore "." and "..".
2277        ((member (file-name-nondirectory file) '("." ".."))
2278         nil)
2279        ;; Recurse down directories.
2280        ((file-directory-p file)
2281         (setq out (nconc (gnus-score-score-files-1 file) out)))
2282        ;; Add files to the list of score files.
2283        ((string-match regexp file)
2284         (push file out))))
2285     (or out
2286         ;; Return a dummy value.
2287         (list "~/News/this.file.does.not.exist.SCORE"))))
2288        
2289 (defun gnus-score-file-regexp ()
2290   "Return a regexp that match all score files."
2291   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2292           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2293         
2294 (defun gnus-score-find-bnews (group)
2295   "Return a list of score files for GROUP.
2296 The score files are those files in the ~/News/ directory which matches
2297 GROUP using BNews sys file syntax."
2298   (let* ((sfiles (append (gnus-score-score-files group)
2299                          gnus-internal-global-score-files))
2300          (kill-dir (file-name-as-directory 
2301                     (expand-file-name gnus-kill-files-directory)))
2302          (klen (length kill-dir))
2303          (score-regexp (gnus-score-file-regexp))
2304          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2305          ofiles not-match regexp)
2306     (save-excursion
2307       (set-buffer (get-buffer-create "*gnus score files*"))
2308       (buffer-disable-undo (current-buffer))
2309       ;; Go through all score file names and create regexp with them
2310       ;; as the source.  
2311       (while sfiles
2312         (erase-buffer)
2313         (insert (car sfiles))
2314         (goto-char (point-min))
2315         ;; First remove the suffix itself.
2316         (when (re-search-forward (concat "." score-regexp) nil t)
2317           (replace-match "" t t) 
2318           (goto-char (point-min))
2319           (if (looking-at (regexp-quote kill-dir))
2320               ;; If the file name was just "SCORE", `klen' is one character
2321               ;; too much.
2322               (delete-char (min (1- (point-max)) klen))
2323             (goto-char (point-max))
2324             (search-backward "/")
2325             (delete-region (1+ (point)) (point-min)))
2326           ;; If short file names were used, we have to translate slashes.
2327           (goto-char (point-min))
2328           (let ((regexp (concat
2329                          "[/:" (if trans (char-to-string trans) "") "]")))
2330             (while (re-search-forward regexp nil t)
2331               (replace-match "." t t)))
2332           ;; Cludge to get rid of "nntp+" problems.
2333           (goto-char (point-min))
2334           (and (looking-at "nn[a-z]+\\+")
2335                (progn
2336                  (search-forward "+")
2337                  (forward-char -1)
2338                  (insert "\\")))
2339           ;; Kludge to deal with "++".
2340           (goto-char (point-min))
2341           (while (search-forward "++" nil t)
2342             (replace-match "\\+\\+" t t))
2343           ;; Translate "all" to ".*".
2344           (goto-char (point-min))
2345           (while (search-forward "all" nil t)
2346             (replace-match ".*" t t))
2347           (goto-char (point-min))
2348           ;; Deal with "not."s.
2349           (if (looking-at "not.")
2350               (progn
2351                 (setq not-match t)
2352                 (setq regexp (buffer-substring 5 (point-max))))
2353             (setq regexp (buffer-substring 1 (point-max)))
2354             (setq not-match nil))
2355           ;; Finally - if this resulting regexp matches the group name,
2356           ;; we add this score file to the list of score files
2357           ;; applicable to this group.
2358           (if (or (and not-match
2359                        (not (string-match regexp group)))
2360                   (and (not not-match)
2361                        (string-match regexp group)))
2362               (setq ofiles (cons (car sfiles) ofiles))))
2363         (setq sfiles (cdr sfiles)))
2364       (kill-buffer (current-buffer))
2365       ;; Slight kludge here - the last score file returned should be
2366       ;; the local score file, whether it exists or not. This is so
2367       ;; that any score commands the user enters will go to the right
2368       ;; file, and not end up in some global score file.
2369       (let ((localscore (gnus-score-file-name group)))
2370         (setq ofiles (cons localscore (delete localscore ofiles))))
2371       (nreverse ofiles))))
2372
2373 (defun gnus-score-find-single (group)
2374   "Return list containing the score file for GROUP."
2375   (list (or gnus-newsgroup-adaptive-score-file
2376             (gnus-score-file-name group gnus-adaptive-file-suffix))
2377         (gnus-score-file-name group)))
2378
2379 (defun gnus-score-find-hierarchical (group)
2380   "Return list of score files for GROUP.
2381 This includes the score file for the group and all its parents."
2382   (let ((all (copy-sequence '(nil)))
2383         (start 0))
2384     (while (string-match "\\." group (1+ start))
2385       (setq start (match-beginning 0))
2386       (setq all (cons (substring group 0 start) all)))
2387     (setq all (cons group all))
2388     (nconc
2389      (mapcar (lambda (newsgroup)
2390                (gnus-score-file-name newsgroup gnus-adaptive-file-suffix))
2391              (setq all (nreverse all)))
2392      (mapcar 'gnus-score-file-name all))))
2393
2394 (defun gnus-score-find-alist (group)
2395   "Return list of score files for GROUP.
2396 The list is determined from the variable gnus-score-file-alist."
2397   (let ((alist gnus-score-file-multiple-match-alist)
2398         score-files)
2399     ;; if this group has been seen before, return the cached entry
2400     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2401         (cdr score-files)               ;ensures caching groups with no matches
2402       ;; handle the multiple match alist
2403       (while alist
2404         (and (string-match (caar alist) group)
2405              (setq score-files
2406                    (nconc score-files (copy-sequence (cdar alist)))))
2407         (setq alist (cdr alist)))
2408       (setq alist gnus-score-file-single-match-alist)
2409       ;; handle the single match alist
2410       (while alist
2411         (and (string-match (caar alist) group)
2412              ;; progn used just in case ("regexp") has no files
2413              ;; and score-files is still nil. -sj
2414              ;; this can be construed as a "stop searching here" feature :>
2415              ;; and used to simplify regexps in the single-alist 
2416              (progn
2417                (setq score-files
2418                      (nconc score-files (copy-sequence (cdar alist))))
2419                (setq alist nil)))
2420         (setq alist (cdr alist)))
2421       ;; cache the score files
2422       (setq gnus-score-file-alist-cache
2423             (cons (cons group score-files) gnus-score-file-alist-cache))
2424       score-files)))
2425
2426 (defun gnus-all-score-files ()
2427   "Return a list of all score files for the current group."
2428   (let ((funcs gnus-score-find-score-files-function)
2429         (group gnus-newsgroup-name)
2430         score-files)
2431     ;; Make sure funcs is a list.
2432     (and funcs
2433          (not (listp funcs))
2434          (setq funcs (list funcs)))
2435     ;; Get the initial score files for this group.
2436     (when funcs 
2437       (setq score-files (gnus-score-find-alist group)))
2438     ;; Add any home adapt files.
2439     (let ((home (gnus-home-score-file group t)))
2440       (when home
2441         (push home score-files)
2442         (setq gnus-newsgroup-adaptive-score-file home)))
2443     ;; Check whether there is a `adapt-file' group parameter.
2444     (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2445       (when param-file
2446         (push param-file score-files)
2447         (setq gnus-newsgroup-adaptive-score-file param-file)))
2448     ;; Go through all the functions for finding score files (or actual
2449     ;; scores) and add them to a list.
2450     (while funcs
2451       (when (gnus-functionp (car funcs))
2452         (setq score-files 
2453               (nconc score-files (funcall (car funcs) group))))
2454       (setq funcs (cdr funcs)))
2455     ;; Add any home score files.
2456     (let ((home (gnus-home-score-file group)))
2457       (when home
2458         (push home score-files)))
2459     ;; Check whether there is a `score-file' group parameter.
2460     (let ((param-file (gnus-group-find-parameter group 'score-file)))
2461       (when param-file
2462         (push param-file score-files)))
2463     ;; Do the scoring if there are any score files for this group.
2464     score-files))
2465     
2466 (defun gnus-possibly-score-headers (&optional trace)
2467   "Do scoring if scoring is required."
2468   (let ((score-files (gnus-all-score-files)))
2469     (when score-files
2470       (gnus-score-headers score-files trace))))
2471
2472 (defun gnus-score-file-name (newsgroup &optional suffix)
2473   "Return the name of a score file for NEWSGROUP."
2474   (let ((suffix (or suffix gnus-score-file-suffix)))
2475     (nnheader-translate-file-chars
2476      (cond
2477       ((or (null newsgroup)
2478            (string-equal newsgroup ""))
2479        ;; The global score file is placed at top of the directory.
2480        (expand-file-name 
2481         suffix gnus-kill-files-directory))
2482       ((gnus-use-long-file-name 'not-score)
2483        ;; Append ".SCORE" to newsgroup name.
2484        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2485                                  "." suffix)
2486                          gnus-kill-files-directory))
2487       (t
2488        ;; Place "SCORE" under the hierarchical directory.
2489        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2490                                  "/" suffix)
2491                          gnus-kill-files-directory))))))
2492
2493 (defun gnus-score-search-global-directories (files)
2494   "Scan all global score directories for score files."
2495   ;; Set the variable `gnus-internal-global-score-files' to all
2496   ;; available global score files.
2497   (interactive (list gnus-global-score-files))
2498   (let (out)
2499     (while files
2500       (if (string-match "/$" (car files))
2501           (setq out (nconc (directory-files 
2502                             (car files) t
2503                             (concat (gnus-score-file-regexp) "$"))))
2504         (setq out (cons (car files) out)))
2505       (setq files (cdr files)))
2506     (setq gnus-internal-global-score-files out)))
2507
2508 (defun gnus-score-default-fold-toggle ()
2509   "Toggle folding for new score file entries."
2510   (interactive)
2511   (setq gnus-score-default-fold (not gnus-score-default-fold))
2512   (if gnus-score-default-fold
2513       (gnus-message 1 "New score file entries will be case insensitive.")
2514     (gnus-message 1 "New score file entries will be case sensitive.")))
2515
2516 ;;; Home score file.
2517
2518 (defun gnus-home-score-file (group &optional adapt)
2519   "Return the home score file for GROUP.
2520 If ADAPT, return the home adaptive file instead."
2521   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2522         elem found)
2523     ;; Make sure we have a list.
2524     (unless (listp list)
2525       (setq list (list list)))
2526     ;; Go through the list and look for matches.
2527     (while (and (not found)
2528                 (setq elem (pop list)))
2529       (setq found
2530             (cond
2531              ;; Simple string.
2532              ((stringp elem)
2533               elem)
2534              ;; Function.
2535              ((gnus-functionp elem)
2536               (funcall elem group))
2537              ;; Regexp-file cons
2538              ((consp elem)
2539               (when (string-match (car elem) group)
2540                 (cadr elem))))))
2541     (when found
2542       (nnheader-concat gnus-kill-files-directory found))))
2543
2544 (defun gnus-hierarchial-home-score-file (group)
2545   "Return the score file of the top-level hierarchy of GROUP."
2546   (if (string-match "^[^.]+\\." group)
2547       (concat (match-string 0 group) gnus-score-file-suffix)
2548     ;; Group name without any dots.
2549     (concat group "." gnus-score-file-suffix)))
2550       
2551 (defun gnus-hierarchial-home-adapt-file (group)
2552   "Return the adapt file of the top-level hierarchy of GROUP."
2553   (if (string-match "^[^.]+\\." group)
2554       (concat (match-string 0 group) gnus-adaptive-file-suffix)
2555     ;; Group name without any dots.
2556     (concat group "." gnus-adaptive-file-suffix)))
2557
2558 ;;;
2559 ;;; Score decays
2560 ;;;
2561
2562 (defun gnus-decay-score (score)
2563   "Decay SCORE."
2564   (floor
2565    (- score
2566       (* (if (< score 0) 1 -1)
2567          (min score
2568               (max gnus-score-decay-constant
2569                    (* (abs score)
2570                       gnus-score-decay-scale)))))))
2571
2572 (defun gnus-decay-scores (alist day)
2573   "Decay non-permanent scores in ALIST."
2574   (let ((times (- (gnus-time-to-day (current-time)) day))
2575         kill entry updated score n)
2576     (unless (zerop times) ;Done decays today already?
2577       (while (setq entry (pop alist))
2578         (when (stringp (car entry))
2579           (setq entry (cdr entry))
2580           (while (setq kill (pop entry))
2581             (when (nth 2 kill)
2582               (setq updated t)
2583               (setq score (or (car kill) gnus-score-interactive-default-score)
2584                     n times)
2585               (while (natnump (decf n))
2586                 (setq score (funcall gnus-decay-score-function score)))
2587               (setcar kill score))))))
2588     ;; Return whether this score file needs to be saved.  By Je-haysuss!
2589     updated))
2590
2591 (provide 'gnus-score)
2592
2593 ;;; gnus-score.el ends here