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