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