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