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