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