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