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