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