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