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