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