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