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