* binhex.el: Don't autoload executable-find.
[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-appt-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 (lambda (file)
1216                                      (gnus-score-load-file file))
1217                                    (if adapt-file (cons adapt-file files)
1218                                      files)))))
1219       (when (and eval (not global))
1220         (eval eval))
1221       ;; We then expand any exclude-file directives.
1222       (setq gnus-scores-exclude-files
1223             (nconc
1224              (apply
1225               'nconc
1226               (mapcar
1227                (lambda (sfile)
1228                  (list
1229                   (expand-file-name sfile (file-name-directory file))
1230                   (expand-file-name sfile gnus-kill-files-directory)))
1231                exclude-files))
1232              gnus-scores-exclude-files))
1233       (when local
1234         (save-excursion
1235           (set-buffer gnus-summary-buffer)
1236           (while local
1237             (and (consp (car local))
1238                  (symbolp (caar local))
1239                  (progn
1240                    (make-local-variable (caar local))
1241                    (set (caar local) (nth 1 (car local)))))
1242             (setq local (cdr local)))))
1243       (when orphan
1244         (setq gnus-orphan-score orphan))
1245       (setq gnus-adaptive-score-alist
1246             (cond ((equal adapt '(t))
1247                    (setq gnus-newsgroup-adaptive t)
1248                    gnus-default-adaptive-score-alist)
1249                   ((equal adapt '(ignore))
1250                    (setq gnus-newsgroup-adaptive nil))
1251                   ((consp adapt)
1252                    (setq gnus-newsgroup-adaptive t)
1253                    adapt)
1254                   (t
1255                    gnus-default-adaptive-score-alist)))
1256       (setq gnus-thread-expunge-below
1257             (or thread-mark-and-expunge gnus-thread-expunge-below))
1258       (setq gnus-summary-mark-below
1259             (or mark mark-and-expunge gnus-summary-mark-below))
1260       (setq gnus-summary-expunge-below
1261             (or expunge mark-and-expunge gnus-summary-expunge-below))
1262       (setq gnus-newsgroup-adaptive-score-file
1263             (or adapt-file gnus-newsgroup-adaptive-score-file)))
1264     (setq gnus-current-score-file file)
1265     (setq gnus-score-alist alist)
1266     lists))
1267
1268 (defun gnus-score-load (file)
1269   ;; Load score FILE.
1270   (let ((cache (assoc file gnus-score-cache)))
1271     (if cache
1272         (setq gnus-score-alist (cdr cache))
1273       (setq gnus-score-alist nil)
1274       (gnus-score-load-score-alist file)
1275       (unless gnus-score-alist
1276         (setq gnus-score-alist (copy-alist '((touched nil)))))
1277       (push (cons file gnus-score-alist) gnus-score-cache))))
1278
1279 (defun gnus-score-remove-from-cache (file)
1280   (setq gnus-score-cache
1281         (delq (assoc file gnus-score-cache) gnus-score-cache)))
1282
1283 (defun gnus-score-load-score-alist (file)
1284   "Read score FILE."
1285   (let (alist)
1286     (if (not (file-readable-p file))
1287         ;; Couldn't read file.
1288         (setq gnus-score-alist nil)
1289       ;; Read file.
1290       (with-temp-buffer
1291         (let ((coding-system-for-read score-mode-coding-system))
1292           (insert-file-contents file))
1293         (goto-char (point-min))
1294         ;; Only do the loading if the score file isn't empty.
1295         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
1296           (setq alist
1297                 (condition-case ()
1298                     (read (current-buffer))
1299                   (error
1300                    (gnus-error 3.2 "Problem with score file %s" file))))))
1301       (cond
1302        ((and alist
1303              (atom alist))
1304         ;; Bogus score file.
1305         (error "Invalid syntax with score file %s" file))
1306        ((eq (car alist) 'setq)
1307         ;; This is an old-style score file.
1308         (setq gnus-score-alist (gnus-score-transform-old-to-new alist)))
1309        (t
1310         (setq gnus-score-alist alist)))
1311       ;; Check the syntax of the score file.
1312       (setq gnus-score-alist
1313             (gnus-score-check-syntax gnus-score-alist file)))))
1314
1315 (defun gnus-score-check-syntax (alist file)
1316   "Check the syntax of the score ALIST."
1317   (cond
1318    ((null alist)
1319     nil)
1320    ((not (consp alist))
1321     (gnus-message 1 "Score file is not a list: %s" file)
1322     (ding)
1323     nil)
1324    (t
1325     (let ((a alist)
1326           sr err s type)
1327       (while (and a (not err))
1328         (setq
1329          err
1330          (cond
1331           ((not (listp (car a)))
1332            (format "Invalid score element %s in %s" (car a) file))
1333           ((stringp (caar a))
1334            (cond
1335             ((not (listp (setq sr (cdar a))))
1336              (format "Invalid header match %s in %s" (nth 1 (car a)) file))
1337             (t
1338              (setq type (caar a))
1339              (while (and sr (not err))
1340                (setq s (pop sr))
1341                (setq
1342                 err
1343                 (cond
1344                  ((if (member (downcase type) '("lines" "chars"))
1345                       (not (numberp (car s)))
1346                     (not (stringp (car s))))
1347                   (format "Invalid match %s in %s" (car s) file))
1348                  ((and (cadr s) (not (integerp (cadr s))))
1349                   (format "Non-integer score %s in %s" (cadr s) file))
1350                  ((and (caddr s) (not (integerp (caddr s))))
1351                   (format "Non-integer date %s in %s" (caddr s) file))
1352                  ((and (cadddr s) (not (symbolp (cadddr s))))
1353                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1354              err)))))
1355         (setq a (cdr a)))
1356       (if err
1357           (progn
1358             (ding)
1359             (gnus-message 3 err)
1360             (sit-for 2)
1361             nil)
1362         alist)))))
1363
1364 (defun gnus-score-transform-old-to-new (alist)
1365   (let* ((alist (nth 2 alist))
1366          out entry)
1367     (when (eq (car alist) 'quote)
1368       (setq alist (nth 1 alist)))
1369     (while alist
1370       (setq entry (car alist))
1371       (if (stringp (car entry))
1372           (let ((scor (cdr entry)))
1373             (push entry out)
1374             (while scor
1375               (setcar scor
1376                       (list (caar scor) (nth 2 (car scor))
1377                             (and (nth 3 (car scor))
1378                                  (date-to-day (nth 3 (car scor))))
1379                             (if (nth 1 (car scor)) 'r 's)))
1380               (setq scor (cdr scor))))
1381         (push (if (not (listp (cdr entry)))
1382                   (list (car entry) (cdr entry))
1383                 entry)
1384               out))
1385       (setq alist (cdr alist)))
1386     (cons (list 'touched t) (nreverse out))))
1387
1388 (defun gnus-score-save ()
1389   ;; Save all score information.
1390   (let ((cache gnus-score-cache)
1391         entry score file)
1392     (save-excursion
1393       (setq gnus-score-alist nil)
1394       (nnheader-set-temp-buffer " *Gnus Scores*")
1395       (while cache
1396         (current-buffer)
1397         (setq entry (pop cache)
1398               file (nnheader-translate-file-chars (car entry) t)
1399               score (cdr entry))
1400         (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1401                 (gnus-score-get 'read-only score)
1402                 (and (file-exists-p file)
1403                      (not (file-writable-p file))))
1404             ()
1405           (setq score (setcdr entry (gnus-delete-alist 'touched score)))
1406           (erase-buffer)
1407           (let (emacs-lisp-mode-hook)
1408             (if (string-match
1409                  (concat (regexp-quote gnus-adaptive-file-suffix) "$")
1410                  file)
1411                 ;; This is an adaptive score file, so we do not run
1412                 ;; it through `pp'.  These files can get huge, and
1413                 ;; are not meant to be edited by human hands.
1414                 (gnus-prin1 score)
1415               ;; This is a normal score file, so we print it very
1416               ;; prettily.
1417               (let ((lisp-mode-syntax-table score-mode-syntax-table))
1418                 (pp score (current-buffer)))))
1419           (gnus-make-directory (file-name-directory file))
1420           ;; If the score file is empty, we delete it.
1421           (if (zerop (buffer-size))
1422               (delete-file file)
1423             ;; There are scores, so we write the file.
1424             (when (file-writable-p file)
1425               (let ((coding-system-for-write score-mode-coding-system))
1426                 (gnus-write-buffer file))
1427               (when gnus-score-after-write-file-function
1428                 (funcall gnus-score-after-write-file-function file)))))
1429         (and gnus-score-uncacheable-files
1430              (string-match gnus-score-uncacheable-files file)
1431              (gnus-score-remove-from-cache file)))
1432       (kill-buffer (current-buffer)))))
1433
1434 (defun gnus-score-load-files (score-files)
1435   "Load all score files in SCORE-FILES."
1436   ;; Load the score files.
1437   (let (scores)
1438     (while score-files
1439       (if (stringp (car score-files))
1440           ;; It is a string, which means that it's a score file name,
1441           ;; so we load the score file and add the score alist to
1442           ;; the list of alists.
1443           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1444         ;; It is an alist, so we just add it to the list directly.
1445         (setq scores (nconc (car score-files) scores)))
1446       (setq score-files (cdr score-files)))
1447     ;; Prune the score files that are to be excluded, if any.
1448     (when gnus-scores-exclude-files
1449       (let ((s scores)
1450             c)
1451         (while s
1452           (and (setq c (rassq (car s) gnus-score-cache))
1453                (member (car c) gnus-scores-exclude-files)
1454                (setq scores (delq (car s) scores)))
1455           (setq s (cdr s)))))
1456     scores))
1457
1458 (defun gnus-score-headers (score-files &optional trace)
1459   ;; Score `gnus-newsgroup-headers'.
1460   (let (scores news)
1461     ;; PLM: probably this is not the best place to clear orphan-score
1462     (setq gnus-orphan-score nil
1463           gnus-scores-articles nil
1464           gnus-scores-exclude-files nil
1465           scores (gnus-score-load-files score-files))
1466     (setq news scores)
1467     ;; Do the scoring.
1468     (while news
1469       (setq scores news
1470             news nil)
1471       (when (and gnus-summary-default-score
1472                  scores)
1473         (let* ((entries gnus-header-index)
1474                (now (date-to-day (current-time-string)))
1475                (expire (and gnus-score-expiry-days
1476                             (- now gnus-score-expiry-days)))
1477                (headers gnus-newsgroup-headers)
1478                (current-score-file gnus-current-score-file)
1479                entry header new)
1480           (gnus-message 7 "Scoring...")
1481           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1482           (while (setq header (pop headers))
1483             ;; WARNING: The assq makes the function O(N*S) while it could
1484             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1485             ;; and S is (length gnus-newsgroup-scored).
1486             (unless (assq (mail-header-number header) gnus-newsgroup-scored)
1487               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1488                     (cons (cons header (or gnus-summary-default-score 0))
1489                           gnus-scores-articles))))
1490
1491           (save-excursion
1492             (set-buffer (gnus-get-buffer-create "*Headers*"))
1493             (buffer-disable-undo)
1494             (when (gnus-buffer-live-p gnus-summary-buffer)
1495               (message-clone-locals gnus-summary-buffer))
1496
1497             ;; Set the global variant of this variable.
1498             (setq gnus-current-score-file current-score-file)
1499             ;; score orphans
1500             (when gnus-orphan-score
1501               (setq gnus-score-index
1502                     (nth 1 (assoc "references" gnus-header-index)))
1503               (gnus-score-orphans gnus-orphan-score))
1504             ;; Run each header through the score process.
1505             (while entries
1506               (setq entry (pop entries)
1507                     header (nth 0 entry)
1508                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1509               (when (< 0 (apply 'max (mapcar
1510                                       (lambda (score)
1511                                         (length (gnus-score-get header score)))
1512                                       scores)))
1513                 ;; Call the scoring function for this type of "header".
1514                 (when (setq new (funcall (nth 2 entry) scores header
1515                                          now expire trace))
1516                   (push new news))))
1517             (when (gnus-buffer-live-p gnus-summary-buffer)
1518               (let ((scored gnus-newsgroup-scored))
1519                 (with-current-buffer gnus-summary-buffer
1520                   (setq gnus-newsgroup-scored scored))))
1521             ;; Remove the buffer.
1522             (gnus-kill-buffer (current-buffer)))
1523
1524           ;; Add articles to `gnus-newsgroup-scored'.
1525           (while gnus-scores-articles
1526             (when (or (/= gnus-summary-default-score
1527                           (cdar gnus-scores-articles))
1528                       gnus-save-score)
1529               (push (cons (mail-header-number (caar gnus-scores-articles))
1530                           (cdar gnus-scores-articles))
1531                     gnus-newsgroup-scored))
1532             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1533
1534           (let (score)
1535             (while (setq score (pop scores))
1536               (while score
1537                 (when (consp (caar score))
1538                   (gnus-score-advanced (car score) trace))
1539                 (pop score))))
1540
1541           (gnus-message 7 "Scoring...done"))))))
1542
1543 (defun gnus-score-lower-thread (thread score-adjust)
1544   "Lower the score on THREAD with SCORE-ADJUST.
1545 THREAD is expected to contain a list of the form `(PARENT [CHILD1
1546 CHILD2 ...])' where PARENT is a header array and each CHILD is a list
1547 of the same form as THREAD.  The empty list nil is valid.  For each
1548 article in the tree, the score of the corresponding entry in
1549 `gnus-newsgroup-scored' is adjusted by SCORE-ADJUST."
1550   (while thread
1551     (let ((head (car thread)))
1552       (if (listp head)
1553           ;; handle a child and its descendants
1554           (gnus-score-lower-thread head score-adjust)
1555         ;; handle the parent
1556         (let* ((article (mail-header-number head))
1557                (score (assq article gnus-newsgroup-scored)))
1558           (if score (setcdr score (+ (cdr score) score-adjust))
1559             (push (cons article score-adjust) gnus-newsgroup-scored)))))
1560     (setq thread (cdr thread))))
1561
1562 (defun gnus-score-orphans (score)
1563   "Score orphans.
1564 A root is an article with no references.  An orphan is an article
1565 which has references, but is not connected via its references to a
1566 root article.  This function finds all the orphans, and adjusts their
1567 score in `gnus-newsgroup-scored' by SCORE."
1568   ;; gnus-make-threads produces a list, where each entry is a "thread"
1569   ;; as described in the gnus-score-lower-thread docs.  This function
1570   ;; will be called again (after limiting has been done) if the display
1571   ;; is threaded.  It would be nice to somehow save this info and use
1572   ;; it later.
1573   (dolist (thread (gnus-make-threads))
1574     (let ((id (aref (car thread) gnus-score-index)))
1575       ;; If the parent of the thread is not a root, lower the score of
1576       ;; it and its descendants.  Note that some roots seem to satisfy
1577       ;; (eq id nil) and some (eq id "");  not sure why.
1578       (when (and id
1579                  (not (string= id "")))
1580         (gnus-score-lower-thread thread score)))))
1581
1582 (defun gnus-score-integer (scores header now expire &optional trace)
1583   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1584         entries alist)
1585     ;; Find matches.
1586     (while scores
1587       (setq alist (car scores)
1588             scores (cdr scores)
1589             entries (assoc header alist))
1590       (while (cdr entries)              ;First entry is the header index.
1591         (let* ((rest (cdr entries))
1592                (kill (car rest))
1593                (match (nth 0 kill))
1594                (type (or (nth 3 kill) '>))
1595                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1596                (date (nth 2 kill))
1597                (found nil)
1598                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1599                                    (eq type '>=) (eq type '=))
1600                                type
1601                              (error "Invalid match type: %s" type)))
1602                (articles gnus-scores-articles))
1603           ;; Instead of doing all the clever stuff that
1604           ;; `gnus-score-string' does to minimize searches and stuff,
1605           ;; I will assume that people generally will put so few
1606           ;; matches on numbers that any cleverness will take more
1607           ;; time than one would gain.
1608           (while articles
1609             (when (funcall match-func
1610                            (or (aref (caar articles) gnus-score-index) 0)
1611                            match)
1612               (when trace
1613                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1614                       gnus-score-trace))
1615               (setq found t)
1616               (setcdr (car articles) (+ score (cdar articles))))
1617             (setq articles (cdr articles)))
1618           ;; Update expire date
1619           (cond ((null date))           ;Permanent entry.
1620                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1621                  (gnus-score-set 'touched '(t) alist)
1622                  (setcar (nthcdr 2 kill) now))
1623                 ((and expire (< date expire)) ;Old entry, remove.
1624                  (gnus-score-set 'touched '(t) alist)
1625                  (setcdr entries (cdr rest))
1626                  (setq rest entries)))
1627           (setq entries rest)))))
1628   nil)
1629
1630 (defun gnus-score-date (scores header now expire &optional trace)
1631   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1632         entries alist match match-func article)
1633     ;; Find matches.
1634     (while scores
1635       (setq alist (car scores)
1636             scores (cdr scores)
1637             entries (assoc header alist))
1638       (while (cdr entries)              ;First entry is the header index.
1639         (let* ((rest (cdr entries))
1640                (kill (car rest))
1641                (type (or (nth 3 kill) 'before))
1642                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1643                (date (nth 2 kill))
1644                (found nil)
1645                (articles gnus-scores-articles)
1646                l)
1647           (cond
1648            ((eq type 'after)
1649             (setq match-func 'string<
1650                   match (gnus-date-iso8601 (nth 0 kill))))
1651            ((eq type 'before)
1652             (setq match-func 'gnus-string>
1653                   match (gnus-date-iso8601 (nth 0 kill))))
1654            ((eq type 'at)
1655             (setq match-func 'string=
1656                   match (gnus-date-iso8601 (nth 0 kill))))
1657            ((eq type 'regexp)
1658             (setq match-func 'string-match
1659                   match (nth 0 kill)))
1660            (t (error "Invalid match type: %s" type)))
1661           ;; Instead of doing all the clever stuff that
1662           ;; `gnus-score-string' does to minimize searches and stuff,
1663           ;; I will assume that people generally will put so few
1664           ;; matches on numbers that any cleverness will take more
1665           ;; time than one would gain.
1666           (while (setq article (pop articles))
1667             (when (and
1668                    (setq l (aref (car article) gnus-score-index))
1669                    (funcall match-func match (gnus-date-iso8601 l)))
1670               (when trace
1671                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1672                       gnus-score-trace))
1673               (setq found t)
1674               (setcdr article (+ score (cdr article)))))
1675           ;; Update expire date
1676           (cond ((null date))           ;Permanent entry.
1677                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1678                  (gnus-score-set 'touched '(t) alist)
1679                  (setcar (nthcdr 2 kill) now))
1680                 ((and expire (< date expire)) ;Old entry, remove.
1681                  (gnus-score-set 'touched '(t) alist)
1682                  (setcdr entries (cdr rest))
1683                  (setq rest entries)))
1684           (setq entries rest)))))
1685   nil)
1686
1687 (defun gnus-score-body (scores header now expire &optional trace)
1688   (if gnus-agent-fetching
1689       nil
1690     (save-excursion
1691       (setq gnus-scores-articles
1692             (sort gnus-scores-articles
1693                   (lambda (a1 a2)
1694                     (< (mail-header-number (car a1))
1695                        (mail-header-number (car a2))))))
1696       (set-buffer nntp-server-buffer)
1697       (save-restriction
1698         (let* ((buffer-read-only nil)
1699                (articles gnus-scores-articles)
1700                (all-scores scores)
1701                (request-func (cond ((string= "head" header)
1702                                     'gnus-request-head)
1703                                    ((string= "body" header)
1704                                     'gnus-request-body)
1705                                    (t 'gnus-request-article)))
1706                entries alist ofunc article last)
1707           (when articles
1708             (setq last (mail-header-number (caar (last articles))))
1709           ;; Not all backends support partial fetching.  In that case,
1710             ;; we just fetch the entire article.
1711             (unless (gnus-check-backend-function
1712                      (and (string-match "^gnus-" (symbol-name request-func))
1713                           (intern (substring (symbol-name request-func)
1714                                              (match-end 0))))
1715                      gnus-newsgroup-name)
1716               (setq ofunc request-func)
1717               (setq request-func 'gnus-request-article))
1718             (while articles
1719               (setq article (mail-header-number (caar articles)))
1720               (gnus-message 7 "Scoring article %s of %s..." article last)
1721               (widen)
1722               (when (funcall request-func article gnus-newsgroup-name)
1723                 (goto-char (point-min))
1724             ;; If just parts of the article is to be searched, but the
1725             ;; backend didn't support partial fetching, we just narrow
1726                 ;; to the relevant parts.
1727                 (when ofunc
1728                   (if (eq ofunc 'gnus-request-head)
1729                       (narrow-to-region
1730                        (point)
1731                        (or (search-forward "\n\n" nil t) (point-max)))
1732                     (narrow-to-region
1733                      (or (search-forward "\n\n" nil t) (point))
1734                      (point-max))))
1735                 (setq scores all-scores)
1736                 ;; Find matches.
1737                 (while scores
1738                   (setq alist (pop scores)
1739                         entries (assoc header alist))
1740                   (while (cdr entries) ;First entry is the header index.
1741                     (let* ((rest (cdr entries))
1742                            (kill (car rest))
1743                            (match (nth 0 kill))
1744                            (type (or (nth 3 kill) 's))
1745                            (score (or (nth 1 kill)
1746                                       gnus-score-interactive-default-score))
1747                            (date (nth 2 kill))
1748                            (found nil)
1749                            (case-fold-search
1750                             (not (or (eq type 'R) (eq type 'S)
1751                                      (eq type 'Regexp) (eq type 'String))))
1752                            (search-func
1753                             (cond ((or (eq type 'r) (eq type 'R)
1754                                        (eq type 'regexp) (eq type 'Regexp))
1755                                    're-search-forward)
1756                                   ((or (eq type 's) (eq type 'S)
1757                                        (eq type 'string) (eq type 'String))
1758                                    'search-forward)
1759                                   (t
1760                                    (error "Invalid match type: %s" type)))))
1761                       (goto-char (point-min))
1762                       (when (funcall search-func match nil t)
1763                         ;; Found a match, update scores.
1764                         (setcdr (car articles) (+ score (cdar articles)))
1765                         (setq found t)
1766                         (when trace
1767                           (push
1768                            (cons (car-safe (rassq alist gnus-score-cache))
1769                                  kill)
1770                            gnus-score-trace)))
1771                       ;; Update expire date
1772                       (unless trace
1773                         (cond
1774                          ((null date))  ;Permanent entry.
1775                          ((and found gnus-update-score-entry-dates)
1776                           ;; Match, update date.
1777                           (gnus-score-set 'touched '(t) alist)
1778                           (setcar (nthcdr 2 kill) now))
1779                          ((and expire (< date expire)) ;Old entry, remove.
1780                           (gnus-score-set 'touched '(t) alist)
1781                           (setcdr entries (cdr rest))
1782                           (setq rest entries))))
1783                       (setq entries rest)))))
1784               (setq articles (cdr articles)))))))
1785     nil))
1786
1787 (defun gnus-score-thread (scores header now expire &optional trace)
1788   (gnus-score-followup scores header now expire trace t))
1789
1790 (defun gnus-score-followup (scores header now expire &optional trace thread)
1791   (if gnus-agent-fetching
1792       ;; FIXME: It seems doable in fetching mode.
1793       nil
1794     ;; Insert the unique article headers in the buffer.
1795     (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1796           (current-score-file gnus-current-score-file)
1797           (all-scores scores)
1798           ;; gnus-score-index is used as a free variable.
1799           alike last this art entries alist articles
1800           new news)
1801
1802       ;; Change score file to the adaptive score file.  All entries that
1803       ;; this function makes will be put into this file.
1804       (save-excursion
1805         (set-buffer gnus-summary-buffer)
1806         (gnus-score-load-file
1807          (or gnus-newsgroup-adaptive-score-file
1808              (gnus-score-file-name
1809               gnus-newsgroup-name gnus-adaptive-file-suffix))))
1810
1811       (setq gnus-scores-articles (sort gnus-scores-articles
1812                                        'gnus-score-string<)
1813             articles gnus-scores-articles)
1814
1815       (erase-buffer)
1816       (while articles
1817         (setq art (car articles)
1818               this (aref (car art) gnus-score-index)
1819               articles (cdr articles))
1820         (if (equal last this)
1821             (push art alike)
1822           (when last
1823             (insert last ?\n)
1824             (put-text-property (1- (point)) (point) 'articles alike))
1825           (setq alike (list art)
1826                 last this)))
1827       (when last                        ; Bwadr, duplicate code.
1828         (insert last ?\n)
1829         (put-text-property (1- (point)) (point) 'articles alike))
1830
1831       ;; Find matches.
1832       (while scores
1833         (setq alist (car scores)
1834               scores (cdr scores)
1835               entries (assoc header alist))
1836         (while (cdr entries)            ;First entry is the header index.
1837           (let* ((rest (cdr entries))
1838                  (kill (car rest))
1839                  (match (nth 0 kill))
1840                  (type (or (nth 3 kill) 's))
1841                  (score (or (nth 1 kill) gnus-score-interactive-default-score))
1842                  (date (nth 2 kill))
1843                  (found nil)
1844                  (mt (aref (symbol-name type) 0))
1845                  (case-fold-search
1846                   (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1847                  (dmt (downcase mt))
1848                  (search-func
1849                   (cond ((= dmt ?r) 're-search-forward)
1850                         ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1851                         (t (error "Invalid match type: %s" type))))
1852                  arts art)
1853             (goto-char (point-min))
1854             (if (= dmt ?e)
1855                 (while (funcall search-func match nil t)
1856                   (and (= (point-at-bol)
1857                           (match-beginning 0))
1858                        (= (progn (end-of-line) (point))
1859                           (match-end 0))
1860                        (progn
1861                          (setq found (setq arts (get-text-property
1862                                                  (point) 'articles)))
1863                          ;; Found a match, update scores.
1864                          (while arts
1865                            (setq art (car arts)
1866                                  arts (cdr arts))
1867                            (gnus-score-add-followups
1868                             (car art) score all-scores thread))))
1869                   (end-of-line))
1870               (while (funcall search-func match nil t)
1871                 (end-of-line)
1872                 (setq found (setq arts (get-text-property (point) 'articles)))
1873                 ;; Found a match, update scores.
1874                 (while (setq art (pop arts))
1875                   (setcdr art (+ score (cdr art)))
1876                   (when trace
1877                     (push (cons
1878                            (car-safe (rassq alist gnus-score-cache))
1879                            kill)
1880                           gnus-score-trace))
1881                   (when (setq new (gnus-score-add-followups
1882                                    (car art) score all-scores thread))
1883                     (push new news)))))
1884             ;; Update expire date
1885             (cond ((null date))         ;Permanent entry.
1886                   ((and found gnus-update-score-entry-dates)
1887                                         ;Match, update date.
1888                    (gnus-score-set 'touched '(t) alist)
1889                    (setcar (nthcdr 2 kill) now))
1890                   ((and expire (< date expire)) ;Old entry, remove.
1891                    (gnus-score-set 'touched '(t) alist)
1892                    (setcdr entries (cdr rest))
1893                    (setq rest entries)))
1894             (setq entries rest))))
1895       ;; We change the score file back to the previous one.
1896       (save-excursion
1897         (set-buffer gnus-summary-buffer)
1898         (gnus-score-load-file current-score-file))
1899       (list (cons "references" news)))))
1900
1901 (defun gnus-score-add-followups (header score scores &optional thread)
1902   "Add a score entry to the adapt file."
1903   (save-excursion
1904     (set-buffer gnus-summary-buffer)
1905     (let* ((id (mail-header-id header))
1906            (scores (car scores))
1907            entry dont)
1908       ;; Don't enter a score if there already is one.
1909       (while (setq entry (pop scores))
1910         (and (equal "references" (car entry))
1911              (or (null (nth 3 (cadr entry)))
1912                  (eq 's (nth 3 (cadr entry))))
1913              (assoc id entry)
1914              (setq dont t)))
1915       (unless dont
1916         (gnus-summary-score-entry
1917          (if thread "thread" "references")
1918          id 's score (current-time-string) nil t)))))
1919
1920 (defun gnus-score-string (score-list header now expire &optional trace)
1921   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1922   ;; Update matching entries to NOW and remove unmatched entries older
1923   ;; than EXPIRE.
1924
1925   ;; Insert the unique article headers in the buffer.
1926   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1927         ;; gnus-score-index is used as a free variable.
1928         (simplify (and gnus-score-thread-simplify
1929                        (string= "subject" header)))
1930         alike last this art entries alist articles
1931         fuzzies arts words kill)
1932
1933     ;; Sorting the articles costs os O(N*log N) but will allow us to
1934     ;; only match with each unique header.  Thus the actual matching
1935     ;; will be O(M*U) where M is the number of strings to match with,
1936     ;; and U is the number of unique headers.  It is assumed (but
1937     ;; untested) this will be a net win because of the large constant
1938     ;; factor involved with string matching.
1939     (setq gnus-scores-articles
1940           ;; We cannot string-sort the extra headers list.  *sigh*
1941           (if (= gnus-score-index 9)
1942               gnus-scores-articles
1943             (sort gnus-scores-articles 'gnus-score-string<))
1944           articles gnus-scores-articles)
1945
1946     (erase-buffer)
1947     (while (setq art (pop articles))
1948       (setq this (aref (car art) gnus-score-index))
1949
1950       ;; If we're working with non-standard headers, we are stuck
1951       ;; with working on them as a group.  What a hassle.
1952       ;; Just wait 'til you see what horrors we commit against `match'...
1953       (if (= gnus-score-index 9)
1954           (setq this (gnus-prin1-to-string this))) ; ick.
1955
1956       (if simplify
1957           (setq this (gnus-map-function gnus-simplify-subject-functions this)))
1958       (if (equal last this)
1959           ;; O(N*H) cons-cells used here, where H is the number of
1960           ;; headers.
1961           (push art alike)
1962         (when last
1963           ;; Insert the line, with a text property on the
1964           ;; terminating newline referring to the articles with
1965           ;; this line.
1966           (insert last ?\n)
1967           (put-text-property (1- (point)) (point) 'articles alike))
1968         (setq alike (list art)
1969               last this)))
1970     (when last                          ; Bwadr, duplicate code.
1971       (insert last ?\n)
1972       (put-text-property (1- (point)) (point) 'articles alike))
1973
1974     ;; Go through all the score alists and pick out the entries
1975     ;; for this header.
1976     (while score-list
1977       (setq alist (pop score-list)
1978             ;; There's only one instance of this header for
1979             ;; each score alist.
1980             entries (assoc header alist))
1981       (while (cdr entries)              ;First entry is the header index.
1982         (let* ((kill (cadr entries))
1983                (type (or (nth 3 kill) 's))
1984                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1985                (date (nth 2 kill))
1986                (extra (nth 4 kill))     ; non-standard header; string.
1987                (found nil)
1988                (mt (aref (symbol-name type) 0))
1989                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
1990                (dmt (downcase mt))
1991                ;; Assume user already simplified regexp and fuzzies
1992                (match (if (and simplify (not (memq dmt '(?f ?r))))
1993                           (gnus-map-function
1994                            gnus-simplify-subject-functions
1995                            (nth 0 kill))
1996                         (nth 0 kill)))
1997                (search-func
1998                 (cond ((= dmt ?r) 're-search-forward)
1999                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
2000                       ((= dmt ?w) nil)
2001                       (t (error "Invalid match type: %s" type)))))
2002
2003           ;; Evil hackery to make match usable in non-standard headers.
2004           (when extra
2005             (setq match (concat "[ (](" extra " \\. \"[^)]*"
2006                                 match "[^\"]*\")[ )]")
2007                   search-func 're-search-forward)) ; XXX danger?!?
2008
2009           (cond
2010            ;; Fuzzy matches.  We save these for later.
2011            ((= dmt ?f)
2012             (push (cons entries alist) fuzzies)
2013             (setq entries (cdr entries)))
2014            ;; Word matches.  Save these for even later.
2015            ((= dmt ?w)
2016             (push (cons entries alist) words)
2017             (setq entries (cdr entries)))
2018            ;; Exact matches.
2019            ((= dmt ?e)
2020             ;; Do exact matching.
2021             (goto-char (point-min))
2022             (while (and (not (eobp))
2023                         (funcall search-func match nil t))
2024               ;; Is it really exact?
2025               (and (eolp)
2026                    (= (point-at-bol) (match-beginning 0))
2027                    ;; Yup.
2028                    (progn
2029                      (setq found (setq arts (get-text-property
2030                                              (point) 'articles)))
2031                      ;; Found a match, update scores.
2032                      (if trace
2033                          (while (setq art (pop arts))
2034                            (setcdr art (+ score (cdr art)))
2035                            (push
2036                             (cons
2037                              (car-safe (rassq alist gnus-score-cache))
2038                              kill)
2039                             gnus-score-trace))
2040                        (while (setq art (pop arts))
2041                          (setcdr art (+ score (cdr art)))))))
2042               (forward-line 1))
2043             ;; Update expiry date
2044             (if trace
2045                 (setq entries (cdr entries))
2046               (cond
2047                ;; Permanent entry.
2048                ((null date)
2049                 (setq entries (cdr entries)))
2050                ;; We have a match, so we update the date.
2051                ((and found gnus-update-score-entry-dates)
2052                 (gnus-score-set 'touched '(t) alist)
2053                 (setcar (nthcdr 2 kill) now)
2054                 (setq entries (cdr entries)))
2055                ;; This entry has expired, so we remove it.
2056                ((and expire (< date expire))
2057                 (gnus-score-set 'touched '(t) alist)
2058                 (setcdr entries (cddr entries)))
2059                ;; No match; go to next entry.
2060                (t
2061                 (setq entries (cdr entries))))))
2062            ;; Regexp and substring matching.
2063            (t
2064             (goto-char (point-min))
2065             (when (string= match "")
2066               (setq match "\n"))
2067             (while (and (not (eobp))
2068                         (funcall search-func match nil t))
2069               (goto-char (match-beginning 0))
2070               (end-of-line)
2071               (setq found (setq arts (get-text-property (point) 'articles)))
2072               ;; Found a match, update scores.
2073               (if trace
2074                   (while (setq art (pop arts))
2075                     (setcdr art (+ score (cdr art)))
2076                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
2077                           gnus-score-trace))
2078                 (while (setq art (pop arts))
2079                   (setcdr art (+ score (cdr art)))))
2080               (forward-line 1))
2081             ;; Update expiry date
2082             (if trace
2083                 (setq entries (cdr entries))
2084               (cond
2085                ;; Permanent entry.
2086                ((null date)
2087                 (setq entries (cdr entries)))
2088                ;; We have a match, so we update the date.
2089                ((and found gnus-update-score-entry-dates)
2090                 (gnus-score-set 'touched '(t) alist)
2091                 (setcar (nthcdr 2 kill) now)
2092                 (setq entries (cdr entries)))
2093                ;; This entry has expired, so we remove it.
2094                ((and expire (< date expire))
2095                 (gnus-score-set 'touched '(t) alist)
2096                 (setcdr entries (cddr entries)))
2097                ;; No match; go to next entry.
2098                (t
2099                 (setq entries (cdr entries))))))))))
2100
2101     ;; Find fuzzy matches.
2102     (when fuzzies
2103       ;; Simplify the entire buffer for easy matching.
2104       (gnus-simplify-buffer-fuzzy)
2105       (while (setq kill (cadaar fuzzies))
2106         (let* ((match (nth 0 kill))
2107                (type (nth 3 kill))
2108                (score (or (nth 1 kill) gnus-score-interactive-default-score))
2109                (date (nth 2 kill))
2110                (mt (aref (symbol-name type) 0))
2111                (case-fold-search (not (= mt ?F)))
2112                found)
2113           (goto-char (point-min))
2114           (while (and (not (eobp))
2115                       (search-forward match nil t))
2116             (when (and (= (point-at-bol) (match-beginning 0))
2117                        (eolp))
2118               (setq found (setq arts (get-text-property (point) 'articles)))
2119               (if trace
2120                   (while (setq art (pop arts))
2121                     (setcdr art (+ score (cdr art)))
2122                     (push (cons
2123                            (car-safe (rassq (cdar fuzzies) gnus-score-cache))
2124                            kill)
2125                           gnus-score-trace))
2126                 ;; Found a match, update scores.
2127                 (while (setq art (pop arts))
2128                   (setcdr art (+ score (cdr art))))))
2129             (forward-line 1))
2130           ;; Update expiry date
2131           (if (not trace)
2132               (cond
2133                ;; Permanent.
2134                ((null date)
2135                 ;; Do nothing.
2136                 )
2137                ;; Match, update date.
2138                ((and found gnus-update-score-entry-dates)
2139                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2140                 (setcar (nthcdr 2 kill) now))
2141                ;; Old entry, remove.
2142                ((and expire (< date expire))
2143                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2144                 (setcdr (caar fuzzies) (cddaar fuzzies)))))
2145           (setq fuzzies (cdr fuzzies)))))
2146
2147     (when words
2148       ;; Enter all words into the hashtb.
2149       (let ((hashtb (gnus-make-hashtable
2150                      (* 10 (count-lines (point-min) (point-max))))))
2151         (gnus-enter-score-words-into-hashtb hashtb)
2152         (while (setq kill (cadaar words))
2153           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
2154                  (date (nth 2 kill))
2155                  found)
2156             (when (setq arts (intern-soft (nth 0 kill) hashtb))
2157               (setq arts (symbol-value arts))
2158               (setq found t)
2159               (if trace
2160                   (while (setq art (pop arts))
2161                     (setcdr art (+ score (cdr art)))
2162                     (push (cons
2163                            (car-safe (rassq (cdar words) gnus-score-cache))
2164                            kill)
2165                           gnus-score-trace))
2166                 ;; Found a match, update scores.
2167                 (while (setq art (pop arts))
2168                   (setcdr art (+ score (cdr art))))))
2169             ;; Update expiry date
2170             (if (not trace)
2171                 (cond
2172                  ;; Permanent.
2173                  ((null date)
2174                   ;; Do nothing.
2175                   )
2176                  ;; Match, update date.
2177                  ((and found gnus-update-score-entry-dates)
2178                   (gnus-score-set 'touched '(t) (cdar words))
2179                   (setcar (nthcdr 2 kill) now))
2180                  ;; Old entry, remove.
2181                  ((and expire (< date expire))
2182                   (gnus-score-set 'touched '(t) (cdar words))
2183                   (setcdr (caar words) (cddaar words)))))
2184             (setq words (cdr words))))))
2185     nil))
2186
2187 (defun gnus-enter-score-words-into-hashtb (hashtb)
2188   ;; Find all the words in the buffer and enter them into
2189   ;; the hashtable.
2190   (let (word val)
2191     (goto-char (point-min))
2192     (with-syntax-table gnus-adaptive-word-syntax-table
2193       (while (re-search-forward "\\b\\w+\\b" nil t)
2194         (setq val
2195               (gnus-gethash
2196                (setq word (downcase (buffer-substring
2197                                      (match-beginning 0) (match-end 0))))
2198                hashtb))
2199         (gnus-sethash
2200          word
2201          (append (get-text-property (point-at-eol) 'articles) val)
2202          hashtb)))
2203     ;; Make all the ignorable words ignored.
2204     (let ((ignored (append gnus-ignored-adaptive-words
2205                            (if gnus-adaptive-word-no-group-words
2206                                (message-tokenize-header
2207                                 (gnus-group-real-name gnus-newsgroup-name)
2208                                 "."))
2209                            gnus-default-ignored-adaptive-words)))
2210       (while ignored
2211         (gnus-sethash (pop ignored) nil hashtb)))))
2212
2213 (defun gnus-score-string< (a1 a2)
2214   ;; Compare headers in articles A2 and A2.
2215   ;; The header index used is the free variable `gnus-score-index'.
2216   (string-lessp (aref (car a1) gnus-score-index)
2217                 (aref (car a2) gnus-score-index)))
2218
2219 (defun gnus-current-score-file-nondirectory (&optional score-file)
2220   (let ((score-file (or score-file gnus-current-score-file)))
2221     (if score-file
2222         (gnus-short-group-name (file-name-nondirectory score-file))
2223       "none")))
2224
2225 (defun gnus-score-adaptive ()
2226   "Create adaptive score rules for this newsgroup."
2227   (when gnus-newsgroup-adaptive
2228     ;; We change the score file to the adaptive score file.
2229     (save-excursion
2230       (set-buffer gnus-summary-buffer)
2231       (gnus-score-load-file
2232        (or gnus-newsgroup-adaptive-score-file
2233            (gnus-home-score-file gnus-newsgroup-name t)
2234            (gnus-score-file-name
2235             gnus-newsgroup-name gnus-adaptive-file-suffix))))
2236     ;; Perform ordinary line scoring.
2237     (when (or (not (listp gnus-newsgroup-adaptive))
2238               (memq 'line gnus-newsgroup-adaptive))
2239       (save-excursion
2240         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
2241                (alist malist)
2242                (date (current-time-string))
2243                (data gnus-newsgroup-data)
2244                elem headers match func)
2245           ;; First we transform the adaptive rule alist into something
2246           ;; that's faster to process.
2247           (while malist
2248             (setq elem (car malist))
2249             (when (symbolp (car elem))
2250               (setcar elem (symbol-value (car elem))))
2251             (setq elem (cdr elem))
2252             (while elem
2253               (when (fboundp
2254                      (setq func
2255                            (intern
2256                             (concat "mail-header-"
2257                                     (if (eq (caar elem) 'followup)
2258                                         "message-id"
2259                                       (downcase (symbol-name (caar elem))))))))
2260                 (setcdr (car elem)
2261                         (cons (if (eq (caar elem) 'followup)
2262                                   "references"
2263                                 (symbol-name (caar elem)))
2264                               (cdar elem)))
2265                 (setcar (car elem)
2266                         `(lambda (h)
2267                            (,func h))))
2268               (setq elem (cdr elem)))
2269             (setq malist (cdr malist)))
2270           ;; Then we score away.
2271           (while data
2272             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2273             (if (or (not elem)
2274                     (gnus-data-pseudo-p (car data)))
2275                 ()
2276               (when (setq headers (gnus-data-header (car data)))
2277                 (while elem
2278                   (setq match (funcall (caar elem) headers))
2279                   (gnus-summary-score-entry
2280                    (nth 1 (car elem)) match
2281                    (cond
2282                     ((numberp match)
2283                      '=)
2284                     ((equal (nth 1 (car elem)) "date")
2285                      'a)
2286                     (t
2287                      ;; Whether we use substring or exact matches is
2288                      ;; controlled here.
2289                      (if (or (not gnus-score-exact-adapt-limit)
2290                              (< (length match) gnus-score-exact-adapt-limit))
2291                          'e
2292                        (if (equal (nth 1 (car elem)) "subject")
2293                            'f 's))))
2294                    (nth 2 (car elem)) date nil t)
2295                   (setq elem (cdr elem)))))
2296             (setq data (cdr data))))))
2297
2298     ;; Perform adaptive word scoring.
2299     (when (and (listp gnus-newsgroup-adaptive)
2300                (memq 'word gnus-newsgroup-adaptive))
2301       (with-temp-buffer
2302         (let* ((hashtb (gnus-make-hashtable 1000))
2303                (date (date-to-day (current-time-string)))
2304                (data gnus-newsgroup-data)
2305                word d score val)
2306           (with-syntax-table gnus-adaptive-word-syntax-table
2307             ;; Go through all articles.
2308             (while (setq d (pop data))
2309               (when (and
2310                      (not (gnus-data-pseudo-p d))
2311                      (setq score
2312                            (cdr (assq
2313                                  (gnus-data-mark d)
2314                                  gnus-adaptive-word-score-alist))))
2315                 ;; This article has a mark that should lead to
2316                 ;; adaptive word rules, so we insert the subject
2317                 ;; and find all words in that string.
2318                 (insert (mail-header-subject (gnus-data-header d)))
2319                 (downcase-region (point-min) (point-max))
2320                 (goto-char (point-min))
2321                 (while (re-search-forward "\\b\\w+\\b" nil t)
2322                   ;; Put the word and score into the hashtb.
2323                   (setq val (gnus-gethash (setq word (match-string 0))
2324                                           hashtb))
2325                   (when (or (not gnus-adaptive-word-length-limit)
2326                             (> (length word)
2327                                gnus-adaptive-word-length-limit))
2328                     (setq val (+ score (or val 0)))
2329                     (if (and gnus-adaptive-word-minimum
2330                              (< val gnus-adaptive-word-minimum))
2331                         (setq val gnus-adaptive-word-minimum))
2332                     (gnus-sethash word val hashtb)))
2333                 (erase-buffer))))
2334           ;; Make all the ignorable words ignored.
2335           (let ((ignored (append gnus-ignored-adaptive-words
2336                                  (if gnus-adaptive-word-no-group-words
2337                                      (message-tokenize-header
2338                                       (gnus-group-real-name
2339                                        gnus-newsgroup-name)
2340                                       "."))
2341                                  gnus-default-ignored-adaptive-words)))
2342             (while ignored
2343               (gnus-sethash (pop ignored) nil hashtb)))
2344           ;; Now we have all the words and scores, so we
2345           ;; add these rules to the ADAPT file.
2346           (set-buffer gnus-summary-buffer)
2347           (mapatoms
2348            (lambda (word)
2349              (when (symbol-value word)
2350                (gnus-summary-score-entry
2351                 "subject" (symbol-name word) 'w (symbol-value word)
2352                 date nil t)))
2353            hashtb))))))
2354
2355 (defun gnus-score-edit-done ()
2356   (let ((bufnam (buffer-file-name (current-buffer)))
2357         (winconf gnus-prev-winconf))
2358     (when winconf
2359       (set-window-configuration winconf))
2360     (gnus-score-remove-from-cache bufnam)
2361     (gnus-score-load-file bufnam)))
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
2769        (lambda (f) (cdr f))
2770        (sort alist 'car-less-than-car)))))
2771
2772 (defun gnus-score-find-alist (group)
2773   "Return list of score files for GROUP.
2774 The list is determined from the variable `gnus-score-file-alist'."
2775   (let ((alist gnus-score-file-multiple-match-alist)
2776         score-files)
2777     ;; if this group has been seen before, return the cached entry
2778     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2779         (cdr score-files)               ;ensures caching groups with no matches
2780       ;; handle the multiple match alist
2781       (while alist
2782         (when (string-match (caar alist) group)
2783           (setq score-files
2784                 (nconc score-files (copy-sequence (cdar alist)))))
2785         (setq alist (cdr alist)))
2786       (setq alist gnus-score-file-single-match-alist)
2787       ;; handle the single match alist
2788       (while alist
2789         (when (string-match (caar alist) group)
2790           ;; progn used just in case ("regexp") has no files
2791           ;; and score-files is still nil.  -sj
2792           ;; this can be construed as a "stop searching here" feature :>
2793           ;; and used to simplify regexps in the single-alist
2794           (setq score-files
2795                 (nconc score-files (copy-sequence (cdar alist))))
2796           (setq alist nil))
2797         (setq alist (cdr alist)))
2798       ;; cache the score files
2799       (push (cons group score-files) gnus-score-file-alist-cache)
2800       score-files)))
2801
2802 (defun gnus-all-score-files (&optional group)
2803   "Return a list of all score files for the current group."
2804   (let ((funcs gnus-score-find-score-files-function)
2805         (group (or group gnus-newsgroup-name))
2806         score-files)
2807     (when group
2808       ;; Make sure funcs is a list.
2809       (and funcs
2810            (not (listp funcs))
2811            (setq funcs (list funcs)))
2812       (when gnus-score-use-all-scores
2813         ;; Get the initial score files for this group.
2814         (when funcs
2815           (setq score-files (nreverse (gnus-score-find-alist group))))
2816         ;; Add any home adapt files.
2817         (let ((home (gnus-home-score-file group t)))
2818           (when home
2819             (push home score-files)
2820             (setq gnus-newsgroup-adaptive-score-file home)))
2821         ;; Check whether there is a `adapt-file' group parameter.
2822         (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2823           (when param-file
2824             (push param-file score-files)
2825             (setq gnus-newsgroup-adaptive-score-file param-file))))
2826       ;; Go through all the functions for finding score files (or actual
2827       ;; scores) and add them to a list.
2828       (while funcs
2829         (when (functionp (car funcs))
2830           (setq score-files
2831                 (append score-files
2832                         (nreverse (funcall (car funcs) group)))))
2833         (setq funcs (cdr funcs)))
2834       (when gnus-score-use-all-scores
2835         ;; Add any home score files.
2836         (let ((home (gnus-home-score-file group)))
2837           (when home
2838             (push home score-files)))
2839         ;; Check whether there is a `score-file' group parameter.
2840         (let ((param-file (gnus-group-find-parameter group 'score-file)))
2841           (when param-file
2842             (push param-file score-files))))
2843       ;; Expand all files names.
2844       (let ((files score-files))
2845         (while files
2846           (when (stringp (car files))
2847             (setcar files (expand-file-name
2848                            (car files) gnus-kill-files-directory)))
2849           (pop files)))
2850       (setq score-files (nreverse score-files))
2851       ;; Remove any duplicate score files.
2852       (while (and score-files
2853                   (member (car score-files) (cdr score-files)))
2854         (pop score-files))
2855       (let ((files score-files))
2856         (while (cdr files)
2857           (if (member (cadr files) (cddr files))
2858               (setcdr files (cddr files))
2859             (pop files))))
2860       ;; Do the scoring if there are any score files for this group.
2861       score-files)))
2862
2863 (defun gnus-possibly-score-headers (&optional trace)
2864   "Do scoring if scoring is required."
2865   (let ((score-files (gnus-all-score-files)))
2866     (when score-files
2867       (gnus-score-headers score-files trace))))
2868
2869 (defun gnus-score-file-name (newsgroup &optional suffix)
2870   "Return the name of a score file for NEWSGROUP."
2871   (let ((suffix (or suffix gnus-score-file-suffix)))
2872     (nnheader-translate-file-chars
2873      (cond
2874       ((or (null newsgroup)
2875            (string-equal newsgroup ""))
2876        ;; The global score file is placed at top of the directory.
2877        (expand-file-name suffix gnus-kill-files-directory))
2878       ((gnus-use-long-file-name 'not-score)
2879        ;; Append ".SCORE" to newsgroup name.
2880        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2881                                  "." suffix)
2882                          gnus-kill-files-directory))
2883       (t
2884        ;; Place "SCORE" under the hierarchical directory.
2885        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2886                                  "/" suffix)
2887                          gnus-kill-files-directory))))))
2888
2889 (defun gnus-score-search-global-directories (files)
2890   "Scan all global score directories for score files."
2891   ;; Set the variable `gnus-internal-global-score-files' to all
2892   ;; available global score files.
2893   (interactive (list gnus-global-score-files))
2894   (let (out)
2895     (while files
2896       ;; #### /$ Unix-specific?
2897       (if (file-directory-p (car files))
2898           (setq out (nconc (directory-files
2899                             (car files) t
2900                             (concat (gnus-score-file-regexp) "$"))))
2901         (push (car files) out))
2902       (setq files (cdr files)))
2903     (setq gnus-internal-global-score-files out)))
2904
2905 (defun gnus-score-default-fold-toggle ()
2906   "Toggle folding for new score file entries."
2907   (interactive)
2908   (setq gnus-score-default-fold (not gnus-score-default-fold))
2909   (if gnus-score-default-fold
2910       (gnus-message 1 "New score file entries will be case insensitive.")
2911     (gnus-message 1 "New score file entries will be case sensitive.")))
2912
2913 ;;; Home score file.
2914
2915 (defun gnus-home-score-file (group &optional adapt)
2916   "Return the home score file for GROUP.
2917 If ADAPT, return the home adaptive file instead."
2918   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2919         elem found)
2920     ;; Make sure we have a list.
2921     (unless (listp list)
2922       (setq list (list list)))
2923     ;; Go through the list and look for matches.
2924     (while (and (not found)
2925                 (setq elem (pop list)))
2926       (setq found
2927             (cond
2928              ;; Simple string.
2929              ((stringp elem)
2930               elem)
2931              ;; Function.
2932              ((functionp elem)
2933               (funcall elem group))
2934              ;; Regexp-file cons.
2935              ((consp elem)
2936               (when (string-match (gnus-globalify-regexp (car elem)) group)
2937                 (replace-match (cadr elem) t nil group))))))
2938     (when found
2939       (setq found (nnheader-translate-file-chars found))
2940       (if (file-name-absolute-p found)
2941           found
2942         (nnheader-concat gnus-kill-files-directory found)))))
2943
2944 (defun gnus-hierarchial-home-score-file (group)
2945   "Return the score file of the top-level hierarchy of GROUP."
2946   (if (string-match "^[^.]+\\." group)
2947       (concat (match-string 0 group) gnus-score-file-suffix)
2948     ;; Group name without any dots.
2949     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2950             gnus-score-file-suffix)))
2951
2952 (defun gnus-hierarchial-home-adapt-file (group)
2953   "Return the adapt file of the top-level hierarchy of GROUP."
2954   (if (string-match "^[^.]+\\." group)
2955       (concat (match-string 0 group) gnus-adaptive-file-suffix)
2956     ;; Group name without any dots.
2957     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2958             gnus-adaptive-file-suffix)))
2959
2960 (defun gnus-current-home-score-file (group)
2961   "Return the \"current\" regular score file."
2962   (car (nreverse (gnus-score-find-alist group))))
2963
2964 ;;;
2965 ;;; Score decays
2966 ;;;
2967
2968 (defun gnus-decay-score (score)
2969   "Decay SCORE according to `gnus-score-decay-constant' and `gnus-score-decay-scale'."
2970   (let ((n (- score
2971               (* (if (< score 0) -1 1)
2972                  (min (abs score)
2973                       (max gnus-score-decay-constant
2974                            (* (abs score)
2975                               gnus-score-decay-scale)))))))
2976     (if (and (featurep 'xemacs)
2977              ;; XEmacs' floor can handle only the floating point
2978              ;; number below the half of the maximum integer.
2979              (> (abs n) (lsh -1 -2)))
2980         (string-to-number
2981          (car (split-string (number-to-string n) "\\.")))
2982       (floor n))))
2983
2984 (defun gnus-decay-scores (alist day)
2985   "Decay non-permanent scores in ALIST."
2986   (let ((times (- (time-to-days (current-time)) day))
2987         kill entry updated score n)
2988     (unless (zerop times)               ;Done decays today already?
2989       (while (setq entry (pop alist))
2990         (when (stringp (car entry))
2991           (setq entry (cdr entry))
2992           (while (setq kill (pop entry))
2993             (when (nth 2 kill)
2994               (setq updated t)
2995               (setq score (or (nth 1 kill)
2996                               gnus-score-interactive-default-score)
2997                     n times)
2998               (while (natnump (decf n))
2999                 (setq score (funcall gnus-decay-score-function score)))
3000               (setcdr kill (cons score
3001                                  (cdr (cdr kill)))))))))
3002     ;; Return whether this score file needs to be saved.  By Je-haysuss!
3003     updated))
3004
3005 (defun gnus-score-regexp-bad-p (regexp)
3006   "Test whether REGEXP is safe for Gnus scoring.
3007 A regexp is unsafe if it matches newline or a buffer boundary.
3008
3009 If the regexp is good, return nil.  If the regexp is bad, return a
3010 cons cell (SYM . STRING), where the symbol SYM is `new' or `bad'.
3011 In the `new' case, the string is a safe replacement for REGEXP.
3012 In the `bad' case, the string is a unsafe subexpression of REGEXP,
3013 and we do not have a simple replacement to suggest.
3014
3015 See Info node `(gnus)Scoring Tips' for examples of good regular expressions."
3016   (let (case-fold-search)
3017     (and
3018      ;; First, try a relatively fast necessary condition.
3019      ;; Notice ranges (like [^:] or [\t-\r]), \s>, \Sw, \W, \', \`:
3020      (string-match "\n\\|\\\\[SsW`']\\|\\[\\^\\|[\0-\n]-" regexp)
3021      ;; Now break the regexp into tokens, and check each:
3022      (let ((tail regexp)                ; remaining regexp to check
3023            tok                          ; current token
3024            bad                          ; nil, or bad subexpression
3025            new                          ; nil, or replacement regexp so far
3026            end)                         ; length of current token
3027        (while (and (not bad)
3028                    (string-match
3029                     "\\`\\(\\\\[sS]?.\\|\\[\\^?]?[^]]*]\\|[^\\]\\)"
3030                     tail))
3031          (setq end (match-end 0)
3032                tok (substring tail 0 end)
3033                tail (substring tail end))
3034          (if;; Is token `bad' (matching newline or buffer ends)?
3035              (or (member tok '("\n" "\\W" "\\`" "\\'"))
3036                  ;; This next handles "[...]", "\\s.", and "\\S.":
3037                  (and (> end 2) (string-match tok "\n")))
3038              (let ((newtok
3039                     ;; Try to suggest a replacement for tok ...
3040                     (cond ((string-equal tok "\\`") "^") ; or "\\(^\\)"
3041                           ((string-equal tok "\\'") "$") ; or "\\($\\)"
3042                           ((string-match "\\[\\^" tok) ; very common
3043                            (concat (substring tok 0 -1) "\n]")))))
3044                (if newtok
3045                    (setq new
3046                          (concat
3047                           (or new
3048                               ;; good prefix so far:
3049                               (substring regexp 0 (- (+ (length tail) end))))
3050                           newtok))
3051                  ;; No replacement idea, so give up:
3052                  (setq bad tok)))
3053            ;; tok is good, may need to extend new
3054            (and new (setq new (concat new tok)))))
3055        ;; Now return a value:
3056        (cond
3057         (bad (cons 'bad bad))
3058         (new (cons 'new new))
3059         (t nil))))))
3060
3061 (provide 'gnus-score)
3062
3063 ;;; gnus-score.el ends here