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