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