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