3a2bbf2dfd35f0ead0ee4afa9e1f1bb9039cb8ed
[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 ;; 2005 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., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, 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 "22.1"
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 "23.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-number 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-number (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-number (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-number (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   (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1143   (gnus-message
1144    4 (substitute-command-keys
1145       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
1146
1147 (defun gnus-score-edit-file (file)
1148   "Edit a score file."
1149   (interactive
1150    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
1151   (gnus-make-directory (file-name-directory file))
1152   (when (buffer-name gnus-summary-buffer)
1153     (gnus-score-save))
1154   (let ((winconf (current-window-configuration)))
1155     (setq gnus-score-edit-buffer (find-file-noselect file))
1156     (gnus-configure-windows 'edit-score)
1157     (gnus-score-mode)
1158     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1159     (make-local-variable 'gnus-prev-winconf)
1160     (setq gnus-prev-winconf winconf))
1161   (gnus-message
1162    4 (substitute-command-keys
1163       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
1164
1165 (defun gnus-score-edit-file-at-point (&optional format)
1166   "Edit score file at point in Score Trace buffers.
1167 If FORMAT, also format the current score file."
1168   (let* ((rule (save-excursion
1169                  (beginning-of-line)
1170                  (read (current-buffer))))
1171          (sep "[ \n\r\t]*")
1172          ;; Must be synced with `gnus-score-find-trace':
1173          (reg " -> +")
1174          (file (save-excursion
1175                  (end-of-line)
1176                  (if (and (re-search-backward reg (point-at-bol) t)
1177                           (re-search-forward  reg (point-at-eol) t))
1178                      (buffer-substring (point) (point-at-eol))
1179                    nil))))
1180     (if (or (not file)
1181             (string-match "\\<\\(non-file rule\\|A file\\)\\>" file)
1182             ;; (see `gnus-score-find-trace' and `gnus-score-advanced')
1183             (string= "" file))
1184         (gnus-error 3 "Can't find a score file in current line.")
1185       (gnus-score-edit-file file)
1186       (when format
1187         (gnus-score-pretty-print))
1188       (when (consp rule) ;; the rule exists
1189         (setq rule (mapconcat #'(lambda (obj)
1190                                   (regexp-quote (format "%S" obj)))
1191                               rule
1192                               sep))
1193         (goto-char (point-min))
1194         (re-search-forward rule nil t)
1195         ;; make it easy to use `kill-sexp':
1196         (goto-char (1- (match-beginning 0)))))))
1197
1198 (defun gnus-score-load-file (file)
1199   ;; Load score file FILE.  Returns a list a retrieved score-alists.
1200   (let* ((file (expand-file-name
1201                 (or (and (string-match
1202                           (concat "^" (regexp-quote
1203                                        (expand-file-name
1204                                         gnus-kill-files-directory)))
1205                           (expand-file-name file))
1206                          file)
1207                     (expand-file-name file gnus-kill-files-directory))))
1208          (cached (assoc file gnus-score-cache))
1209          (global (member file gnus-internal-global-score-files))
1210          lists alist)
1211     (if cached
1212         ;; The score file was already loaded.
1213         (setq alist (cdr cached))
1214       ;; We load the score file.
1215       (setq gnus-score-alist nil)
1216       (setq alist (gnus-score-load-score-alist file))
1217       ;; We add '(touched) to the alist to signify that it hasn't been
1218       ;; touched (yet).
1219       (unless (assq 'touched alist)
1220         (push (list 'touched nil) alist))
1221       ;; If it is a global score file, we make it read-only.
1222       (and global
1223            (not (assq 'read-only alist))
1224            (push (list 'read-only t) alist))
1225       (push (cons file alist) gnus-score-cache))
1226     (let ((a alist)
1227           found)
1228       (while a
1229         ;; Downcase all header names.
1230         (cond
1231          ((stringp (caar a))
1232           (setcar (car a) (downcase (caar a)))
1233           (setq found t))
1234          ;; Advanced scoring.
1235          ((consp (caar a))
1236           (setq found t)))
1237         (pop a))
1238       ;; If there are actual scores in the alist, we add it to the
1239       ;; return value of this function.
1240       (when found
1241         (setq lists (list alist))))
1242     ;; Treat the other possible atoms in the score alist.
1243     (let ((mark (car (gnus-score-get 'mark alist)))
1244           (expunge (car (gnus-score-get 'expunge alist)))
1245           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
1246           (files (gnus-score-get 'files alist))
1247           (exclude-files (gnus-score-get 'exclude-files alist))
1248           (orphan (car (gnus-score-get 'orphan alist)))
1249           (adapt (gnus-score-get 'adapt alist))
1250           (thread-mark-and-expunge
1251            (car (gnus-score-get 'thread-mark-and-expunge alist)))
1252           (adapt-file (car (gnus-score-get 'adapt-file alist)))
1253           (local (gnus-score-get 'local alist))
1254           (decay (car (gnus-score-get 'decay alist)))
1255           (eval (car (gnus-score-get 'eval alist))))
1256       ;; Perform possible decays.
1257       (when (and (if (stringp gnus-decay-scores)
1258                      (string-match gnus-decay-scores file)
1259                    gnus-decay-scores)
1260                  (or cached (file-exists-p file))
1261                  (or (not decay)
1262                      (gnus-decay-scores alist decay)))
1263         (gnus-score-set 'touched '(t) alist)
1264         (gnus-score-set 'decay (list (time-to-days (current-time))) alist))
1265       ;; We do not respect eval and files atoms from global score
1266       ;; files.
1267       (when (and files (not global))
1268         (setq lists (apply 'append lists
1269                            (mapcar 'gnus-score-load-file
1270                                    (if adapt-file (cons adapt-file files)
1271                                      files)))))
1272       (when (and eval (not global))
1273         (eval eval))
1274       ;; We then expand any exclude-file directives.
1275       (setq gnus-scores-exclude-files
1276             (nconc
1277              (apply
1278               'nconc
1279               (mapcar
1280                (lambda (sfile)
1281                  (list
1282                   (expand-file-name sfile (file-name-directory file))
1283                   (expand-file-name sfile gnus-kill-files-directory)))
1284                exclude-files))
1285              gnus-scores-exclude-files))
1286       (when local
1287         (save-excursion
1288           (set-buffer gnus-summary-buffer)
1289           (while local
1290             (and (consp (car local))
1291                  (symbolp (caar local))
1292                  (progn
1293                    (make-local-variable (caar local))
1294                    (set (caar local) (nth 1 (car local)))))
1295             (setq local (cdr local)))))
1296       (when orphan
1297         (setq gnus-orphan-score orphan))
1298       (setq gnus-adaptive-score-alist
1299             (cond ((equal adapt '(t))
1300                    (setq gnus-newsgroup-adaptive t)
1301                    gnus-default-adaptive-score-alist)
1302                   ((equal adapt '(ignore))
1303                    (setq gnus-newsgroup-adaptive nil))
1304                   ((consp adapt)
1305                    (setq gnus-newsgroup-adaptive t)
1306                    adapt)
1307                   (t
1308                    gnus-default-adaptive-score-alist)))
1309       (setq gnus-thread-expunge-below
1310             (or thread-mark-and-expunge gnus-thread-expunge-below))
1311       (setq gnus-summary-mark-below
1312             (or mark mark-and-expunge gnus-summary-mark-below))
1313       (setq gnus-summary-expunge-below
1314             (or expunge mark-and-expunge gnus-summary-expunge-below))
1315       (setq gnus-newsgroup-adaptive-score-file
1316             (or adapt-file gnus-newsgroup-adaptive-score-file)))
1317     (setq gnus-current-score-file file)
1318     (setq gnus-score-alist alist)
1319     lists))
1320
1321 (defun gnus-score-load (file)
1322   ;; Load score FILE.
1323   (let ((cache (assoc file gnus-score-cache)))
1324     (if cache
1325         (setq gnus-score-alist (cdr cache))
1326       (setq gnus-score-alist nil)
1327       (gnus-score-load-score-alist file)
1328       (unless gnus-score-alist
1329         (setq gnus-score-alist (copy-alist '((touched nil)))))
1330       (push (cons file gnus-score-alist) gnus-score-cache))))
1331
1332 (defun gnus-score-remove-from-cache (file)
1333   (setq gnus-score-cache
1334         (delq (assoc file gnus-score-cache) gnus-score-cache)))
1335
1336 (defun gnus-score-load-score-alist (file)
1337   "Read score FILE."
1338   (let (alist)
1339     (if (not (file-readable-p file))
1340         ;; Couldn't read file.
1341         (setq gnus-score-alist nil)
1342       ;; Read file.
1343       (with-temp-buffer
1344         (insert-file-contents-as-coding-system
1345          score-mode-coding-system file)
1346         (goto-char (point-min))
1347         ;; Only do the loading if the score file isn't empty.
1348         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
1349           (setq alist
1350                 (condition-case ()
1351                     (read (current-buffer))
1352                   (error
1353                    (gnus-error 3.2 "Problem with score file %s" file))))))
1354       (cond
1355        ((and alist
1356              (atom alist))
1357         ;; Bogus score file.
1358         (error "Invalid syntax with score file %s" file))
1359        ((eq (car alist) 'setq)
1360         ;; This is an old-style score file.
1361         (setq gnus-score-alist (gnus-score-transform-old-to-new alist)))
1362        (t
1363         (setq gnus-score-alist alist)))
1364       ;; Check the syntax of the score file.
1365       (setq gnus-score-alist
1366             (gnus-score-check-syntax gnus-score-alist file)))))
1367
1368 (defun gnus-score-check-syntax (alist file)
1369   "Check the syntax of the score ALIST."
1370   (cond
1371    ((null alist)
1372     nil)
1373    ((not (consp alist))
1374     (gnus-message 1 "Score file is not a list: %s" file)
1375     (ding)
1376     nil)
1377    (t
1378     (let ((a alist)
1379           sr err s type)
1380       (while (and a (not err))
1381         (setq
1382          err
1383          (cond
1384           ((not (listp (car a)))
1385            (format "Invalid score element %s in %s" (car a) file))
1386           ((stringp (caar a))
1387            (cond
1388             ((not (listp (setq sr (cdar a))))
1389              (format "Invalid header match %s in %s" (nth 1 (car a)) file))
1390             (t
1391              (setq type (caar a))
1392              (while (and sr (not err))
1393                (setq s (pop sr))
1394                (setq
1395                 err
1396                 (cond
1397                  ((if (member (downcase type) '("lines" "chars"))
1398                       (not (numberp (car s)))
1399                     (not (stringp (car s))))
1400                   (format "Invalid match %s in %s" (car s) file))
1401                  ((and (cadr s) (not (integerp (cadr s))))
1402                   (format "Non-integer score %s in %s" (cadr s) file))
1403                  ((and (caddr s) (not (integerp (caddr s))))
1404                   (format "Non-integer date %s in %s" (caddr s) file))
1405                  ((and (cadddr s) (not (symbolp (cadddr s))))
1406                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1407              err)))))
1408         (setq a (cdr a)))
1409       (if err
1410           (progn
1411             (ding)
1412             (gnus-message 3 err)
1413             (sit-for 2)
1414             nil)
1415         alist)))))
1416
1417 (defun gnus-score-transform-old-to-new (alist)
1418   (let* ((alist (nth 2 alist))
1419          out entry)
1420     (when (eq (car alist) 'quote)
1421       (setq alist (nth 1 alist)))
1422     (while alist
1423       (setq entry (car alist))
1424       (if (stringp (car entry))
1425           (let ((scor (cdr entry)))
1426             (push entry out)
1427             (while scor
1428               (setcar scor
1429                       (list (caar scor) (nth 2 (car scor))
1430                             (and (nth 3 (car scor))
1431                                  (date-to-day (nth 3 (car scor))))
1432                             (if (nth 1 (car scor)) 'r 's)))
1433               (setq scor (cdr scor))))
1434         (push (if (not (listp (cdr entry)))
1435                   (list (car entry) (cdr entry))
1436                 entry)
1437               out))
1438       (setq alist (cdr alist)))
1439     (cons (list 'touched t) (nreverse out))))
1440
1441 (defun gnus-score-save ()
1442   ;; Save all score information.
1443   (let ((cache gnus-score-cache)
1444         entry score file)
1445     (save-excursion
1446       (setq gnus-score-alist nil)
1447       (nnheader-set-temp-buffer " *Gnus Scores*")
1448       (while cache
1449         (current-buffer)
1450         (setq entry (pop cache)
1451               file (nnheader-translate-file-chars (car entry) t)
1452               score (cdr entry))
1453         (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1454                 (gnus-score-get 'read-only score)
1455                 (and (file-exists-p file)
1456                      (not (file-writable-p file))))
1457             ()
1458           (setq score (setcdr entry (gnus-delete-alist 'touched score)))
1459           (erase-buffer)
1460           (let (emacs-lisp-mode-hook)
1461             (if (and (not gnus-adaptive-pretty-print)
1462                      (string-match
1463                       (concat (regexp-quote gnus-adaptive-file-suffix) "$")
1464                       file))
1465                 ;; This is an adaptive score file, so we do not run it through
1466                 ;; `pp' unless requested.  These files can get huge, and are
1467                 ;; not meant to be edited by human hands.
1468                 (gnus-prin1 score)
1469               ;; This is a normal score file, so we print it very
1470               ;; prettily.
1471               (let ((lisp-mode-syntax-table score-mode-syntax-table))
1472                 (gnus-pp score))))
1473           (gnus-make-directory (file-name-directory file))
1474           ;; If the score file is empty, we delete it.
1475           (if (zerop (buffer-size))
1476               (delete-file file)
1477             ;; There are scores, so we write the file.
1478             (when (file-writable-p file)
1479               (gnus-write-buffer-as-coding-system
1480                score-mode-coding-system file)
1481               (when gnus-score-after-write-file-function
1482                 (funcall gnus-score-after-write-file-function file)))))
1483         (and gnus-score-uncacheable-files
1484              (string-match gnus-score-uncacheable-files file)
1485              (gnus-score-remove-from-cache file)))
1486       (kill-buffer (current-buffer)))))
1487
1488 (defun gnus-score-load-files (score-files)
1489   "Load all score files in SCORE-FILES."
1490   ;; Load the score files.
1491   (let (scores)
1492     (while score-files
1493       (if (stringp (car score-files))
1494           ;; It is a string, which means that it's a score file name,
1495           ;; so we load the score file and add the score alist to
1496           ;; the list of alists.
1497           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1498         ;; It is an alist, so we just add it to the list directly.
1499         (setq scores (nconc (car score-files) scores)))
1500       (setq score-files (cdr score-files)))
1501     ;; Prune the score files that are to be excluded, if any.
1502     (when gnus-scores-exclude-files
1503       (let ((s scores)
1504             c)
1505         (while s
1506           (and (setq c (rassq (car s) gnus-score-cache))
1507                (member (car c) gnus-scores-exclude-files)
1508                (setq scores (delq (car s) scores)))
1509           (setq s (cdr s)))))
1510     scores))
1511
1512 (defun gnus-score-headers (score-files &optional trace)
1513   ;; Score `gnus-newsgroup-headers'.
1514   (let (scores news)
1515     ;; PLM: probably this is not the best place to clear orphan-score
1516     (setq gnus-orphan-score nil
1517           gnus-scores-articles nil
1518           gnus-scores-exclude-files nil
1519           scores (gnus-score-load-files score-files))
1520     (setq news scores)
1521     ;; Do the scoring.
1522     (while news
1523       (setq scores news
1524             news nil)
1525       (when (and gnus-summary-default-score
1526                  scores)
1527         (let* ((entries gnus-header-index)
1528                (now (date-to-day (current-time-string)))
1529                (expire (and gnus-score-expiry-days
1530                             (- now gnus-score-expiry-days)))
1531                (headers gnus-newsgroup-headers)
1532                (current-score-file gnus-current-score-file)
1533                entry header new)
1534           (gnus-message 7 "Scoring...")
1535           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1536           (while (setq header (pop headers))
1537             ;; WARNING: The assq makes the function O(N*S) while it could
1538             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1539             ;; and S is (length gnus-newsgroup-scored).
1540             (unless (assq (mail-header-number header) gnus-newsgroup-scored)
1541               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1542                     (cons (cons header (or gnus-summary-default-score 0))
1543                           gnus-scores-articles))))
1544
1545           (save-excursion
1546             (set-buffer (gnus-get-buffer-create "*Headers*"))
1547             (buffer-disable-undo)
1548             (when (gnus-buffer-live-p gnus-summary-buffer)
1549               (message-clone-locals gnus-summary-buffer))
1550
1551             ;; Set the global variant of this variable.
1552             (setq gnus-current-score-file current-score-file)
1553             ;; score orphans
1554             (when gnus-orphan-score
1555               (setq gnus-score-index
1556                     (nth 1 (assoc "references" gnus-header-index)))
1557               (gnus-score-orphans gnus-orphan-score))
1558             ;; Run each header through the score process.
1559             (while entries
1560               (setq entry (pop entries)
1561                     header (nth 0 entry)
1562                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1563               (when (< 0 (apply 'max (mapcar
1564                                       (lambda (score)
1565                                         (length (gnus-score-get header score)))
1566                                       scores)))
1567                 ;; Call the scoring function for this type of "header".
1568                 (when (setq new (funcall (nth 2 entry) scores header
1569                                          now expire trace))
1570                   (push new news))))
1571             (when (gnus-buffer-live-p gnus-summary-buffer)
1572               (let ((scored gnus-newsgroup-scored))
1573                 (with-current-buffer gnus-summary-buffer
1574                   (setq gnus-newsgroup-scored scored))))
1575             ;; Remove the buffer.
1576             (gnus-kill-buffer (current-buffer)))
1577
1578           ;; Add articles to `gnus-newsgroup-scored'.
1579           (while gnus-scores-articles
1580             (when (or (/= gnus-summary-default-score
1581                           (cdar gnus-scores-articles))
1582                       gnus-save-score)
1583               (push (cons (mail-header-number (caar gnus-scores-articles))
1584                           (cdar gnus-scores-articles))
1585                     gnus-newsgroup-scored))
1586             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1587
1588           (let (score)
1589             (while (setq score (pop scores))
1590               (while score
1591                 (when (consp (caar score))
1592                   (gnus-score-advanced (car score) trace))
1593                 (pop score))))
1594
1595           (gnus-message 7 "Scoring...done"))))))
1596
1597 (defun gnus-score-lower-thread (thread score-adjust)
1598   "Lower the score on THREAD with SCORE-ADJUST.
1599 THREAD is expected to contain a list of the form `(PARENT [CHILD1
1600 CHILD2 ...])' where PARENT is a header array and each CHILD is a list
1601 of the same form as THREAD.  The empty list nil is valid.  For each
1602 article in the tree, the score of the corresponding entry in
1603 `gnus-newsgroup-scored' is adjusted by SCORE-ADJUST."
1604   (while thread
1605     (let ((head (car thread)))
1606       (if (listp head)
1607           ;; handle a child and its descendants
1608           (gnus-score-lower-thread head score-adjust)
1609         ;; handle the parent
1610         (let* ((article (mail-header-number head))
1611                (score (assq article gnus-newsgroup-scored)))
1612           (if score (setcdr score (+ (cdr score) score-adjust))
1613             (push (cons article score-adjust) gnus-newsgroup-scored)))))
1614     (setq thread (cdr thread))))
1615
1616 (defun gnus-score-orphans (score)
1617   "Score orphans.
1618 A root is an article with no references.  An orphan is an article
1619 which has references, but is not connected via its references to a
1620 root article.  This function finds all the orphans, and adjusts their
1621 score in `gnus-newsgroup-scored' by SCORE."
1622   ;; gnus-make-threads produces a list, where each entry is a "thread"
1623   ;; as described in the gnus-score-lower-thread docs.  This function
1624   ;; will be called again (after limiting has been done) if the display
1625   ;; is threaded.  It would be nice to somehow save this info and use
1626   ;; it later.
1627   (dolist (thread (gnus-make-threads))
1628     (let ((id (aref (car thread) gnus-score-index)))
1629       ;; If the parent of the thread is not a root, lower the score of
1630       ;; it and its descendants.  Note that some roots seem to satisfy
1631       ;; (eq id nil) and some (eq id "");  not sure why.
1632       (when (and id
1633                  (not (string= id "")))
1634         (gnus-score-lower-thread thread score)))))
1635
1636 (defun gnus-score-integer (scores header now expire &optional trace)
1637   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1638         entries alist)
1639     ;; Find matches.
1640     (while scores
1641       (setq alist (car scores)
1642             scores (cdr scores)
1643             entries (assoc header alist))
1644       (while (cdr entries)              ;First entry is the header index.
1645         (let* ((rest (cdr entries))
1646                (kill (car rest))
1647                (match (nth 0 kill))
1648                (type (or (nth 3 kill) '>))
1649                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1650                (date (nth 2 kill))
1651                (found nil)
1652                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1653                                    (eq type '>=) (eq type '=))
1654                                type
1655                              (error "Invalid match type: %s" type)))
1656                (articles gnus-scores-articles))
1657           ;; Instead of doing all the clever stuff that
1658           ;; `gnus-score-string' does to minimize searches and stuff,
1659           ;; I will assume that people generally will put so few
1660           ;; matches on numbers that any cleverness will take more
1661           ;; time than one would gain.
1662           (while articles
1663             (when (funcall match-func
1664                            (or (aref (caar articles) gnus-score-index) 0)
1665                            match)
1666               (when trace
1667                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1668                       gnus-score-trace))
1669               (setq found t)
1670               (setcdr (car articles) (+ score (cdar articles))))
1671             (setq articles (cdr articles)))
1672           ;; Update expire date
1673           (cond ((null date))           ;Permanent entry.
1674                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1675                  (gnus-score-set 'touched '(t) alist)
1676                  (setcar (nthcdr 2 kill) now))
1677                 ((and expire (< date expire)) ;Old entry, remove.
1678                  (gnus-score-set 'touched '(t) alist)
1679                  (setcdr entries (cdr rest))
1680                  (setq rest entries)))
1681           (setq entries rest)))))
1682   nil)
1683
1684 (defun gnus-score-date (scores header now expire &optional trace)
1685   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1686         entries alist match match-func article)
1687     ;; Find matches.
1688     (while scores
1689       (setq alist (car scores)
1690             scores (cdr scores)
1691             entries (assoc header alist))
1692       (while (cdr entries)              ;First entry is the header index.
1693         (let* ((rest (cdr entries))
1694                (kill (car rest))
1695                (type (or (nth 3 kill) 'before))
1696                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1697                (date (nth 2 kill))
1698                (found nil)
1699                (articles gnus-scores-articles)
1700                l)
1701           (cond
1702            ((eq type 'after)
1703             (setq match-func 'string<
1704                   match (gnus-date-iso8601 (nth 0 kill))))
1705            ((eq type 'before)
1706             (setq match-func 'gnus-string>
1707                   match (gnus-date-iso8601 (nth 0 kill))))
1708            ((eq type 'at)
1709             (setq match-func 'string=
1710                   match (gnus-date-iso8601 (nth 0 kill))))
1711            ((eq type 'regexp)
1712             (setq match-func 'string-match
1713                   match (nth 0 kill)))
1714            (t (error "Invalid match type: %s" type)))
1715           ;; Instead of doing all the clever stuff that
1716           ;; `gnus-score-string' does to minimize searches and stuff,
1717           ;; I will assume that people generally will put so few
1718           ;; matches on numbers that any cleverness will take more
1719           ;; time than one would gain.
1720           (while (setq article (pop articles))
1721             (when (and
1722                    (setq l (aref (car article) gnus-score-index))
1723                    (funcall match-func match (gnus-date-iso8601 l)))
1724               (when trace
1725                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1726                       gnus-score-trace))
1727               (setq found t)
1728               (setcdr article (+ score (cdr article)))))
1729           ;; Update expire date
1730           (cond ((null date))           ;Permanent entry.
1731                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1732                  (gnus-score-set 'touched '(t) alist)
1733                  (setcar (nthcdr 2 kill) now))
1734                 ((and expire (< date expire)) ;Old entry, remove.
1735                  (gnus-score-set 'touched '(t) alist)
1736                  (setcdr entries (cdr rest))
1737                  (setq rest entries)))
1738           (setq entries rest)))))
1739   nil)
1740
1741 (defun gnus-score-body (scores header now expire &optional trace)
1742   (if gnus-agent-fetching
1743       nil
1744     (save-excursion
1745       (setq gnus-scores-articles
1746             (sort gnus-scores-articles
1747                   (lambda (a1 a2)
1748                     (< (mail-header-number (car a1))
1749                        (mail-header-number (car a2))))))
1750       (set-buffer nntp-server-buffer)
1751       (save-restriction
1752         (let* ((buffer-read-only nil)
1753                (articles gnus-scores-articles)
1754                (all-scores scores)
1755                (request-func (cond ((string= "head" header)
1756                                     'gnus-request-head)
1757                                    ((string= "body" header)
1758                                     'gnus-request-body)
1759                                    (t 'gnus-request-article)))
1760                entries alist ofunc article last)
1761           (when articles
1762             (setq last (mail-header-number (caar (last articles))))
1763             ;; Not all backends support partial fetching.  In that case,
1764             ;; we just fetch the entire article.
1765             (unless (gnus-check-backend-function
1766                      (and (string-match "^gnus-" (symbol-name request-func))
1767                           (intern (substring (symbol-name request-func)
1768                                              (match-end 0))))
1769                      gnus-newsgroup-name)
1770               (setq ofunc request-func)
1771               (setq request-func 'gnus-request-article))
1772             (while articles
1773               (setq article (mail-header-number (caar articles)))
1774               (gnus-message 7 "Scoring article %s of %s..." article last)
1775               (widen)
1776               (when (funcall request-func article gnus-newsgroup-name)
1777                 (goto-char (point-min))
1778                 ;; If just parts of the article is to be searched, but the
1779                 ;; backend didn't support partial fetching, we just narrow
1780                 ;; to the relevant parts.
1781                 (when ofunc
1782                   (if (eq ofunc 'gnus-request-head)
1783                       (narrow-to-region
1784                        (point)
1785                        (or (search-forward "\n\n" nil t) (point-max)))
1786                     (narrow-to-region
1787                      (or (search-forward "\n\n" nil t) (point))
1788                      (point-max))))
1789                 (setq scores all-scores)
1790                 ;; Find matches.
1791                 (while scores
1792                   (setq alist (pop scores)
1793                         entries (assoc header alist))
1794                   (while (cdr entries) ;First entry is the header index.
1795                     (let* ((rest (cdr entries))
1796                            (kill (car rest))
1797                            (match (nth 0 kill))
1798                            (type (or (nth 3 kill) 's))
1799                            (score (or (nth 1 kill)
1800                                       gnus-score-interactive-default-score))
1801                            (date (nth 2 kill))
1802                            (found nil)
1803                            (case-fold-search
1804                             (not (or (eq type 'R) (eq type 'S)
1805                                      (eq type 'Regexp) (eq type 'String))))
1806                            (search-func
1807                             (cond ((or (eq type 'r) (eq type 'R)
1808                                        (eq type 'regexp) (eq type 'Regexp))
1809                                    're-search-forward)
1810                                   ((or (eq type 's) (eq type 'S)
1811                                        (eq type 'string) (eq type 'String))
1812                                    'search-forward)
1813                                   (t
1814                                    (error "Invalid match type: %s" type)))))
1815                       (goto-char (point-min))
1816                       (when (funcall search-func match nil t)
1817                         ;; Found a match, update scores.
1818                         (setcdr (car articles) (+ score (cdar articles)))
1819                         (setq found t)
1820                         (when trace
1821                           (push
1822                            (cons (car-safe (rassq alist gnus-score-cache))
1823                                  kill)
1824                            gnus-score-trace)))
1825                       ;; Update expire date
1826                       (unless trace
1827                         (cond
1828                          ((null date))  ;Permanent entry.
1829                          ((and found gnus-update-score-entry-dates)
1830                           ;; Match, update date.
1831                           (gnus-score-set 'touched '(t) alist)
1832                           (setcar (nthcdr 2 kill) now))
1833                          ((and expire (< date expire)) ;Old entry, remove.
1834                           (gnus-score-set 'touched '(t) alist)
1835                           (setcdr entries (cdr rest))
1836                           (setq rest entries))))
1837                       (setq entries rest)))))
1838               (setq articles (cdr articles)))))))
1839     nil))
1840
1841 (defun gnus-score-thread (scores header now expire &optional trace)
1842   (gnus-score-followup scores header now expire trace t))
1843
1844 (defun gnus-score-followup (scores header now expire &optional trace thread)
1845   (if gnus-agent-fetching
1846       ;; FIXME: It seems doable in fetching mode.
1847       nil
1848     ;; Insert the unique article headers in the buffer.
1849     (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1850           (current-score-file gnus-current-score-file)
1851           (all-scores scores)
1852           ;; gnus-score-index is used as a free variable.
1853           alike last this art entries alist articles
1854           new news)
1855
1856       ;; Change score file to the adaptive score file.  All entries that
1857       ;; this function makes will be put into this file.
1858       (save-excursion
1859         (set-buffer gnus-summary-buffer)
1860         (gnus-score-load-file
1861          (or gnus-newsgroup-adaptive-score-file
1862              (gnus-score-file-name
1863               gnus-newsgroup-name gnus-adaptive-file-suffix))))
1864
1865       (setq gnus-scores-articles (sort gnus-scores-articles
1866                                        'gnus-score-string<)
1867             articles gnus-scores-articles)
1868
1869       (erase-buffer)
1870       (while articles
1871         (setq art (car articles)
1872               this (aref (car art) gnus-score-index)
1873               articles (cdr articles))
1874         (if (equal last this)
1875             (push art alike)
1876           (when last
1877             (insert last ?\n)
1878             (put-text-property (1- (point)) (point) 'articles alike))
1879           (setq alike (list art)
1880                 last this)))
1881       (when last                        ; Bwadr, duplicate code.
1882         (insert last ?\n)
1883         (put-text-property (1- (point)) (point) 'articles alike))
1884
1885       ;; Find matches.
1886       (while scores
1887         (setq alist (car scores)
1888               scores (cdr scores)
1889               entries (assoc header alist))
1890         (while (cdr entries)            ;First entry is the header index.
1891           (let* ((rest (cdr entries))
1892                  (kill (car rest))
1893                  (match (nth 0 kill))
1894                  (type (or (nth 3 kill) 's))
1895                  (score (or (nth 1 kill) gnus-score-interactive-default-score))
1896                  (date (nth 2 kill))
1897                  (found nil)
1898                  (mt (aref (symbol-name type) 0))
1899                  (case-fold-search
1900                   (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1901                  (dmt (downcase mt))
1902                  (search-func
1903                   (cond ((= dmt ?r) 're-search-forward)
1904                         ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1905                         (t (error "Invalid match type: %s" type))))
1906                  arts art)
1907             (goto-char (point-min))
1908             (if (= dmt ?e)
1909                 (while (funcall search-func match nil t)
1910                   (and (= (point-at-bol)
1911                           (match-beginning 0))
1912                        (= (progn (end-of-line) (point))
1913                           (match-end 0))
1914                        (progn
1915                          (setq found (setq arts (get-text-property
1916                                                  (point) 'articles)))
1917                          ;; Found a match, update scores.
1918                          (while arts
1919                            (setq art (car arts)
1920                                  arts (cdr arts))
1921                            (gnus-score-add-followups
1922                             (car art) score all-scores thread))))
1923                   (end-of-line))
1924               (while (funcall search-func match nil t)
1925                 (end-of-line)
1926                 (setq found (setq arts (get-text-property (point) 'articles)))
1927                 ;; Found a match, update scores.
1928                 (while (setq art (pop arts))
1929                   (setcdr art (+ score (cdr art)))
1930                   (when trace
1931                     (push (cons
1932                            (car-safe (rassq alist gnus-score-cache))
1933                            kill)
1934                           gnus-score-trace))
1935                   (when (setq new (gnus-score-add-followups
1936                                    (car art) score all-scores thread))
1937                     (push new news)))))
1938             ;; Update expire date
1939             (cond ((null date))         ;Permanent entry.
1940                   ((and found gnus-update-score-entry-dates)
1941                    ;Match, update date.
1942                    (gnus-score-set 'touched '(t) alist)
1943                    (setcar (nthcdr 2 kill) now))
1944                   ((and expire (< date expire)) ;Old entry, remove.
1945                    (gnus-score-set 'touched '(t) alist)
1946                    (setcdr entries (cdr rest))
1947                    (setq rest entries)))
1948             (setq entries rest))))
1949       ;; We change the score file back to the previous one.
1950       (save-excursion
1951         (set-buffer gnus-summary-buffer)
1952         (gnus-score-load-file current-score-file))
1953       (list (cons "references" news)))))
1954
1955 (defun gnus-score-add-followups (header score scores &optional thread)
1956   "Add a score entry to the adapt file."
1957   (save-excursion
1958     (set-buffer gnus-summary-buffer)
1959     (let* ((id (mail-header-id header))
1960            (scores (car scores))
1961            entry dont)
1962       ;; Don't enter a score if there already is one.
1963       (while (setq entry (pop scores))
1964         (and (equal "references" (car entry))
1965              (or (null (nth 3 (cadr entry)))
1966                  (eq 's (nth 3 (cadr entry))))
1967              (assoc id entry)
1968              (setq dont t)))
1969       (unless dont
1970         (gnus-summary-score-entry
1971          (if thread "thread" "references")
1972          id 's score (current-time-string) nil t)))))
1973
1974 (defun gnus-score-string (score-list header now expire &optional trace)
1975   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1976   ;; Update matching entries to NOW and remove unmatched entries older
1977   ;; than EXPIRE.
1978
1979   ;; Insert the unique article headers in the buffer.
1980   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1981         ;; gnus-score-index is used as a free variable.
1982         (simplify (and gnus-score-thread-simplify
1983                        (string= "subject" header)))
1984         alike last this art entries alist articles
1985         fuzzies arts words kill)
1986
1987     ;; Sorting the articles costs os O(N*log N) but will allow us to
1988     ;; only match with each unique header.  Thus the actual matching
1989     ;; will be O(M*U) where M is the number of strings to match with,
1990     ;; and U is the number of unique headers.  It is assumed (but
1991     ;; untested) this will be a net win because of the large constant
1992     ;; factor involved with string matching.
1993     (setq gnus-scores-articles
1994           ;; We cannot string-sort the extra headers list.  *sigh*
1995           (if (= gnus-score-index 9)
1996               gnus-scores-articles
1997             (sort gnus-scores-articles 'gnus-score-string<))
1998           articles gnus-scores-articles)
1999
2000     (erase-buffer)
2001     (while (setq art (pop articles))
2002       (setq this (aref (car art) gnus-score-index))
2003
2004       ;; If we're working with non-standard headers, we are stuck
2005       ;; with working on them as a group.  What a hassle.
2006       ;; Just wait 'til you see what horrors we commit against `match'...
2007       (if (= gnus-score-index 9)
2008           (setq this (gnus-prin1-to-string this))) ; ick.
2009
2010       (if simplify
2011           (setq this (gnus-map-function gnus-simplify-subject-functions this)))
2012       (if (equal last this)
2013           ;; O(N*H) cons-cells used here, where H is the number of
2014           ;; headers.
2015           (push art alike)
2016         (when last
2017           ;; Insert the line, with a text property on the
2018           ;; terminating newline referring to the articles with
2019           ;; this line.
2020           (insert last ?\n)
2021           (put-text-property (1- (point)) (point) 'articles alike))
2022         (setq alike (list art)
2023               last this)))
2024     (when last                          ; Bwadr, duplicate code.
2025       (insert last ?\n)
2026       (put-text-property (1- (point)) (point) 'articles alike))
2027
2028     ;; Go through all the score alists and pick out the entries
2029     ;; for this header.
2030     (while score-list
2031       (setq alist (pop score-list)
2032             ;; There's only one instance of this header for
2033             ;; each score alist.
2034             entries (assoc header alist))
2035       (while (cdr entries)              ;First entry is the header index.
2036         (let* ((kill (cadr entries))
2037                (type (or (nth 3 kill) 's))
2038                (score (or (nth 1 kill) gnus-score-interactive-default-score))
2039                (date (nth 2 kill))
2040                (extra (nth 4 kill))     ; non-standard header; string.
2041                (found nil)
2042                (mt (aref (symbol-name type) 0))
2043                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
2044                (dmt (downcase mt))
2045                ;; Assume user already simplified regexp and fuzzies
2046                (match (if (and simplify (not (memq dmt '(?f ?r))))
2047                           (gnus-map-function
2048                            gnus-simplify-subject-functions
2049                            (nth 0 kill))
2050                         (nth 0 kill)))
2051                (search-func
2052                 (cond ((= dmt ?r) 're-search-forward)
2053                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
2054                       ((= dmt ?w) nil)
2055                       (t (error "Invalid match type: %s" type)))))
2056
2057           ;; Evil hackery to make match usable in non-standard headers.
2058           (when extra
2059             (setq match (concat "[ (](" extra " \\. \"[^)]*"
2060                                 match "[^\"]*\")[ )]")
2061                   search-func 're-search-forward)) ; XXX danger?!?
2062
2063           (cond
2064            ;; Fuzzy matches.  We save these for later.
2065            ((= dmt ?f)
2066             (push (cons entries alist) fuzzies)
2067             (setq entries (cdr entries)))
2068            ;; Word matches.  Save these for even later.
2069            ((= dmt ?w)
2070             (push (cons entries alist) words)
2071             (setq entries (cdr entries)))
2072            ;; Exact matches.
2073            ((= dmt ?e)
2074             ;; Do exact matching.
2075             (goto-char (point-min))
2076             (while (and (not (eobp))
2077                         (funcall search-func match nil t))
2078               ;; Is it really exact?
2079               (and (eolp)
2080                    (= (point-at-bol) (match-beginning 0))
2081                    ;; Yup.
2082                    (progn
2083                      (setq found (setq arts (get-text-property
2084                                              (point) 'articles)))
2085                      ;; Found a match, update scores.
2086                      (if trace
2087                          (while (setq art (pop arts))
2088                            (setcdr art (+ score (cdr art)))
2089                            (push
2090                             (cons
2091                              (car-safe (rassq alist gnus-score-cache))
2092                              kill)
2093                             gnus-score-trace))
2094                        (while (setq art (pop arts))
2095                          (setcdr art (+ score (cdr art)))))))
2096               (forward-line 1))
2097             ;; Update expiry date
2098             (if trace
2099                 (setq entries (cdr entries))
2100               (cond
2101                ;; Permanent entry.
2102                ((null date)
2103                 (setq entries (cdr entries)))
2104                ;; We have a match, so we update the date.
2105                ((and found gnus-update-score-entry-dates)
2106                 (gnus-score-set 'touched '(t) alist)
2107                 (setcar (nthcdr 2 kill) now)
2108                 (setq entries (cdr entries)))
2109                ;; This entry has expired, so we remove it.
2110                ((and expire (< date expire))
2111                 (gnus-score-set 'touched '(t) alist)
2112                 (setcdr entries (cddr entries)))
2113                ;; No match; go to next entry.
2114                (t
2115                 (setq entries (cdr entries))))))
2116            ;; Regexp and substring matching.
2117            (t
2118             (goto-char (point-min))
2119             (when (string= match "")
2120               (setq match "\n"))
2121             (while (and (not (eobp))
2122                         (funcall search-func match nil t))
2123               (goto-char (match-beginning 0))
2124               (end-of-line)
2125               (setq found (setq arts (get-text-property (point) 'articles)))
2126               ;; Found a match, update scores.
2127               (if trace
2128                   (while (setq art (pop arts))
2129                     (setcdr art (+ score (cdr art)))
2130                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
2131                           gnus-score-trace))
2132                 (while (setq art (pop arts))
2133                   (setcdr art (+ score (cdr art)))))
2134               (forward-line 1))
2135             ;; Update expiry date
2136             (if trace
2137                 (setq entries (cdr entries))
2138               (cond
2139                ;; Permanent entry.
2140                ((null date)
2141                 (setq entries (cdr entries)))
2142                ;; We have a match, so we update the date.
2143                ((and found gnus-update-score-entry-dates)
2144                 (gnus-score-set 'touched '(t) alist)
2145                 (setcar (nthcdr 2 kill) now)
2146                 (setq entries (cdr entries)))
2147                ;; This entry has expired, so we remove it.
2148                ((and expire (< date expire))
2149                 (gnus-score-set 'touched '(t) alist)
2150                 (setcdr entries (cddr entries)))
2151                ;; No match; go to next entry.
2152                (t
2153                 (setq entries (cdr entries))))))))))
2154
2155     ;; Find fuzzy matches.
2156     (when fuzzies
2157       ;; Simplify the entire buffer for easy matching.
2158       (gnus-simplify-buffer-fuzzy)
2159       (while (setq kill (cadaar fuzzies))
2160         (let* ((match (nth 0 kill))
2161                (type (nth 3 kill))
2162                (score (or (nth 1 kill) gnus-score-interactive-default-score))
2163                (date (nth 2 kill))
2164                (mt (aref (symbol-name type) 0))
2165                (case-fold-search (not (= mt ?F)))
2166                found)
2167           (goto-char (point-min))
2168           (while (and (not (eobp))
2169                       (search-forward match nil t))
2170             (when (and (= (point-at-bol) (match-beginning 0))
2171                        (eolp))
2172               (setq found (setq arts (get-text-property (point) 'articles)))
2173               (if trace
2174                   (while (setq art (pop arts))
2175                     (setcdr art (+ score (cdr art)))
2176                     (push (cons
2177                            (car-safe (rassq (cdar fuzzies) gnus-score-cache))
2178                            kill)
2179                           gnus-score-trace))
2180                 ;; Found a match, update scores.
2181                 (while (setq art (pop arts))
2182                   (setcdr art (+ score (cdr art))))))
2183             (forward-line 1))
2184           ;; Update expiry date
2185           (if (not trace)
2186               (cond
2187                ;; Permanent.
2188                ((null date)
2189                 ;; Do nothing.
2190                 )
2191                ;; Match, update date.
2192                ((and found gnus-update-score-entry-dates)
2193                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2194                 (setcar (nthcdr 2 kill) now))
2195                ;; Old entry, remove.
2196                ((and expire (< date expire))
2197                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2198                 (setcdr (caar fuzzies) (cddaar fuzzies)))))
2199           (setq fuzzies (cdr fuzzies)))))
2200
2201     (when words
2202       ;; Enter all words into the hashtb.
2203       (let ((hashtb (gnus-make-hashtable
2204                      (* 10 (count-lines (point-min) (point-max))))))
2205         (gnus-enter-score-words-into-hashtb hashtb)
2206         (while (setq kill (cadaar words))
2207           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
2208                  (date (nth 2 kill))
2209                  found)
2210             (when (setq arts (intern-soft (nth 0 kill) hashtb))
2211               (setq arts (symbol-value arts))
2212               (setq found t)
2213               (if trace
2214                   (while (setq art (pop arts))
2215                     (setcdr art (+ score (cdr art)))
2216                     (push (cons
2217                            (car-safe (rassq (cdar words) gnus-score-cache))
2218                            kill)
2219                           gnus-score-trace))
2220                 ;; Found a match, update scores.
2221                 (while (setq art (pop arts))
2222                   (setcdr art (+ score (cdr art))))))
2223             ;; Update expiry date
2224             (if (not trace)
2225                 (cond
2226                  ;; Permanent.
2227                  ((null date)
2228                   ;; Do nothing.
2229                   )
2230                  ;; Match, update date.
2231                  ((and found gnus-update-score-entry-dates)
2232                   (gnus-score-set 'touched '(t) (cdar words))
2233                   (setcar (nthcdr 2 kill) now))
2234                  ;; Old entry, remove.
2235                  ((and expire (< date expire))
2236                   (gnus-score-set 'touched '(t) (cdar words))
2237                   (setcdr (caar words) (cddaar words)))))
2238             (setq words (cdr words))))))
2239     nil))
2240
2241 (defun gnus-enter-score-words-into-hashtb (hashtb)
2242   ;; Find all the words in the buffer and enter them into
2243   ;; the hashtable.
2244   (let (word val)
2245     (goto-char (point-min))
2246     (with-syntax-table gnus-adaptive-word-syntax-table
2247       (while (re-search-forward "\\b\\w+\\b" nil t)
2248         (setq val
2249               (gnus-gethash
2250                (setq word (downcase (buffer-substring
2251                                      (match-beginning 0) (match-end 0))))
2252                hashtb))
2253         (gnus-sethash
2254          word
2255          (append (get-text-property (point-at-eol) 'articles) val)
2256          hashtb)))
2257     ;; Make all the ignorable words ignored.
2258     (let ((ignored (append gnus-ignored-adaptive-words
2259                            (if gnus-adaptive-word-no-group-words
2260                                (message-tokenize-header
2261                                 (gnus-group-real-name gnus-newsgroup-name)
2262                                 "."))
2263                            gnus-default-ignored-adaptive-words)))
2264       (while ignored
2265         (gnus-sethash (pop ignored) nil hashtb)))))
2266
2267 (defun gnus-score-string< (a1 a2)
2268   ;; Compare headers in articles A2 and A2.
2269   ;; The header index used is the free variable `gnus-score-index'.
2270   (string-lessp (aref (car a1) gnus-score-index)
2271                 (aref (car a2) gnus-score-index)))
2272
2273 (defun gnus-current-score-file-nondirectory (&optional score-file)
2274   (let ((score-file (or score-file gnus-current-score-file)))
2275     (if score-file
2276         (gnus-short-group-name (file-name-nondirectory score-file))
2277       "none")))
2278
2279 (defun gnus-score-adaptive ()
2280   "Create adaptive score rules for this newsgroup."
2281   (when gnus-newsgroup-adaptive
2282     ;; We change the score file to the adaptive score file.
2283     (save-excursion
2284       (set-buffer gnus-summary-buffer)
2285       (gnus-score-load-file
2286        (or gnus-newsgroup-adaptive-score-file
2287            (gnus-home-score-file gnus-newsgroup-name t)
2288            (gnus-score-file-name
2289             gnus-newsgroup-name gnus-adaptive-file-suffix))))
2290     ;; Perform ordinary line scoring.
2291     (when (or (not (listp gnus-newsgroup-adaptive))
2292               (memq 'line gnus-newsgroup-adaptive))
2293       (save-excursion
2294         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
2295                (alist malist)
2296                (date (current-time-string))
2297                (data gnus-newsgroup-data)
2298                elem headers match func)
2299           ;; First we transform the adaptive rule alist into something
2300           ;; that's faster to process.
2301           (while malist
2302             (setq elem (car malist))
2303             (when (symbolp (car elem))
2304               (setcar elem (symbol-value (car elem))))
2305             (setq elem (cdr elem))
2306             (while elem
2307               (when (fboundp
2308                      (setq func
2309                            (intern
2310                             (concat "mail-header-"
2311                                     (if (eq (caar elem) 'followup)
2312                                         "message-id"
2313                                       (downcase (symbol-name (caar elem))))))))
2314                 (setcdr (car elem)
2315                         (cons (if (eq (caar elem) 'followup)
2316                                   "references"
2317                                 (symbol-name (caar elem)))
2318                               (cdar elem)))
2319                 (setcar (car elem)
2320                         `(lambda (h)
2321                            (,func h))))
2322               (setq elem (cdr elem)))
2323             (setq malist (cdr malist)))
2324           ;; Then we score away.
2325           (while data
2326             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2327             (if (or (not elem)
2328                     (gnus-data-pseudo-p (car data)))
2329                 ()
2330               (when (setq headers (gnus-data-header (car data)))
2331                 (while elem
2332                   (setq match (funcall (caar elem) headers))
2333                   (gnus-summary-score-entry
2334                    (nth 1 (car elem)) match
2335                    (cond
2336                     ((numberp match)
2337                      '=)
2338                     ((equal (nth 1 (car elem)) "date")
2339                      'a)
2340                     (t
2341                      ;; Whether we use substring or exact matches is
2342                      ;; controlled here.
2343                      (if (or (not gnus-score-exact-adapt-limit)
2344                              (< (length match) gnus-score-exact-adapt-limit))
2345                          'e
2346                        (if (equal (nth 1 (car elem)) "subject")
2347                            'f 's))))
2348                    (nth 2 (car elem)) date nil t)
2349                   (setq elem (cdr elem)))))
2350             (setq data (cdr data))))))
2351
2352     ;; Perform adaptive word scoring.
2353     (when (and (listp gnus-newsgroup-adaptive)
2354                (memq 'word gnus-newsgroup-adaptive))
2355       (with-temp-buffer
2356         (let* ((hashtb (gnus-make-hashtable 1000))
2357                (date (date-to-day (current-time-string)))
2358                (data gnus-newsgroup-data)
2359                word d score val)
2360           (with-syntax-table gnus-adaptive-word-syntax-table
2361             ;; Go through all articles.
2362             (while (setq d (pop data))
2363               (when (and
2364                      (not (gnus-data-pseudo-p d))
2365                      (setq score
2366                            (cdr (assq
2367                                  (gnus-data-mark d)
2368                                  gnus-adaptive-word-score-alist))))
2369                 ;; This article has a mark that should lead to
2370                 ;; adaptive word rules, so we insert the subject
2371                 ;; and find all words in that string.
2372                 (insert (mail-header-subject (gnus-data-header d)))
2373                 (downcase-region (point-min) (point-max))
2374                 (goto-char (point-min))
2375                 (while (re-search-forward "\\b\\w+\\b" nil t)
2376                   ;; Put the word and score into the hashtb.
2377                   (setq val (gnus-gethash (setq word (match-string 0))
2378                                           hashtb))
2379                   (when (or (not gnus-adaptive-word-length-limit)
2380                             (> (length word)
2381                                gnus-adaptive-word-length-limit))
2382                     (setq val (+ score (or val 0)))
2383                     (if (and gnus-adaptive-word-minimum
2384                              (< val gnus-adaptive-word-minimum))
2385                         (setq val gnus-adaptive-word-minimum))
2386                     (gnus-sethash word val hashtb)))
2387                 (erase-buffer))))
2388           ;; Make all the ignorable words ignored.
2389           (let ((ignored (append gnus-ignored-adaptive-words
2390                                  (if gnus-adaptive-word-no-group-words
2391                                      (message-tokenize-header
2392                                       (gnus-group-real-name
2393                                        gnus-newsgroup-name)
2394                                       "."))
2395                                  gnus-default-ignored-adaptive-words)))
2396             (while ignored
2397               (gnus-sethash (pop ignored) nil hashtb)))
2398           ;; Now we have all the words and scores, so we
2399           ;; add these rules to the ADAPT file.
2400           (set-buffer gnus-summary-buffer)
2401           (mapatoms
2402            (lambda (word)
2403              (when (symbol-value word)
2404                (gnus-summary-score-entry
2405                 "subject" (symbol-name word) 'w (symbol-value word)
2406                 date nil t)))
2407            hashtb))))))
2408
2409 (defun gnus-score-edit-done ()
2410   (let ((bufnam (buffer-file-name (current-buffer)))
2411         (winconf gnus-prev-winconf))
2412     (when winconf
2413       (set-window-configuration winconf))
2414     (gnus-score-remove-from-cache bufnam)
2415     (gnus-score-load-file bufnam)
2416     (run-hooks 'gnus-score-edit-done-hook)))
2417
2418 (defun gnus-score-find-trace ()
2419   "Find all score rules that applies to the current article."
2420   (interactive)
2421   (let ((old-scored gnus-newsgroup-scored))
2422     (let ((gnus-newsgroup-headers
2423            (list (gnus-summary-article-header)))
2424           (gnus-newsgroup-scored nil)
2425           ;; Must be synced with `gnus-score-edit-file-at-point':
2426           (frmt "%S [%s] -> %s\n")
2427           trace
2428           file)
2429       (save-excursion
2430         (nnheader-set-temp-buffer "*Score Trace*"))
2431       (setq gnus-score-trace nil)
2432       (gnus-possibly-score-headers 'trace)
2433       (if (not (setq trace gnus-score-trace))
2434           (gnus-error
2435            1 "No score rules apply to the current article (default score %d)."
2436            gnus-summary-default-score)
2437         (set-buffer "*Score Trace*")
2438         ;; Use a keymap instead?
2439         (local-set-key "q"
2440                        (lambda ()
2441                          (interactive)
2442                          (bury-buffer nil)
2443                          (gnus-summary-expand-window)))
2444         (local-set-key "k"
2445                        (lambda ()
2446                          (interactive)
2447                          (kill-buffer (current-buffer))
2448                          (gnus-summary-expand-window)))
2449         (local-set-key "e" (lambda ()
2450                              "Run `gnus-score-edit-file-at-point'."
2451                              (interactive)
2452                              (gnus-score-edit-file-at-point)))
2453         (local-set-key "f" (lambda ()
2454                              "Run `gnus-score-edit-file-at-point'."
2455                              (interactive)
2456                              (gnus-score-edit-file-at-point 'format)))
2457         (local-set-key "t" 'toggle-truncate-lines)
2458         (setq truncate-lines t)
2459         (dolist (entry trace)
2460           (setq file (or (car entry)
2461                          ;; Must be synced with
2462                          ;; `gnus-score-edit-file-at-point':
2463                          "(non-file rule)"))
2464           (insert
2465            (format frmt
2466                    (cdr entry)
2467                    ;; Don't use `file-name-sans-extension' to see .SCORE and
2468                    ;; .ADAPT directly:
2469                    (file-name-nondirectory file)
2470                    (abbreviate-file-name file))))
2471         (insert
2472          "\n\nQuick help:
2473
2474 Type `e' to edit score file corresponding to the score rule on current line,
2475 `f' to format (pretty print) the score file and edit it,
2476 `t' toggle to truncate long lines in this buffer,
2477 `q' to quit, `k' to kill score trace buffer.
2478
2479 The first sexp on each line is the score rule, followed by the file name of
2480 the score file and its full name, including the directory.")
2481         (goto-char (point-min))
2482         (gnus-configure-windows 'score-trace)))
2483     (set-buffer gnus-summary-buffer)
2484     (setq gnus-newsgroup-scored old-scored)))
2485
2486 (defun gnus-score-find-favourite-words ()
2487   "List words used in scoring."
2488   (interactive)
2489   (let ((alists (gnus-score-load-files (gnus-all-score-files)))
2490         alist rule rules kill)
2491     ;; Go through all the score alists for this group
2492     ;; and find all `w' rules.
2493     (while (setq alist (pop alists))
2494       (while (setq rule (pop alist))
2495         (when (and (stringp (car rule))
2496                    (equal "subject" (downcase (pop rule))))
2497           (while (setq kill (pop rule))
2498             (when (memq (nth 3 kill) '(w W word Word))
2499               (push (cons (or (nth 1 kill)
2500                               gnus-score-interactive-default-score)
2501                           (car kill))
2502                     rules))))))
2503     (setq rules (sort rules (lambda (r1 r2)
2504                               (string-lessp (cdr r1) (cdr r2)))))
2505     ;; Add up words that have appeared several times.
2506     (let ((r rules))
2507       (while (cdr r)
2508         (if (equal (cdar r) (cdadr r))
2509             (progn
2510               (setcar (car r) (+ (caar r) (caadr r)))
2511               (setcdr r (cddr r)))
2512           (pop r))))
2513     ;; Insert the words.
2514     (nnheader-set-temp-buffer "*Score Words*")
2515     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2516         (gnus-error 3 "No word score rules")
2517       (while rules
2518         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2519         (pop rules))
2520       (goto-char (point-min))
2521       (gnus-configure-windows 'score-words))))
2522
2523 (defun gnus-summary-rescore ()
2524   "Redo the entire scoring process in the current summary."
2525   (interactive)
2526   (gnus-score-save)
2527   (setq gnus-score-cache nil)
2528   (setq gnus-newsgroup-scored nil)
2529   (gnus-possibly-score-headers)
2530   (gnus-score-update-all-lines))
2531
2532 (defun gnus-score-flush-cache ()
2533   "Flush the cache of score files."
2534   (interactive)
2535   (gnus-score-save)
2536   (setq gnus-score-cache nil
2537         gnus-score-alist nil
2538         gnus-short-name-score-file-cache nil)
2539   (gnus-message 6 "The score cache is now flushed"))
2540
2541 (gnus-add-shutdown 'gnus-score-close 'gnus)
2542
2543 (defvar gnus-score-file-alist-cache nil)
2544
2545 (defun gnus-score-close ()
2546   "Clear all internal score variables."
2547   (setq gnus-score-cache nil
2548         gnus-internal-global-score-files nil
2549         gnus-score-file-list nil
2550         gnus-score-file-alist-cache nil))
2551
2552 ;; Summary score marking commands.
2553
2554 (defun gnus-summary-raise-same-subject-and-select (score)
2555   "Raise articles which has the same subject with SCORE and select the next."
2556   (interactive "p")
2557   (let ((subject (gnus-summary-article-subject)))
2558     (gnus-summary-raise-score score)
2559     (while (gnus-summary-find-subject subject)
2560       (gnus-summary-raise-score score))
2561     (gnus-summary-next-article t)))
2562
2563 (defun gnus-summary-raise-same-subject (score)
2564   "Raise articles which has the same subject with SCORE."
2565   (interactive "p")
2566   (let ((subject (gnus-summary-article-subject)))
2567     (gnus-summary-raise-score score)
2568     (while (gnus-summary-find-subject subject)
2569       (gnus-summary-raise-score score))
2570     (gnus-summary-next-subject 1 t)))
2571
2572 (defun gnus-score-delta-default (level)
2573   (if level (prefix-numeric-value level)
2574     gnus-score-interactive-default-score))
2575
2576 (defun gnus-summary-raise-thread (&optional score)
2577   "Raise the score of the articles in the current thread with SCORE."
2578   (interactive "P")
2579   (setq score (gnus-score-delta-default score))
2580   (let (e)
2581     (save-excursion
2582       (let ((articles (gnus-summary-articles-in-thread)))
2583         (while articles
2584           (gnus-summary-goto-subject (car articles))
2585           (gnus-summary-raise-score score)
2586           (setq articles (cdr articles))))
2587       (setq e (point)))
2588     (let ((gnus-summary-check-current t))
2589       (unless (zerop (gnus-summary-next-subject 1 t))
2590         (goto-char e))))
2591   (gnus-summary-recenter)
2592   (gnus-summary-position-point)
2593   (gnus-set-mode-line 'summary))
2594
2595 (defun gnus-summary-lower-same-subject-and-select (score)
2596   "Raise articles which has the same subject with SCORE and select the next."
2597   (interactive "p")
2598   (gnus-summary-raise-same-subject-and-select (- score)))
2599
2600 (defun gnus-summary-lower-same-subject (score)
2601   "Raise articles which has the same subject with SCORE."
2602   (interactive "p")
2603   (gnus-summary-raise-same-subject (- score)))
2604
2605 (defun gnus-summary-lower-thread (&optional score)
2606   "Lower score of articles in the current thread with SCORE."
2607   (interactive "P")
2608   (gnus-summary-raise-thread (- (gnus-score-delta-default score))))
2609
2610 ;;; Finding score files.
2611
2612 (defun gnus-score-score-files (group)
2613   "Return a list of all possible score files."
2614   ;; Search and set any global score files.
2615   (when gnus-global-score-files
2616     (unless gnus-internal-global-score-files
2617       (gnus-score-search-global-directories gnus-global-score-files)))
2618   ;; Fix the kill-file dir variable.
2619   (setq gnus-kill-files-directory
2620         (file-name-as-directory gnus-kill-files-directory))
2621   ;; If we can't read it, there are no score files.
2622   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2623       (setq gnus-score-file-list nil)
2624     (if (not (gnus-use-long-file-name 'not-score))
2625         ;; We do not use long file names, so we have to do some
2626         ;; directory traversing.
2627         (setq gnus-score-file-list
2628               (cons nil
2629                     (or gnus-short-name-score-file-cache
2630                         (prog2
2631                             (gnus-message 6 "Finding all score files...")
2632                             (setq gnus-short-name-score-file-cache
2633                                   (gnus-score-score-files-1
2634                                    gnus-kill-files-directory))
2635                           (gnus-message 6 "Finding all score files...done")))))
2636       ;; We want long file names.
2637       (when (or (not gnus-score-file-list)
2638                 (not (car gnus-score-file-list))
2639                 (gnus-file-newer-than gnus-kill-files-directory
2640                                       (car gnus-score-file-list)))
2641         (setq gnus-score-file-list
2642               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2643                     (nreverse
2644                      (directory-files
2645                       gnus-kill-files-directory t
2646                       (gnus-score-file-regexp)))))))
2647     (cdr gnus-score-file-list)))
2648
2649 (defun gnus-score-score-files-1 (dir)
2650   "Return all possible score files under DIR."
2651   (let ((files (list (expand-file-name dir)))
2652         (regexp (gnus-score-file-regexp))
2653         (case-fold-search nil)
2654         seen out file)
2655     (while (setq file (pop files))
2656       (cond
2657        ;; Ignore files that start with a dot.
2658        ((string-match "^\\." (file-name-nondirectory file))
2659         nil)
2660        ;; Add subtrees of directory to also be searched.
2661        ((and (file-directory-p file)
2662              (not (member (file-truename file) seen)))
2663         (push (file-truename file) seen)
2664         (setq files (nconc (directory-files file t nil t) files)))
2665        ;; Add files to the list of score files.
2666        ((string-match regexp file)
2667         (push file out))))
2668     (or out
2669         ;; Return a dummy value.
2670         (list (expand-file-name "this.file.does.not.exist.SCORE"
2671                                 gnus-kill-files-directory)))))
2672
2673 (defun gnus-score-file-regexp ()
2674   "Return a regexp that match all score files."
2675   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2676           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2677
2678 (defun gnus-score-find-bnews (group)
2679   "Return a list of score files for GROUP.
2680 The score files are those files in the ~/News/ directory which matches
2681 GROUP using BNews sys file syntax."
2682   (let* ((sfiles (append (gnus-score-score-files group)
2683                          gnus-internal-global-score-files))
2684          (kill-dir (file-name-as-directory
2685                     (expand-file-name gnus-kill-files-directory)))
2686          (klen (length kill-dir))
2687          (score-regexp (gnus-score-file-regexp))
2688          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2689          (group-trans (nnheader-translate-file-chars group t))
2690          ofiles not-match regexp)
2691     (save-excursion
2692       (set-buffer (gnus-get-buffer-create "*gnus score files*"))
2693       (buffer-disable-undo)
2694       ;; Go through all score file names and create regexp with them
2695       ;; as the source.
2696       (while sfiles
2697         (erase-buffer)
2698         (insert (car sfiles))
2699         (goto-char (point-min))
2700         ;; First remove the suffix itself.
2701         (when (re-search-forward (concat "." score-regexp) nil t)
2702           (replace-match "" t t)
2703           (goto-char (point-min))
2704           (if (looking-at (regexp-quote kill-dir))
2705               ;; If the file name was just "SCORE", `klen' is one character
2706               ;; too much.
2707               (delete-char (min (1- (point-max)) klen))
2708             (goto-char (point-max))
2709             (if (re-search-backward gnus-directory-sep-char-regexp nil t)
2710                 (delete-region (1+ (point)) (point-min))
2711               (gnus-message 1 "Can't find directory separator in %s"
2712                             (car sfiles))))
2713           ;; If short file names were used, we have to translate slashes.
2714           (goto-char (point-min))
2715           (let ((regexp (concat
2716                          "[/:" (if trans (char-to-string trans)) "]")))
2717             (while (re-search-forward regexp nil t)
2718               (replace-match "." t t)))
2719           ;; Kludge to get rid of "nntp+" problems.
2720           (goto-char (point-min))
2721           (when (looking-at "nn[a-z]+\\+")
2722             (search-forward "+")
2723             (forward-char -1)
2724             (insert "\\")
2725             (forward-char 1))
2726           ;; Kludge to deal with "++".
2727           (while (search-forward "+" nil t)
2728             (replace-match "\\+" t t))
2729           ;; Translate "all" to ".*".
2730           (goto-char (point-min))
2731           (while (search-forward "all" nil t)
2732             (replace-match ".*" t t))
2733           (goto-char (point-min))
2734           ;; Deal with "not."s.
2735           (if (looking-at "not.")
2736               (progn
2737                 (setq not-match t)
2738                 (setq regexp
2739                       (concat "^" (buffer-substring 5 (point-max)) "$")))
2740             (setq regexp (concat "^" (buffer-substring 1 (point-max)) "$"))
2741             (setq not-match nil))
2742           ;; Finally - if this resulting regexp matches the group name,
2743           ;; we add this score file to the list of score files
2744           ;; applicable to this group.
2745           (when (or (and not-match
2746                          (ignore-errors
2747                            (not (string-match regexp group-trans))))
2748                     (and (not not-match)
2749                          (ignore-errors (string-match regexp group-trans))))
2750             (push (car sfiles) ofiles)))
2751         (setq sfiles (cdr sfiles)))
2752       (gnus-kill-buffer (current-buffer))
2753       ;; Slight kludge here - the last score file returned should be
2754       ;; the local score file, whether it exists or not.  This is so
2755       ;; that any score commands the user enters will go to the right
2756       ;; file, and not end up in some global score file.
2757       (let ((localscore (gnus-score-file-name group)))
2758         (setq ofiles (cons localscore (delete localscore ofiles))))
2759       (gnus-sort-score-files (nreverse ofiles)))))
2760
2761 (defun gnus-score-find-single (group)
2762   "Return list containing the score file for GROUP."
2763   (list (or gnus-newsgroup-adaptive-score-file
2764             (gnus-score-file-name group gnus-adaptive-file-suffix))
2765         (gnus-score-file-name group)))
2766
2767 (defun gnus-score-find-hierarchical (group)
2768   "Return list of score files for GROUP.
2769 This includes the score file for the group and all its parents."
2770   (let* ((prefix (gnus-group-real-prefix group))
2771          (all (list nil))
2772          (group (gnus-group-real-name group))
2773          (start 0))
2774     (while (string-match "\\." group (1+ start))
2775       (setq start (match-beginning 0))
2776       (push (substring group 0 start) all))
2777     (push group all)
2778     (setq all
2779           (nconc
2780            (mapcar (lambda (group)
2781                      (gnus-score-file-name group gnus-adaptive-file-suffix))
2782                    (setq all (nreverse all)))
2783            (mapcar 'gnus-score-file-name all)))
2784     (if (equal prefix "")
2785         all
2786       (mapcar
2787        (lambda (file)
2788          (nnheader-translate-file-chars
2789           (concat (file-name-directory file) prefix
2790                   (file-name-nondirectory file))))
2791        all))))
2792
2793 (defun gnus-score-file-rank (file)
2794   "Return a number that says how specific score FILE is.
2795 Destroys the current buffer."
2796   (if (member file gnus-internal-global-score-files)
2797       0
2798     (when (string-match
2799            (concat "^" (regexp-quote
2800                         (expand-file-name
2801                          (file-name-as-directory gnus-kill-files-directory))))
2802            file)
2803       (setq file (substring file (match-end 0))))
2804     (insert file)
2805     (goto-char (point-min))
2806     (let ((beg (point))
2807           elems)
2808       (while (re-search-forward "[./]" nil t)
2809         (push (buffer-substring beg (1- (point)))
2810               elems))
2811       (erase-buffer)
2812       (setq elems (delete "all" elems))
2813       (length elems))))
2814
2815 (defun gnus-sort-score-files (files)
2816   "Sort FILES so that the most general files come first."
2817   (with-temp-buffer
2818     (let ((alist
2819            (mapcar
2820             (lambda (file)
2821               (cons (inline (gnus-score-file-rank file)) file))
2822             files)))
2823       (mapcar 'cdr (sort alist 'car-less-than-car)))))
2824
2825 (defun gnus-score-find-alist (group)
2826   "Return list of score files for GROUP.
2827 The list is determined from the variable `gnus-score-file-alist'."
2828   (let ((alist gnus-score-file-multiple-match-alist)
2829         score-files)
2830     ;; if this group has been seen before, return the cached entry
2831     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2832         (cdr score-files)               ;ensures caching groups with no matches
2833       ;; handle the multiple match alist
2834       (while alist
2835         (when (string-match (caar alist) group)
2836           (setq score-files
2837                 (nconc score-files (copy-sequence (cdar alist)))))
2838         (setq alist (cdr alist)))
2839       (setq alist gnus-score-file-single-match-alist)
2840       ;; handle the single match alist
2841       (while alist
2842         (when (string-match (caar alist) group)
2843           ;; progn used just in case ("regexp") has no files
2844           ;; and score-files is still nil.  -sj
2845           ;; this can be construed as a "stop searching here" feature :>
2846           ;; and used to simplify regexps in the single-alist
2847           (setq score-files
2848                 (nconc score-files (copy-sequence (cdar alist))))
2849           (setq alist nil))
2850         (setq alist (cdr alist)))
2851       ;; cache the score files
2852       (push (cons group score-files) gnus-score-file-alist-cache)
2853       score-files)))
2854
2855 (defun gnus-all-score-files (&optional group)
2856   "Return a list of all score files for the current group."
2857   (let ((funcs gnus-score-find-score-files-function)
2858         (group (or group gnus-newsgroup-name))
2859         score-files)
2860     (when group
2861       ;; Make sure funcs is a list.
2862       (and funcs
2863            (not (listp funcs))
2864            (setq funcs (list funcs)))
2865       (when gnus-score-use-all-scores
2866         ;; Get the initial score files for this group.
2867         (when funcs
2868           (setq score-files (nreverse (gnus-score-find-alist group))))
2869         ;; Add any home adapt files.
2870         (let ((home (gnus-home-score-file group t)))
2871           (when home
2872             (push home score-files)
2873             (setq gnus-newsgroup-adaptive-score-file home)))
2874         ;; Check whether there is a `adapt-file' group parameter.
2875         (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2876           (when param-file
2877             (push param-file score-files)
2878             (setq gnus-newsgroup-adaptive-score-file param-file))))
2879       ;; Go through all the functions for finding score files (or actual
2880       ;; scores) and add them to a list.
2881       (while funcs
2882         (when (functionp (car funcs))
2883           (setq score-files
2884                 (append score-files
2885                         (nreverse (funcall (car funcs) group)))))
2886         (setq funcs (cdr funcs)))
2887       (when gnus-score-use-all-scores
2888         ;; Add any home score files.
2889         (let ((home (gnus-home-score-file group)))
2890           (when home
2891             (push home score-files)))
2892         ;; Check whether there is a `score-file' group parameter.
2893         (let ((param-file (gnus-group-find-parameter group 'score-file)))
2894           (when param-file
2895             (push param-file score-files))))
2896       ;; Expand all files names.
2897       (let ((files score-files))
2898         (while files
2899           (when (stringp (car files))
2900             (setcar files (expand-file-name
2901                            (car files) gnus-kill-files-directory)))
2902           (pop files)))
2903       (setq score-files (nreverse score-files))
2904       ;; Remove any duplicate score files.
2905       (while (and score-files
2906                   (member (car score-files) (cdr score-files)))
2907         (pop score-files))
2908       (let ((files score-files))
2909         (while (cdr files)
2910           (if (member (cadr files) (cddr files))
2911               (setcdr files (cddr files))
2912             (pop files))))
2913       ;; Do the scoring if there are any score files for this group.
2914       score-files)))
2915
2916 (defun gnus-possibly-score-headers (&optional trace)
2917   "Do scoring if scoring is required."
2918   (let ((score-files (gnus-all-score-files)))
2919     (when score-files
2920       (gnus-score-headers score-files trace))))
2921
2922 (defun gnus-score-file-name (newsgroup &optional suffix)
2923   "Return the name of a score file for NEWSGROUP."
2924   (let ((suffix (or suffix gnus-score-file-suffix)))
2925     (nnheader-translate-file-chars
2926      (cond
2927       ((or (null newsgroup)
2928            (string-equal newsgroup ""))
2929        ;; The global score file is placed at top of the directory.
2930        (expand-file-name suffix gnus-kill-files-directory))
2931       ((gnus-use-long-file-name 'not-score)
2932        ;; Append ".SCORE" to newsgroup name.
2933        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2934                                  "." suffix)
2935                          gnus-kill-files-directory))
2936       (t
2937        ;; Place "SCORE" under the hierarchical directory.
2938        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2939                                  "/" suffix)
2940                          gnus-kill-files-directory))))))
2941
2942 (defun gnus-score-search-global-directories (files)
2943   "Scan all global score directories for score files."
2944   ;; Set the variable `gnus-internal-global-score-files' to all
2945   ;; available global score files.
2946   (interactive (list gnus-global-score-files))
2947   (let (out)
2948     (while files
2949       ;; #### /$ Unix-specific?
2950       (if (file-directory-p (car files))
2951           (setq out (nconc (directory-files
2952                             (car files) t
2953                             (concat (gnus-score-file-regexp) "$"))))
2954         (push (car files) out))
2955       (setq files (cdr files)))
2956     (setq gnus-internal-global-score-files out)))
2957
2958 (defun gnus-score-default-fold-toggle ()
2959   "Toggle folding for new score file entries."
2960   (interactive)
2961   (setq gnus-score-default-fold (not gnus-score-default-fold))
2962   (if gnus-score-default-fold
2963       (gnus-message 1 "New score file entries will be case insensitive.")
2964     (gnus-message 1 "New score file entries will be case sensitive.")))
2965
2966 ;;; Home score file.
2967
2968 (defun gnus-home-score-file (group &optional adapt)
2969   "Return the home score file for GROUP.
2970 If ADAPT, return the home adaptive file instead."
2971   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2972         elem found)
2973     ;; Make sure we have a list.
2974     (unless (listp list)
2975       (setq list (list list)))
2976     ;; Go through the list and look for matches.
2977     (while (and (not found)
2978                 (setq elem (pop list)))
2979       (setq found
2980             (cond
2981              ;; Simple string.
2982              ((stringp elem)
2983               elem)
2984              ;; Function.
2985              ((functionp elem)
2986               (funcall elem group))
2987              ;; Regexp-file cons.
2988              ((consp elem)
2989               (when (string-match (gnus-globalify-regexp (car elem)) group)
2990                 (replace-match (cadr elem) t nil group))))))
2991     (when found
2992       (setq found (nnheader-translate-file-chars found))
2993       (if (file-name-absolute-p found)
2994           found
2995         (nnheader-concat gnus-kill-files-directory found)))))
2996
2997 (defun gnus-hierarchial-home-score-file (group)
2998   "Return the score file of the top-level hierarchy of GROUP."
2999   (if (string-match "^[^.]+\\." group)
3000       (concat (match-string 0 group) gnus-score-file-suffix)
3001     ;; Group name without any dots.
3002     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
3003             gnus-score-file-suffix)))
3004
3005 (defun gnus-hierarchial-home-adapt-file (group)
3006   "Return the adapt file of the top-level hierarchy of GROUP."
3007   (if (string-match "^[^.]+\\." group)
3008       (concat (match-string 0 group) gnus-adaptive-file-suffix)
3009     ;; Group name without any dots.
3010     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
3011             gnus-adaptive-file-suffix)))
3012
3013 (defun gnus-current-home-score-file (group)
3014   "Return the \"current\" regular score file."
3015   (car (nreverse (gnus-score-find-alist group))))
3016
3017 ;;;
3018 ;;; Score decays
3019 ;;;
3020
3021 (defun gnus-decay-score (score)
3022   "Decay SCORE according to `gnus-score-decay-constant' and `gnus-score-decay-scale'."
3023   (let ((n (- score
3024               (* (if (< score 0) -1 1)
3025                  (min (abs score)
3026                       (max gnus-score-decay-constant
3027                            (* (abs score)
3028                               gnus-score-decay-scale)))))))
3029     (if (and (featurep 'xemacs)
3030              ;; XEmacs' floor can handle only the floating point
3031              ;; number below the half of the maximum integer.
3032              (> (abs n) (lsh -1 -2)))
3033         (string-to-number
3034          (car (split-string (number-to-string n) "\\.")))
3035       (floor n))))
3036
3037 (defun gnus-decay-scores (alist day)
3038   "Decay non-permanent scores in ALIST."
3039   (let ((times (- (time-to-days (current-time)) day))
3040         kill entry updated score n)
3041     (unless (zerop times)               ;Done decays today already?
3042       (while (setq entry (pop alist))
3043         (when (stringp (car entry))
3044           (setq entry (cdr entry))
3045           (while (setq kill (pop entry))
3046             (when (nth 2 kill)
3047               (setq updated t)
3048               (setq score (or (nth 1 kill)
3049                               gnus-score-interactive-default-score)
3050                     n times)
3051               (while (natnump (decf n))
3052                 (setq score (funcall gnus-decay-score-function score)))
3053               (setcdr kill (cons score
3054                                  (cdr (cdr kill)))))))))
3055     ;; Return whether this score file needs to be saved.  By Je-haysuss!
3056     updated))
3057
3058 (defun gnus-score-regexp-bad-p (regexp)
3059   "Test whether REGEXP is safe for Gnus scoring.
3060 A regexp is unsafe if it matches newline or a buffer boundary.
3061
3062 If the regexp is good, return nil.  If the regexp is bad, return a
3063 cons cell (SYM . STRING), where the symbol SYM is `new' or `bad'.
3064 In the `new' case, the string is a safe replacement for REGEXP.
3065 In the `bad' case, the string is a unsafe subexpression of REGEXP,
3066 and we do not have a simple replacement to suggest.
3067
3068 See Info node `(gnus)Scoring Tips' for examples of good regular expressions."
3069   (let (case-fold-search)
3070     (and
3071      ;; First, try a relatively fast necessary condition.
3072      ;; Notice ranges (like [^:] or [\t-\r]), \s>, \Sw, \W, \', \`:
3073      (string-match "\n\\|\\\\[SsW`']\\|\\[\\^\\|[\0-\n]-" regexp)
3074      ;; Now break the regexp into tokens, and check each:
3075      (let ((tail regexp)                ; remaining regexp to check
3076            tok                          ; current token
3077            bad                          ; nil, or bad subexpression
3078            new                          ; nil, or replacement regexp so far
3079            end)                         ; length of current token
3080        (while (and (not bad)
3081                    (string-match
3082                     "\\`\\(\\\\[sS]?.\\|\\[\\^?]?[^]]*]\\|[^\\]\\)"
3083                     tail))
3084          (setq end (match-end 0)
3085                tok (substring tail 0 end)
3086                tail (substring tail end))
3087          (if;; Is token `bad' (matching newline or buffer ends)?
3088              (or (member tok '("\n" "\\W" "\\`" "\\'"))
3089                  ;; This next handles "[...]", "\\s.", and "\\S.":
3090                  (and (> end 2) (string-match tok "\n")))
3091              (let ((newtok
3092                     ;; Try to suggest a replacement for tok ...
3093                     (cond ((string-equal tok "\\`") "^") ; or "\\(^\\)"
3094                           ((string-equal tok "\\'") "$") ; or "\\($\\)"
3095                           ((string-match "\\[\\^" tok) ; very common
3096                            (concat (substring tok 0 -1) "\n]")))))
3097                (if newtok
3098                    (setq new
3099                          (concat
3100                           (or new
3101                               ;; good prefix so far:
3102                               (substring regexp 0 (- (+ (length tail) end))))
3103                           newtok))
3104                  ;; No replacement idea, so give up:
3105                  (setq bad tok)))
3106            ;; tok is good, may need to extend new
3107            (and new (setq new (concat new tok)))))
3108        ;; Now return a value:
3109        (cond
3110         (bad (cons 'bad bad))
3111         (new (cons 'new new))
3112         (t nil))))))
3113
3114 (provide 'gnus-score)
3115
3116 ;;; gnus-score.el ends here