* gnus-score.el (gnus-score-find-trace): Added comment on sync
[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
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-file (file)
1092   "Edit a score file."
1093   (interactive
1094    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
1095   (gnus-make-directory (file-name-directory file))
1096   (when (buffer-name gnus-summary-buffer)
1097     (gnus-score-save))
1098   (let ((winconf (current-window-configuration)))
1099     (setq gnus-score-edit-buffer (find-file-noselect file))
1100     (gnus-configure-windows 'edit-score)
1101     (gnus-score-mode)
1102     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1103     (make-local-variable 'gnus-prev-winconf)
1104     (setq gnus-prev-winconf winconf))
1105   (gnus-message
1106    4 (substitute-command-keys
1107       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
1108
1109 (defun gnus-score-edit-file-at-point (&optional format)
1110   "Edit score file at point in Score Trace buffers.
1111 If FORMAT, also format the current score file."
1112   (let* ((rule (save-excursion
1113                  (beginning-of-line)
1114                  (read (current-buffer))))
1115          (sep "[ \n\r\t]*")
1116          ;; Must be synced with `gnus-score-find-trace':
1117          (reg " -> +")
1118          (file (save-excursion
1119                  (end-of-line)
1120                  (if (and (re-search-backward reg (gnus-point-at-bol) t)
1121                           (re-search-forward  reg (gnus-point-at-eol) t))
1122                      (buffer-substring (point) (gnus-point-at-eol))
1123                    nil))))
1124     (if (or (not file)
1125             (string-match "\\<\\(non-file rule\\|A file\\)\\>" file)
1126             ;; (see `gnus-score-find-trace' and `gnus-score-advanced')
1127             (string= "" file))
1128         (gnus-error 3 "Can't find a score file in current line.")
1129       (gnus-score-edit-file file)
1130       (when format
1131         (gnus-score-pretty-print))
1132       (when (consp rule) ;; the rule exists
1133         (setq rule (mapconcat #'(lambda (obj)
1134                                   (regexp-quote (format "%S" obj)))
1135                               rule
1136                               sep))
1137         (goto-char (point-min))
1138         (re-search-forward rule nil t)
1139         ;; make it easy to use `kill-sexp':
1140         (goto-char (1- (match-beginning 0)))))))
1141
1142 (defun gnus-score-load-file (file)
1143   ;; Load score file FILE.  Returns a list a retrieved score-alists.
1144   (let* ((file (expand-file-name
1145                 (or (and (string-match
1146                           (concat "^" (regexp-quote
1147                                        (expand-file-name
1148                                         gnus-kill-files-directory)))
1149                           (expand-file-name file))
1150                          file)
1151                     (expand-file-name file gnus-kill-files-directory))))
1152          (cached (assoc file gnus-score-cache))
1153          (global (member file gnus-internal-global-score-files))
1154          lists alist)
1155     (if cached
1156         ;; The score file was already loaded.
1157         (setq alist (cdr cached))
1158       ;; We load the score file.
1159       (setq gnus-score-alist nil)
1160       (setq alist (gnus-score-load-score-alist file))
1161       ;; We add '(touched) to the alist to signify that it hasn't been
1162       ;; touched (yet).
1163       (unless (assq 'touched alist)
1164         (push (list 'touched nil) alist))
1165       ;; If it is a global score file, we make it read-only.
1166       (and global
1167            (not (assq 'read-only alist))
1168            (push (list 'read-only t) alist))
1169       (push (cons file alist) gnus-score-cache))
1170     (let ((a alist)
1171           found)
1172       (while a
1173         ;; Downcase all header names.
1174         (cond
1175          ((stringp (caar a))
1176           (setcar (car a) (downcase (caar a)))
1177           (setq found t))
1178          ;; Advanced scoring.
1179          ((consp (caar a))
1180           (setq found t)))
1181         (pop a))
1182       ;; If there are actual scores in the alist, we add it to the
1183       ;; return value of this function.
1184       (when found
1185         (setq lists (list alist))))
1186     ;; Treat the other possible atoms in the score alist.
1187     (let ((mark (car (gnus-score-get 'mark alist)))
1188           (expunge (car (gnus-score-get 'expunge alist)))
1189           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
1190           (files (gnus-score-get 'files alist))
1191           (exclude-files (gnus-score-get 'exclude-files alist))
1192           (orphan (car (gnus-score-get 'orphan alist)))
1193           (adapt (gnus-score-get 'adapt alist))
1194           (thread-mark-and-expunge
1195            (car (gnus-score-get 'thread-mark-and-expunge alist)))
1196           (adapt-file (car (gnus-score-get 'adapt-file alist)))
1197           (local (gnus-score-get 'local alist))
1198           (decay (car (gnus-score-get 'decay alist)))
1199           (eval (car (gnus-score-get 'eval alist))))
1200       ;; Perform possible decays.
1201       (when (and gnus-decay-scores
1202                  (or cached (file-exists-p file))
1203                  (or (not decay)
1204                      (gnus-decay-scores alist decay)))
1205         (gnus-score-set 'touched '(t) alist)
1206         (gnus-score-set 'decay (list (time-to-days (current-time))) alist))
1207       ;; We do not respect eval and files atoms from global score
1208       ;; files.
1209       (when (and files (not global))
1210         (setq lists (apply 'append lists
1211                            (mapcar (lambda (file)
1212                                      (gnus-score-load-file file))
1213                                    (if adapt-file (cons adapt-file files)
1214                                      files)))))
1215       (when (and eval (not global))
1216         (eval eval))
1217       ;; We then expand any exclude-file directives.
1218       (setq gnus-scores-exclude-files
1219             (nconc
1220              (apply
1221               'nconc
1222               (mapcar
1223                (lambda (sfile)
1224                  (list
1225                   (expand-file-name sfile (file-name-directory file))
1226                   (expand-file-name sfile gnus-kill-files-directory)))
1227                exclude-files))
1228              gnus-scores-exclude-files))
1229       (when local
1230         (save-excursion
1231           (set-buffer gnus-summary-buffer)
1232           (while local
1233             (and (consp (car local))
1234                  (symbolp (caar local))
1235                  (progn
1236                    (make-local-variable (caar local))
1237                    (set (caar local) (nth 1 (car local)))))
1238             (setq local (cdr local)))))
1239       (when orphan
1240         (setq gnus-orphan-score orphan))
1241       (setq gnus-adaptive-score-alist
1242             (cond ((equal adapt '(t))
1243                    (setq gnus-newsgroup-adaptive t)
1244                    gnus-default-adaptive-score-alist)
1245                   ((equal adapt '(ignore))
1246                    (setq gnus-newsgroup-adaptive nil))
1247                   ((consp adapt)
1248                    (setq gnus-newsgroup-adaptive t)
1249                    adapt)
1250                   (t
1251                    gnus-default-adaptive-score-alist)))
1252       (setq gnus-thread-expunge-below
1253             (or thread-mark-and-expunge gnus-thread-expunge-below))
1254       (setq gnus-summary-mark-below
1255             (or mark mark-and-expunge gnus-summary-mark-below))
1256       (setq gnus-summary-expunge-below
1257             (or expunge mark-and-expunge gnus-summary-expunge-below))
1258       (setq gnus-newsgroup-adaptive-score-file
1259             (or adapt-file gnus-newsgroup-adaptive-score-file)))
1260     (setq gnus-current-score-file file)
1261     (setq gnus-score-alist alist)
1262     lists))
1263
1264 (defun gnus-score-load (file)
1265   ;; Load score FILE.
1266   (let ((cache (assoc file gnus-score-cache)))
1267     (if cache
1268         (setq gnus-score-alist (cdr cache))
1269       (setq gnus-score-alist nil)
1270       (gnus-score-load-score-alist file)
1271       (unless gnus-score-alist
1272         (setq gnus-score-alist (copy-alist '((touched nil)))))
1273       (push (cons file gnus-score-alist) gnus-score-cache))))
1274
1275 (defun gnus-score-remove-from-cache (file)
1276   (setq gnus-score-cache
1277         (delq (assoc file gnus-score-cache) gnus-score-cache)))
1278
1279 (defun gnus-score-load-score-alist (file)
1280   "Read score FILE."
1281   (let (alist)
1282     (if (not (file-readable-p file))
1283         ;; Couldn't read file.
1284         (setq gnus-score-alist nil)
1285       ;; Read file.
1286       (with-temp-buffer
1287         (let ((coding-system-for-read score-mode-coding-system))
1288           (insert-file-contents file))
1289         (goto-char (point-min))
1290         ;; Only do the loading if the score file isn't empty.
1291         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
1292           (setq alist
1293                 (condition-case ()
1294                     (read (current-buffer))
1295                   (error
1296                    (gnus-error 3.2 "Problem with score file %s" file))))))
1297       (cond
1298        ((and alist
1299              (atom alist))
1300         ;; Bogus score file.
1301         (error "Invalid syntax with score file %s" file))
1302        ((eq (car alist) 'setq)
1303         ;; This is an old-style score file.
1304         (setq gnus-score-alist (gnus-score-transform-old-to-new alist)))
1305        (t
1306         (setq gnus-score-alist alist)))
1307       ;; Check the syntax of the score file.
1308       (setq gnus-score-alist
1309             (gnus-score-check-syntax gnus-score-alist file)))))
1310
1311 (defun gnus-score-check-syntax (alist file)
1312   "Check the syntax of the score ALIST."
1313   (cond
1314    ((null alist)
1315     nil)
1316    ((not (consp alist))
1317     (gnus-message 1 "Score file is not a list: %s" file)
1318     (ding)
1319     nil)
1320    (t
1321     (let ((a alist)
1322           sr err s type)
1323       (while (and a (not err))
1324         (setq
1325          err
1326          (cond
1327           ((not (listp (car a)))
1328            (format "Invalid score element %s in %s" (car a) file))
1329           ((stringp (caar a))
1330            (cond
1331             ((not (listp (setq sr (cdar a))))
1332              (format "Invalid header match %s in %s" (nth 1 (car a)) file))
1333             (t
1334              (setq type (caar a))
1335              (while (and sr (not err))
1336                (setq s (pop sr))
1337                (setq
1338                 err
1339                 (cond
1340                  ((if (member (downcase type) '("lines" "chars"))
1341                       (not (numberp (car s)))
1342                     (not (stringp (car s))))
1343                   (format "Invalid match %s in %s" (car s) file))
1344                  ((and (cadr s) (not (integerp (cadr s))))
1345                   (format "Non-integer score %s in %s" (cadr s) file))
1346                  ((and (caddr s) (not (integerp (caddr s))))
1347                   (format "Non-integer date %s in %s" (caddr s) file))
1348                  ((and (cadddr s) (not (symbolp (cadddr s))))
1349                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1350              err)))))
1351         (setq a (cdr a)))
1352       (if err
1353           (progn
1354             (ding)
1355             (gnus-message 3 err)
1356             (sit-for 2)
1357             nil)
1358         alist)))))
1359
1360 (defun gnus-score-transform-old-to-new (alist)
1361   (let* ((alist (nth 2 alist))
1362          out entry)
1363     (when (eq (car alist) 'quote)
1364       (setq alist (nth 1 alist)))
1365     (while alist
1366       (setq entry (car alist))
1367       (if (stringp (car entry))
1368           (let ((scor (cdr entry)))
1369             (push entry out)
1370             (while scor
1371               (setcar scor
1372                       (list (caar scor) (nth 2 (car scor))
1373                             (and (nth 3 (car scor))
1374                                  (date-to-day (nth 3 (car scor))))
1375                             (if (nth 1 (car scor)) 'r 's)))
1376               (setq scor (cdr scor))))
1377         (push (if (not (listp (cdr entry)))
1378                   (list (car entry) (cdr entry))
1379                 entry)
1380               out))
1381       (setq alist (cdr alist)))
1382     (cons (list 'touched t) (nreverse out))))
1383
1384 (defun gnus-score-save ()
1385   ;; Save all score information.
1386   (let ((cache gnus-score-cache)
1387         entry score file)
1388     (save-excursion
1389       (setq gnus-score-alist nil)
1390       (nnheader-set-temp-buffer " *Gnus Scores*")
1391       (while cache
1392         (current-buffer)
1393         (setq entry (pop cache)
1394               file (nnheader-translate-file-chars (car entry) t)
1395               score (cdr entry))
1396         (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1397                 (gnus-score-get 'read-only score)
1398                 (and (file-exists-p file)
1399                      (not (file-writable-p file))))
1400             ()
1401           (setq score (setcdr entry (gnus-delete-alist 'touched score)))
1402           (erase-buffer)
1403           (let (emacs-lisp-mode-hook)
1404             (if (string-match
1405                  (concat (regexp-quote gnus-adaptive-file-suffix) "$")
1406                  file)
1407                 ;; This is an adaptive score file, so we do not run
1408                 ;; it through `pp'.  These files can get huge, and
1409                 ;; are not meant to be edited by human hands.
1410                 (gnus-prin1 score)
1411               ;; This is a normal score file, so we print it very
1412               ;; prettily.
1413               (let ((lisp-mode-syntax-table score-mode-syntax-table))
1414                 (pp score (current-buffer)))))
1415           (gnus-make-directory (file-name-directory file))
1416           ;; If the score file is empty, we delete it.
1417           (if (zerop (buffer-size))
1418               (delete-file file)
1419             ;; There are scores, so we write the file.
1420             (when (file-writable-p file)
1421               (let ((coding-system-for-write score-mode-coding-system))
1422                 (gnus-write-buffer file))
1423               (when gnus-score-after-write-file-function
1424                 (funcall gnus-score-after-write-file-function file)))))
1425         (and gnus-score-uncacheable-files
1426              (string-match gnus-score-uncacheable-files file)
1427              (gnus-score-remove-from-cache file)))
1428       (kill-buffer (current-buffer)))))
1429
1430 (defun gnus-score-load-files (score-files)
1431   "Load all score files in SCORE-FILES."
1432   ;; Load the score files.
1433   (let (scores)
1434     (while score-files
1435       (if (stringp (car score-files))
1436           ;; It is a string, which means that it's a score file name,
1437           ;; so we load the score file and add the score alist to
1438           ;; the list of alists.
1439           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1440         ;; It is an alist, so we just add it to the list directly.
1441         (setq scores (nconc (car score-files) scores)))
1442       (setq score-files (cdr score-files)))
1443     ;; Prune the score files that are to be excluded, if any.
1444     (when gnus-scores-exclude-files
1445       (let ((s scores)
1446             c)
1447         (while s
1448           (and (setq c (rassq (car s) gnus-score-cache))
1449                (member (car c) gnus-scores-exclude-files)
1450                (setq scores (delq (car s) scores)))
1451           (setq s (cdr s)))))
1452     scores))
1453
1454 (defun gnus-score-headers (score-files &optional trace)
1455   ;; Score `gnus-newsgroup-headers'.
1456   (let (scores news)
1457     ;; PLM: probably this is not the best place to clear orphan-score
1458     (setq gnus-orphan-score nil
1459           gnus-scores-articles nil
1460           gnus-scores-exclude-files nil
1461           scores (gnus-score-load-files score-files))
1462     (setq news scores)
1463     ;; Do the scoring.
1464     (while news
1465       (setq scores news
1466             news nil)
1467       (when (and gnus-summary-default-score
1468                  scores)
1469         (let* ((entries gnus-header-index)
1470                (now (date-to-day (current-time-string)))
1471                (expire (and gnus-score-expiry-days
1472                             (- now gnus-score-expiry-days)))
1473                (headers gnus-newsgroup-headers)
1474                (current-score-file gnus-current-score-file)
1475                entry header new)
1476           (gnus-message 7 "Scoring...")
1477           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1478           (while (setq header (pop headers))
1479             ;; WARNING: The assq makes the function O(N*S) while it could
1480             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1481             ;; and S is (length gnus-newsgroup-scored).
1482             (unless (assq (mail-header-number header) gnus-newsgroup-scored)
1483               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1484                     (cons (cons header (or gnus-summary-default-score 0))
1485                           gnus-scores-articles))))
1486
1487           (save-excursion
1488             (set-buffer (gnus-get-buffer-create "*Headers*"))
1489             (buffer-disable-undo)
1490             (when (gnus-buffer-live-p gnus-summary-buffer)
1491               (message-clone-locals gnus-summary-buffer))
1492
1493             ;; Set the global variant of this variable.
1494             (setq gnus-current-score-file current-score-file)
1495             ;; score orphans
1496             (when gnus-orphan-score
1497               (setq gnus-score-index
1498                     (nth 1 (assoc "references" gnus-header-index)))
1499               (gnus-score-orphans gnus-orphan-score))
1500             ;; Run each header through the score process.
1501             (while entries
1502               (setq entry (pop entries)
1503                     header (nth 0 entry)
1504                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1505               (when (< 0 (apply 'max (mapcar
1506                                       (lambda (score)
1507                                         (length (gnus-score-get header score)))
1508                                       scores)))
1509                 ;; Call the scoring function for this type of "header".
1510                 (when (setq new (funcall (nth 2 entry) scores header
1511                                          now expire trace))
1512                   (push new news))))
1513             (when (gnus-buffer-live-p gnus-summary-buffer)
1514               (let ((scored gnus-newsgroup-scored))
1515                 (with-current-buffer gnus-summary-buffer
1516                   (setq gnus-newsgroup-scored scored))))
1517             ;; Remove the buffer.
1518             (gnus-kill-buffer (current-buffer)))
1519
1520           ;; Add articles to `gnus-newsgroup-scored'.
1521           (while gnus-scores-articles
1522             (when (or (/= gnus-summary-default-score
1523                           (cdar gnus-scores-articles))
1524                       gnus-save-score)
1525               (push (cons (mail-header-number (caar gnus-scores-articles))
1526                           (cdar gnus-scores-articles))
1527                     gnus-newsgroup-scored))
1528             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1529
1530           (let (score)
1531             (while (setq score (pop scores))
1532               (while score
1533                 (when (consp (caar score))
1534                   (gnus-score-advanced (car score) trace))
1535                 (pop score))))
1536
1537           (gnus-message 7 "Scoring...done"))))))
1538
1539 (defun gnus-score-lower-thread (thread score-adjust)
1540   "Lower the score on THREAD with SCORE-ADJUST.
1541 THREAD is expected to contain a list of the form `(PARENT [CHILD1
1542 CHILD2 ...])' where PARENT is a header array and each CHILD is a list
1543 of the same form as THREAD.  The empty list nil is valid.  For each
1544 article in the tree, the score of the corresponding entry in
1545 `gnus-newsgroup-scored' is adjusted by SCORE-ADJUST."
1546   (while thread
1547     (let ((head (car thread)))
1548       (if (listp head)
1549           ;; handle a child and its descendants
1550           (gnus-score-lower-thread head score-adjust)
1551         ;; handle the parent
1552         (let* ((article (mail-header-number head))
1553                (score (assq article gnus-newsgroup-scored)))
1554           (if score (setcdr score (+ (cdr score) score-adjust))
1555             (push (cons article score-adjust) gnus-newsgroup-scored)))))
1556     (setq thread (cdr thread))))
1557
1558 (defun gnus-score-orphans (score)
1559   "Score orphans.
1560 A root is an article with no references.  An orphan is an article
1561 which has references, but is not connected via its references to a
1562 root article.  This function finds all the orphans, and adjusts their
1563 score in `gnus-newsgroup-scored' by SCORE."
1564   ;; gnus-make-threads produces a list, where each entry is a "thread"
1565   ;; as described in the gnus-score-lower-thread docs.  This function
1566   ;; will be called again (after limiting has been done) if the display
1567   ;; is threaded.  It would be nice to somehow save this info and use
1568   ;; it later.
1569   (dolist (thread (gnus-make-threads))
1570     (let ((id (aref (car thread) gnus-score-index)))
1571       ;; If the parent of the thread is not a root, lower the score of
1572       ;; it and its descendants.  Note that some roots seem to satisfy
1573       ;; (eq id nil) and some (eq id "");  not sure why.
1574       (when (and id
1575                  (not (string= id "")))
1576         (gnus-score-lower-thread thread score)))))
1577
1578 (defun gnus-score-integer (scores header now expire &optional trace)
1579   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1580         entries alist)
1581     ;; Find matches.
1582     (while scores
1583       (setq alist (car scores)
1584             scores (cdr scores)
1585             entries (assoc header alist))
1586       (while (cdr entries)              ;First entry is the header index.
1587         (let* ((rest (cdr entries))
1588                (kill (car rest))
1589                (match (nth 0 kill))
1590                (type (or (nth 3 kill) '>))
1591                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1592                (date (nth 2 kill))
1593                (found nil)
1594                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1595                                    (eq type '>=) (eq type '=))
1596                                type
1597                              (error "Invalid match type: %s" type)))
1598                (articles gnus-scores-articles))
1599           ;; Instead of doing all the clever stuff that
1600           ;; `gnus-score-string' does to minimize searches and stuff,
1601           ;; I will assume that people generally will put so few
1602           ;; matches on numbers that any cleverness will take more
1603           ;; time than one would gain.
1604           (while articles
1605             (when (funcall match-func
1606                            (or (aref (caar articles) gnus-score-index) 0)
1607                            match)
1608               (when trace
1609                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1610                       gnus-score-trace))
1611               (setq found t)
1612               (setcdr (car articles) (+ score (cdar articles))))
1613             (setq articles (cdr articles)))
1614           ;; Update expire date
1615           (cond ((null date))           ;Permanent entry.
1616                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1617                  (gnus-score-set 'touched '(t) alist)
1618                  (setcar (nthcdr 2 kill) now))
1619                 ((and expire (< date expire)) ;Old entry, remove.
1620                  (gnus-score-set 'touched '(t) alist)
1621                  (setcdr entries (cdr rest))
1622                  (setq rest entries)))
1623           (setq entries rest)))))
1624   nil)
1625
1626 (defun gnus-score-date (scores header now expire &optional trace)
1627   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1628         entries alist match match-func article)
1629     ;; Find matches.
1630     (while scores
1631       (setq alist (car scores)
1632             scores (cdr scores)
1633             entries (assoc header alist))
1634       (while (cdr entries)              ;First entry is the header index.
1635         (let* ((rest (cdr entries))
1636                (kill (car rest))
1637                (type (or (nth 3 kill) 'before))
1638                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1639                (date (nth 2 kill))
1640                (found nil)
1641                (articles gnus-scores-articles)
1642                l)
1643           (cond
1644            ((eq type 'after)
1645             (setq match-func 'string<
1646                   match (gnus-date-iso8601 (nth 0 kill))))
1647            ((eq type 'before)
1648             (setq match-func 'gnus-string>
1649                   match (gnus-date-iso8601 (nth 0 kill))))
1650            ((eq type 'at)
1651             (setq match-func 'string=
1652                   match (gnus-date-iso8601 (nth 0 kill))))
1653            ((eq type 'regexp)
1654             (setq match-func 'string-match
1655                   match (nth 0 kill)))
1656            (t (error "Invalid match type: %s" type)))
1657           ;; Instead of doing all the clever stuff that
1658           ;; `gnus-score-string' does to minimize searches and stuff,
1659           ;; I will assume that people generally will put so few
1660           ;; matches on numbers that any cleverness will take more
1661           ;; time than one would gain.
1662           (while (setq article (pop articles))
1663             (when (and
1664                    (setq l (aref (car article) gnus-score-index))
1665                    (funcall match-func match (gnus-date-iso8601 l)))
1666               (when trace
1667                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1668                       gnus-score-trace))
1669               (setq found t)
1670               (setcdr article (+ score (cdr article)))))
1671           ;; Update expire date
1672           (cond ((null date))           ;Permanent entry.
1673                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1674                  (gnus-score-set 'touched '(t) alist)
1675                  (setcar (nthcdr 2 kill) now))
1676                 ((and expire (< date expire)) ;Old entry, remove.
1677                  (gnus-score-set 'touched '(t) alist)
1678                  (setcdr entries (cdr rest))
1679                  (setq rest entries)))
1680           (setq entries rest)))))
1681   nil)
1682
1683 (defun gnus-score-body (scores header now expire &optional trace)
1684   (if gnus-agent-fetching
1685       nil
1686     (save-excursion
1687       (setq gnus-scores-articles
1688             (sort gnus-scores-articles
1689                   (lambda (a1 a2)
1690                     (< (mail-header-number (car a1))
1691                        (mail-header-number (car a2))))))
1692       (set-buffer nntp-server-buffer)
1693       (save-restriction
1694         (let* ((buffer-read-only nil)
1695                (articles gnus-scores-articles)
1696                (all-scores scores)
1697                (request-func (cond ((string= "head" header)
1698                                     'gnus-request-head)
1699                                    ((string= "body" header)
1700                                     'gnus-request-body)
1701                                    (t 'gnus-request-article)))
1702                entries alist ofunc article last)
1703           (when articles
1704             (setq last (mail-header-number (caar (last articles))))
1705           ;; Not all backends support partial fetching.  In that case,
1706             ;; we just fetch the entire article.
1707             (unless (gnus-check-backend-function
1708                      (and (string-match "^gnus-" (symbol-name request-func))
1709                           (intern (substring (symbol-name request-func)
1710                                              (match-end 0))))
1711                      gnus-newsgroup-name)
1712               (setq ofunc request-func)
1713               (setq request-func 'gnus-request-article))
1714             (while articles
1715               (setq article (mail-header-number (caar articles)))
1716               (gnus-message 7 "Scoring article %s of %s..." article last)
1717               (widen)
1718               (when (funcall request-func article gnus-newsgroup-name)
1719                 (goto-char (point-min))
1720             ;; If just parts of the article is to be searched, but the
1721             ;; backend didn't support partial fetching, we just narrow
1722                 ;; to the relevant parts.
1723                 (when ofunc
1724                   (if (eq ofunc 'gnus-request-head)
1725                       (narrow-to-region
1726                        (point)
1727                        (or (search-forward "\n\n" nil t) (point-max)))
1728                     (narrow-to-region
1729                      (or (search-forward "\n\n" nil t) (point))
1730                      (point-max))))
1731                 (setq scores all-scores)
1732                 ;; Find matches.
1733                 (while scores
1734                   (setq alist (pop scores)
1735                         entries (assoc header alist))
1736                   (while (cdr entries) ;First entry is the header index.
1737                     (let* ((rest (cdr entries))
1738                            (kill (car rest))
1739                            (match (nth 0 kill))
1740                            (type (or (nth 3 kill) 's))
1741                            (score (or (nth 1 kill)
1742                                       gnus-score-interactive-default-score))
1743                            (date (nth 2 kill))
1744                            (found nil)
1745                            (case-fold-search
1746                             (not (or (eq type 'R) (eq type 'S)
1747                                      (eq type 'Regexp) (eq type 'String))))
1748                            (search-func
1749                             (cond ((or (eq type 'r) (eq type 'R)
1750                                        (eq type 'regexp) (eq type 'Regexp))
1751                                    're-search-forward)
1752                                   ((or (eq type 's) (eq type 'S)
1753                                        (eq type 'string) (eq type 'String))
1754                                    'search-forward)
1755                                   (t
1756                                    (error "Invalid match type: %s" type)))))
1757                       (goto-char (point-min))
1758                       (when (funcall search-func match nil t)
1759                         ;; Found a match, update scores.
1760                         (setcdr (car articles) (+ score (cdar articles)))
1761                         (setq found t)
1762                         (when trace
1763                           (push
1764                            (cons (car-safe (rassq alist gnus-score-cache))
1765                                  kill)
1766                            gnus-score-trace)))
1767                       ;; Update expire date
1768                       (unless trace
1769                         (cond
1770                          ((null date))  ;Permanent entry.
1771                          ((and found gnus-update-score-entry-dates)
1772                           ;; Match, update date.
1773                           (gnus-score-set 'touched '(t) alist)
1774                           (setcar (nthcdr 2 kill) now))
1775                          ((and expire (< date expire)) ;Old entry, remove.
1776                           (gnus-score-set 'touched '(t) alist)
1777                           (setcdr entries (cdr rest))
1778                           (setq rest entries))))
1779                       (setq entries rest)))))
1780               (setq articles (cdr articles)))))))
1781     nil))
1782
1783 (defun gnus-score-thread (scores header now expire &optional trace)
1784   (gnus-score-followup scores header now expire trace t))
1785
1786 (defun gnus-score-followup (scores header now expire &optional trace thread)
1787   (if gnus-agent-fetching
1788       ;; FIXME: It seems doable in fetching mode.
1789       nil
1790     ;; Insert the unique article headers in the buffer.
1791     (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1792           (current-score-file gnus-current-score-file)
1793           (all-scores scores)
1794           ;; gnus-score-index is used as a free variable.
1795           alike last this art entries alist articles
1796           new news)
1797
1798       ;; Change score file to the adaptive score file.  All entries that
1799       ;; this function makes will be put into this file.
1800       (save-excursion
1801         (set-buffer gnus-summary-buffer)
1802         (gnus-score-load-file
1803          (or gnus-newsgroup-adaptive-score-file
1804              (gnus-score-file-name
1805               gnus-newsgroup-name gnus-adaptive-file-suffix))))
1806
1807       (setq gnus-scores-articles (sort gnus-scores-articles
1808                                        'gnus-score-string<)
1809             articles gnus-scores-articles)
1810
1811       (erase-buffer)
1812       (while articles
1813         (setq art (car articles)
1814               this (aref (car art) gnus-score-index)
1815               articles (cdr articles))
1816         (if (equal last this)
1817             (push art alike)
1818           (when last
1819             (insert last ?\n)
1820             (put-text-property (1- (point)) (point) 'articles alike))
1821           (setq alike (list art)
1822                 last this)))
1823       (when last                        ; Bwadr, duplicate code.
1824         (insert last ?\n)
1825         (put-text-property (1- (point)) (point) 'articles alike))
1826
1827       ;; Find matches.
1828       (while scores
1829         (setq alist (car scores)
1830               scores (cdr scores)
1831               entries (assoc header alist))
1832         (while (cdr entries)            ;First entry is the header index.
1833           (let* ((rest (cdr entries))
1834                  (kill (car rest))
1835                  (match (nth 0 kill))
1836                  (type (or (nth 3 kill) 's))
1837                  (score (or (nth 1 kill) gnus-score-interactive-default-score))
1838                  (date (nth 2 kill))
1839                  (found nil)
1840                  (mt (aref (symbol-name type) 0))
1841                  (case-fold-search
1842                   (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1843                  (dmt (downcase mt))
1844                  (search-func
1845                   (cond ((= dmt ?r) 're-search-forward)
1846                         ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1847                         (t (error "Invalid match type: %s" type))))
1848                  arts art)
1849             (goto-char (point-min))
1850             (if (= dmt ?e)
1851                 (while (funcall search-func match nil t)
1852                   (and (= (gnus-point-at-bol)
1853                           (match-beginning 0))
1854                        (= (progn (end-of-line) (point))
1855                           (match-end 0))
1856                        (progn
1857                          (setq found (setq arts (get-text-property
1858                                                  (point) 'articles)))
1859                          ;; Found a match, update scores.
1860                          (while arts
1861                            (setq art (car arts)
1862                                  arts (cdr arts))
1863                            (gnus-score-add-followups
1864                             (car art) score all-scores thread))))
1865                   (end-of-line))
1866               (while (funcall search-func match nil t)
1867                 (end-of-line)
1868                 (setq found (setq arts (get-text-property (point) 'articles)))
1869                 ;; Found a match, update scores.
1870                 (while (setq art (pop arts))
1871                   (setcdr art (+ score (cdr art)))
1872                   (when trace
1873                     (push (cons
1874                            (car-safe (rassq alist gnus-score-cache))
1875                            kill)
1876                           gnus-score-trace))
1877                   (when (setq new (gnus-score-add-followups
1878                                    (car art) score all-scores thread))
1879                     (push new news)))))
1880             ;; Update expire date
1881             (cond ((null date))         ;Permanent entry.
1882                   ((and found gnus-update-score-entry-dates)
1883                                         ;Match, update date.
1884                    (gnus-score-set 'touched '(t) alist)
1885                    (setcar (nthcdr 2 kill) now))
1886                   ((and expire (< date expire)) ;Old entry, remove.
1887                    (gnus-score-set 'touched '(t) alist)
1888                    (setcdr entries (cdr rest))
1889                    (setq rest entries)))
1890             (setq entries rest))))
1891       ;; We change the score file back to the previous one.
1892       (save-excursion
1893         (set-buffer gnus-summary-buffer)
1894         (gnus-score-load-file current-score-file))
1895       (list (cons "references" news)))))
1896
1897 (defun gnus-score-add-followups (header score scores &optional thread)
1898   "Add a score entry to the adapt file."
1899   (save-excursion
1900     (set-buffer gnus-summary-buffer)
1901     (let* ((id (mail-header-id header))
1902            (scores (car scores))
1903            entry dont)
1904       ;; Don't enter a score if there already is one.
1905       (while (setq entry (pop scores))
1906         (and (equal "references" (car entry))
1907              (or (null (nth 3 (cadr entry)))
1908                  (eq 's (nth 3 (cadr entry))))
1909              (assoc id entry)
1910              (setq dont t)))
1911       (unless dont
1912         (gnus-summary-score-entry
1913          (if thread "thread" "references")
1914          id 's score (current-time-string) nil t)))))
1915
1916 (defun gnus-score-string (score-list header now expire &optional trace)
1917   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1918   ;; Update matching entries to NOW and remove unmatched entries older
1919   ;; than EXPIRE.
1920
1921   ;; Insert the unique article headers in the buffer.
1922   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1923         ;; gnus-score-index is used as a free variable.
1924         (simplify (and gnus-score-thread-simplify
1925                        (string= "subject" header)))
1926         alike last this art entries alist articles
1927         fuzzies arts words kill)
1928
1929     ;; Sorting the articles costs os O(N*log N) but will allow us to
1930     ;; only match with each unique header.  Thus the actual matching
1931     ;; will be O(M*U) where M is the number of strings to match with,
1932     ;; and U is the number of unique headers.  It is assumed (but
1933     ;; untested) this will be a net win because of the large constant
1934     ;; factor involved with string matching.
1935     (setq gnus-scores-articles
1936           ;; We cannot string-sort the extra headers list.  *sigh*
1937           (if (= gnus-score-index 9)
1938               gnus-scores-articles
1939             (sort gnus-scores-articles 'gnus-score-string<))
1940           articles gnus-scores-articles)
1941
1942     (erase-buffer)
1943     (while (setq art (pop articles))
1944       (setq this (aref (car art) gnus-score-index))
1945
1946       ;; If we're working with non-standard headers, we are stuck
1947       ;; with working on them as a group.  What a hassle.
1948       ;; Just wait 'til you see what horrors we commit against `match'...
1949       (if (= gnus-score-index 9)
1950           (setq this (gnus-prin1-to-string this))) ; ick.
1951
1952       (if simplify
1953           (setq this (gnus-map-function gnus-simplify-subject-functions this)))
1954       (if (equal last this)
1955           ;; O(N*H) cons-cells used here, where H is the number of
1956           ;; headers.
1957           (push art alike)
1958         (when last
1959           ;; Insert the line, with a text property on the
1960           ;; terminating newline referring to the articles with
1961           ;; this line.
1962           (insert last ?\n)
1963           (put-text-property (1- (point)) (point) 'articles alike))
1964         (setq alike (list art)
1965               last this)))
1966     (when last                          ; Bwadr, duplicate code.
1967       (insert last ?\n)
1968       (put-text-property (1- (point)) (point) 'articles alike))
1969
1970     ;; Go through all the score alists and pick out the entries
1971     ;; for this header.
1972     (while score-list
1973       (setq alist (pop score-list)
1974             ;; There's only one instance of this header for
1975             ;; each score alist.
1976             entries (assoc header alist))
1977       (while (cdr entries)              ;First entry is the header index.
1978         (let* ((kill (cadr entries))
1979                (type (or (nth 3 kill) 's))
1980                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1981                (date (nth 2 kill))
1982                (extra (nth 4 kill))     ; non-standard header; string.
1983                (found nil)
1984                (mt (aref (symbol-name type) 0))
1985                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
1986                (dmt (downcase mt))
1987                ;; Assume user already simplified regexp and fuzzies
1988                (match (if (and simplify (not (memq dmt '(?f ?r))))
1989                           (gnus-map-function
1990                            gnus-simplify-subject-functions
1991                            (nth 0 kill))
1992                         (nth 0 kill)))
1993                (search-func
1994                 (cond ((= dmt ?r) 're-search-forward)
1995                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1996                       ((= dmt ?w) nil)
1997                       (t (error "Invalid match type: %s" type)))))
1998
1999           ;; Evil hackery to make match usable in non-standard headers.
2000           (when extra
2001             (setq match (concat "[ (](" extra " \\. \"[^)]*"
2002                                 match "[^\"]*\")[ )]")
2003                   search-func 're-search-forward)) ; XXX danger?!?
2004
2005           (cond
2006            ;; Fuzzy matches.  We save these for later.
2007            ((= dmt ?f)
2008             (push (cons entries alist) fuzzies)
2009             (setq entries (cdr entries)))
2010            ;; Word matches.  Save these for even later.
2011            ((= dmt ?w)
2012             (push (cons entries alist) words)
2013             (setq entries (cdr entries)))
2014            ;; Exact matches.
2015            ((= dmt ?e)
2016             ;; Do exact matching.
2017             (goto-char (point-min))
2018             (while (and (not (eobp))
2019                         (funcall search-func match nil t))
2020               ;; Is it really exact?
2021               (and (eolp)
2022                    (= (gnus-point-at-bol) (match-beginning 0))
2023                    ;; Yup.
2024                    (progn
2025                      (setq found (setq arts (get-text-property
2026                                              (point) 'articles)))
2027                      ;; Found a match, update scores.
2028                      (if trace
2029                          (while (setq art (pop arts))
2030                            (setcdr art (+ score (cdr art)))
2031                            (push
2032                             (cons
2033                              (car-safe (rassq alist gnus-score-cache))
2034                              kill)
2035                             gnus-score-trace))
2036                        (while (setq art (pop arts))
2037                          (setcdr art (+ score (cdr art)))))))
2038               (forward-line 1))
2039             ;; Update expiry date
2040             (if trace
2041                 (setq entries (cdr entries))
2042               (cond
2043                ;; Permanent entry.
2044                ((null date)
2045                 (setq entries (cdr entries)))
2046                ;; We have a match, so we update the date.
2047                ((and found gnus-update-score-entry-dates)
2048                 (gnus-score-set 'touched '(t) alist)
2049                 (setcar (nthcdr 2 kill) now)
2050                 (setq entries (cdr entries)))
2051                ;; This entry has expired, so we remove it.
2052                ((and expire (< date expire))
2053                 (gnus-score-set 'touched '(t) alist)
2054                 (setcdr entries (cddr entries)))
2055                ;; No match; go to next entry.
2056                (t
2057                 (setq entries (cdr entries))))))
2058            ;; Regexp and substring matching.
2059            (t
2060             (goto-char (point-min))
2061             (when (string= match "")
2062               (setq match "\n"))
2063             (while (and (not (eobp))
2064                         (funcall search-func match nil t))
2065               (goto-char (match-beginning 0))
2066               (end-of-line)
2067               (setq found (setq arts (get-text-property (point) 'articles)))
2068               ;; Found a match, update scores.
2069               (if trace
2070                   (while (setq art (pop arts))
2071                     (setcdr art (+ score (cdr art)))
2072                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
2073                           gnus-score-trace))
2074                 (while (setq art (pop arts))
2075                   (setcdr art (+ score (cdr art)))))
2076               (forward-line 1))
2077             ;; Update expiry date
2078             (if trace
2079                 (setq entries (cdr entries))
2080               (cond
2081                ;; Permanent entry.
2082                ((null date)
2083                 (setq entries (cdr entries)))
2084                ;; We have a match, so we update the date.
2085                ((and found gnus-update-score-entry-dates)
2086                 (gnus-score-set 'touched '(t) alist)
2087                 (setcar (nthcdr 2 kill) now)
2088                 (setq entries (cdr entries)))
2089                ;; This entry has expired, so we remove it.
2090                ((and expire (< date expire))
2091                 (gnus-score-set 'touched '(t) alist)
2092                 (setcdr entries (cddr entries)))
2093                ;; No match; go to next entry.
2094                (t
2095                 (setq entries (cdr entries))))))))))
2096
2097     ;; Find fuzzy matches.
2098     (when fuzzies
2099       ;; Simplify the entire buffer for easy matching.
2100       (gnus-simplify-buffer-fuzzy)
2101       (while (setq kill (cadaar fuzzies))
2102         (let* ((match (nth 0 kill))
2103                (type (nth 3 kill))
2104                (score (or (nth 1 kill) gnus-score-interactive-default-score))
2105                (date (nth 2 kill))
2106                (mt (aref (symbol-name type) 0))
2107                (case-fold-search (not (= mt ?F)))
2108                found)
2109           (goto-char (point-min))
2110           (while (and (not (eobp))
2111                       (search-forward match nil t))
2112             (when (and (= (gnus-point-at-bol) (match-beginning 0))
2113                        (eolp))
2114               (setq found (setq arts (get-text-property (point) 'articles)))
2115               (if trace
2116                   (while (setq art (pop arts))
2117                     (setcdr art (+ score (cdr art)))
2118                     (push (cons
2119                            (car-safe (rassq (cdar fuzzies) gnus-score-cache))
2120                            kill)
2121                           gnus-score-trace))
2122                 ;; Found a match, update scores.
2123                 (while (setq art (pop arts))
2124                   (setcdr art (+ score (cdr art))))))
2125             (forward-line 1))
2126           ;; Update expiry date
2127           (if (not trace)
2128               (cond
2129                ;; Permanent.
2130                ((null date)
2131                 ;; Do nothing.
2132                 )
2133                ;; Match, update date.
2134                ((and found gnus-update-score-entry-dates)
2135                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2136                 (setcar (nthcdr 2 kill) now))
2137                ;; Old entry, remove.
2138                ((and expire (< date expire))
2139                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2140                 (setcdr (caar fuzzies) (cddaar fuzzies)))))
2141           (setq fuzzies (cdr fuzzies)))))
2142
2143     (when words
2144       ;; Enter all words into the hashtb.
2145       (let ((hashtb (gnus-make-hashtable
2146                      (* 10 (count-lines (point-min) (point-max))))))
2147         (gnus-enter-score-words-into-hashtb hashtb)
2148         (while (setq kill (cadaar words))
2149           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
2150                  (date (nth 2 kill))
2151                  found)
2152             (when (setq arts (intern-soft (nth 0 kill) hashtb))
2153               (setq arts (symbol-value arts))
2154               (setq found t)
2155               (if trace
2156                   (while (setq art (pop arts))
2157                     (setcdr art (+ score (cdr art)))
2158                     (push (cons
2159                            (car-safe (rassq (cdar words) gnus-score-cache))
2160                            kill)
2161                           gnus-score-trace))
2162                 ;; Found a match, update scores.
2163                 (while (setq art (pop arts))
2164                   (setcdr art (+ score (cdr art))))))
2165             ;; Update expiry date
2166             (if (not trace)
2167                 (cond
2168                  ;; Permanent.
2169                  ((null date)
2170                   ;; Do nothing.
2171                   )
2172                  ;; Match, update date.
2173                  ((and found gnus-update-score-entry-dates)
2174                   (gnus-score-set 'touched '(t) (cdar words))
2175                   (setcar (nthcdr 2 kill) now))
2176                  ;; Old entry, remove.
2177                  ((and expire (< date expire))
2178                   (gnus-score-set 'touched '(t) (cdar words))
2179                   (setcdr (caar words) (cddaar words)))))
2180             (setq words (cdr words))))))
2181     nil))
2182
2183 (defun gnus-enter-score-words-into-hashtb (hashtb)
2184   ;; Find all the words in the buffer and enter them into
2185   ;; the hashtable.
2186   (let ((syntab (syntax-table))
2187         word val)
2188     (goto-char (point-min))
2189     (unwind-protect
2190         (progn
2191           (set-syntax-table gnus-adaptive-word-syntax-table)
2192           (while (re-search-forward "\\b\\w+\\b" nil t)
2193             (setq val
2194                   (gnus-gethash
2195                    (setq word (downcase (buffer-substring
2196                                          (match-beginning 0) (match-end 0))))
2197                    hashtb))
2198             (gnus-sethash
2199              word
2200              (append (get-text-property (gnus-point-at-eol) 'articles) val)
2201              hashtb)))
2202       (set-syntax-table syntab))
2203     ;; Make all the ignorable words ignored.
2204     (let ((ignored (append gnus-ignored-adaptive-words
2205                            (if gnus-adaptive-word-no-group-words
2206                                (message-tokenize-header
2207                                 (gnus-group-real-name gnus-newsgroup-name)
2208                                 "."))
2209                            gnus-default-ignored-adaptive-words)))
2210       (while ignored
2211         (gnus-sethash (pop ignored) nil hashtb)))))
2212
2213 (defun gnus-score-string< (a1 a2)
2214   ;; Compare headers in articles A2 and A2.
2215   ;; The header index used is the free variable `gnus-score-index'.
2216   (string-lessp (aref (car a1) gnus-score-index)
2217                 (aref (car a2) gnus-score-index)))
2218
2219 (defun gnus-current-score-file-nondirectory (&optional score-file)
2220   (let ((score-file (or score-file gnus-current-score-file)))
2221     (if score-file
2222         (gnus-short-group-name (file-name-nondirectory score-file))
2223       "none")))
2224
2225 (defun gnus-score-adaptive ()
2226   "Create adaptive score rules for this newsgroup."
2227   (when gnus-newsgroup-adaptive
2228     ;; We change the score file to the adaptive score file.
2229     (save-excursion
2230       (set-buffer gnus-summary-buffer)
2231       (gnus-score-load-file
2232        (or gnus-newsgroup-adaptive-score-file
2233            (gnus-home-score-file gnus-newsgroup-name t)
2234            (gnus-score-file-name
2235             gnus-newsgroup-name gnus-adaptive-file-suffix))))
2236     ;; Perform ordinary line scoring.
2237     (when (or (not (listp gnus-newsgroup-adaptive))
2238               (memq 'line gnus-newsgroup-adaptive))
2239       (save-excursion
2240         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
2241                (alist malist)
2242                (date (current-time-string))
2243                (data gnus-newsgroup-data)
2244                elem headers match func)
2245           ;; First we transform the adaptive rule alist into something
2246           ;; that's faster to process.
2247           (while malist
2248             (setq elem (car malist))
2249             (when (symbolp (car elem))
2250               (setcar elem (symbol-value (car elem))))
2251             (setq elem (cdr elem))
2252             (while elem
2253               (when (fboundp
2254                      (setq func
2255                            (intern
2256                             (concat "mail-header-"
2257                                     (if (eq (caar elem) 'followup)
2258                                         "message-id"
2259                                       (downcase (symbol-name (caar elem))))))))
2260                 (setcdr (car elem)
2261                         (cons (if (eq (caar elem) 'followup)
2262                                   "references"
2263                                 (symbol-name (caar elem)))
2264                               (cdar elem)))
2265                 (setcar (car elem)
2266                         `(lambda (h)
2267                            (,func h))))
2268               (setq elem (cdr elem)))
2269             (setq malist (cdr malist)))
2270           ;; Then we score away.
2271           (while data
2272             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2273             (if (or (not elem)
2274                     (gnus-data-pseudo-p (car data)))
2275                 ()
2276               (when (setq headers (gnus-data-header (car data)))
2277                 (while elem
2278                   (setq match (funcall (caar elem) headers))
2279                   (gnus-summary-score-entry
2280                    (nth 1 (car elem)) match
2281                    (cond
2282                     ((numberp match)
2283                      '=)
2284                     ((equal (nth 1 (car elem)) "date")
2285                      'a)
2286                     (t
2287                      ;; Whether we use substring or exact matches is
2288                      ;; controlled here.
2289                      (if (or (not gnus-score-exact-adapt-limit)
2290                              (< (length match) gnus-score-exact-adapt-limit))
2291                          'e
2292                        (if (equal (nth 1 (car elem)) "subject")
2293                            'f 's))))
2294                    (nth 2 (car elem)) date nil t)
2295                   (setq elem (cdr elem)))))
2296             (setq data (cdr data))))))
2297
2298     ;; Perform adaptive word scoring.
2299     (when (and (listp gnus-newsgroup-adaptive)
2300                (memq 'word gnus-newsgroup-adaptive))
2301       (with-temp-buffer
2302         (let* ((hashtb (gnus-make-hashtable 1000))
2303                (date (date-to-day (current-time-string)))
2304                (data gnus-newsgroup-data)
2305                (syntab (syntax-table))
2306                word d score val)
2307           (unwind-protect
2308               (progn
2309                 (set-syntax-table gnus-adaptive-word-syntax-table)
2310                 ;; Go through all articles.
2311                 (while (setq d (pop data))
2312                   (when (and
2313                          (not (gnus-data-pseudo-p d))
2314                          (setq score
2315                                (cdr (assq
2316                                      (gnus-data-mark d)
2317                                      gnus-adaptive-word-score-alist))))
2318                     ;; This article has a mark that should lead to
2319                     ;; adaptive word rules, so we insert the subject
2320                     ;; and find all words in that string.
2321                     (insert (mail-header-subject (gnus-data-header d)))
2322                     (downcase-region (point-min) (point-max))
2323                     (goto-char (point-min))
2324                     (while (re-search-forward "\\b\\w+\\b" nil t)
2325                       ;; Put the word and score into the hashtb.
2326                       (setq val (gnus-gethash (setq word (match-string 0))
2327                                               hashtb))
2328                       (when (or (not gnus-adaptive-word-length-limit)
2329                                 (> (length word)
2330                                    gnus-adaptive-word-length-limit))
2331                         (setq val (+ score (or val 0)))
2332                         (if (and gnus-adaptive-word-minimum
2333                                  (< val gnus-adaptive-word-minimum))
2334                             (setq val gnus-adaptive-word-minimum))
2335                         (gnus-sethash word val hashtb)))
2336                     (erase-buffer))))
2337             (set-syntax-table syntab))
2338           ;; Make all the ignorable words ignored.
2339           (let ((ignored (append gnus-ignored-adaptive-words
2340                                  (if gnus-adaptive-word-no-group-words
2341                                      (message-tokenize-header
2342                                       (gnus-group-real-name
2343                                        gnus-newsgroup-name)
2344                                       "."))
2345                                  gnus-default-ignored-adaptive-words)))
2346             (while ignored
2347               (gnus-sethash (pop ignored) nil hashtb)))
2348           ;; Now we have all the words and scores, so we
2349           ;; add these rules to the ADAPT file.
2350           (set-buffer gnus-summary-buffer)
2351           (mapatoms
2352            (lambda (word)
2353              (when (symbol-value word)
2354                (gnus-summary-score-entry
2355                 "subject" (symbol-name word) 'w (symbol-value word)
2356                 date nil t)))
2357            hashtb))))))
2358
2359 (defun gnus-score-edit-done ()
2360   (let ((bufnam (buffer-file-name (current-buffer)))
2361         (winconf gnus-prev-winconf))
2362     (when winconf
2363       (set-window-configuration winconf))
2364     (gnus-score-remove-from-cache bufnam)
2365     (gnus-score-load-file bufnam)))
2366
2367 (defun gnus-score-find-trace ()
2368   "Find all score rules that applies to the current article."
2369   (interactive)
2370   (let ((old-scored gnus-newsgroup-scored))
2371     (let ((gnus-newsgroup-headers
2372            (list (gnus-summary-article-header)))
2373           (gnus-newsgroup-scored nil)
2374           ;; Must be synced with `gnus-score-edit-file-at-point':
2375           (frmt "%S [%s] -> %s\n")
2376           trace
2377           file)
2378       (save-excursion
2379         (nnheader-set-temp-buffer "*Score Trace*"))
2380       (setq gnus-score-trace nil)
2381       (gnus-possibly-score-headers 'trace)
2382       (if (not (setq trace gnus-score-trace))
2383           (gnus-error
2384            1 "No score rules apply to the current article (default score %d)."
2385            gnus-summary-default-score)
2386         (set-buffer "*Score Trace*")
2387         ;; Use a keymap instead?
2388         (local-set-key "q"
2389                        (lambda ()
2390                          (interactive)
2391                          (bury-buffer nil)
2392                          (gnus-summary-expand-window)))
2393         (local-set-key "e" (lambda ()
2394                              "Run `gnus-score-edit-file-at-point'."
2395                              (interactive)
2396                              (gnus-score-edit-file-at-point)))
2397         (local-set-key "f" (lambda ()
2398                              "Run `gnus-score-edit-file-at-point'."
2399                              (interactive)
2400                              (gnus-score-edit-file-at-point 'format)))
2401         (local-set-key "t" 'toggle-truncate-lines)
2402         (setq truncate-lines t)
2403         (dolist (entry trace)
2404           (setq file (or (car entry)
2405                          ;; Must be synced with
2406                          ;; `gnus-score-edit-file-at-point':
2407                          "(non-file rule)"))
2408           (insert
2409            (format frmt
2410                    (cdr entry)
2411                    ;; Don't use `file-name-sans-extension' to see .SCORE and
2412                    ;; .ADAPT directly:
2413                    (file-name-nondirectory file)
2414                    (abbreviate-file-name file))))
2415         (insert
2416          "\n\nQuick help:
2417
2418 Type `e' to edit score file corresponding to the score rule on current line,
2419 `f' to format (pretty print) the score file and edit it,
2420 `t' toggle to truncate long lines in this buffer,
2421 `q' to quit.
2422
2423 The first sexp on each line is the score rule, followed by the file name of
2424 the score file and its full name, including the directory.")
2425         (goto-char (point-min))
2426         (gnus-configure-windows 'score-trace)))
2427     (set-buffer gnus-summary-buffer)
2428     (setq gnus-newsgroup-scored old-scored)))
2429
2430 (defun gnus-score-find-favourite-words ()
2431   "List words used in scoring."
2432   (interactive)
2433   (let ((alists (gnus-score-load-files (gnus-all-score-files)))
2434         alist rule rules kill)
2435     ;; Go through all the score alists for this group
2436     ;; and find all `w' rules.
2437     (while (setq alist (pop alists))
2438       (while (setq rule (pop alist))
2439         (when (and (stringp (car rule))
2440                    (equal "subject" (downcase (pop rule))))
2441           (while (setq kill (pop rule))
2442             (when (memq (nth 3 kill) '(w W word Word))
2443               (push (cons (or (nth 1 kill)
2444                               gnus-score-interactive-default-score)
2445                           (car kill))
2446                     rules))))))
2447     (setq rules (sort rules (lambda (r1 r2)
2448                               (string-lessp (cdr r1) (cdr r2)))))
2449     ;; Add up words that have appeared several times.
2450     (let ((r rules))
2451       (while (cdr r)
2452         (if (equal (cdar r) (cdadr r))
2453             (progn
2454               (setcar (car r) (+ (caar r) (caadr r)))
2455               (setcdr r (cddr r)))
2456           (pop r))))
2457     ;; Insert the words.
2458     (nnheader-set-temp-buffer "*Score Words*")
2459     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2460         (gnus-error 3 "No word score rules")
2461       (while rules
2462         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2463         (pop rules))
2464       (goto-char (point-min))
2465       (gnus-configure-windows 'score-words))))
2466
2467 (defun gnus-summary-rescore ()
2468   "Redo the entire scoring process in the current summary."
2469   (interactive)
2470   (gnus-score-save)
2471   (setq gnus-score-cache nil)
2472   (setq gnus-newsgroup-scored nil)
2473   (gnus-possibly-score-headers)
2474   (gnus-score-update-all-lines))
2475
2476 (defun gnus-score-flush-cache ()
2477   "Flush the cache of score files."
2478   (interactive)
2479   (gnus-score-save)
2480   (setq gnus-score-cache nil
2481         gnus-score-alist nil
2482         gnus-short-name-score-file-cache nil)
2483   (gnus-message 6 "The score cache is now flushed"))
2484
2485 (gnus-add-shutdown 'gnus-score-close 'gnus)
2486
2487 (defvar gnus-score-file-alist-cache nil)
2488
2489 (defun gnus-score-close ()
2490   "Clear all internal score variables."
2491   (setq gnus-score-cache nil
2492         gnus-internal-global-score-files nil
2493         gnus-score-file-list nil
2494         gnus-score-file-alist-cache nil))
2495
2496 ;; Summary score marking commands.
2497
2498 (defun gnus-summary-raise-same-subject-and-select (score)
2499   "Raise articles which has the same subject with SCORE and select the next."
2500   (interactive "p")
2501   (let ((subject (gnus-summary-article-subject)))
2502     (gnus-summary-raise-score score)
2503     (while (gnus-summary-find-subject subject)
2504       (gnus-summary-raise-score score))
2505     (gnus-summary-next-article t)))
2506
2507 (defun gnus-summary-raise-same-subject (score)
2508   "Raise articles which has the same subject with SCORE."
2509   (interactive "p")
2510   (let ((subject (gnus-summary-article-subject)))
2511     (gnus-summary-raise-score score)
2512     (while (gnus-summary-find-subject subject)
2513       (gnus-summary-raise-score score))
2514     (gnus-summary-next-subject 1 t)))
2515
2516 (defun gnus-score-delta-default (level)
2517   (if level (prefix-numeric-value level)
2518     gnus-score-interactive-default-score))
2519
2520 (defun gnus-summary-raise-thread (&optional score)
2521   "Raise the score of the articles in the current thread with SCORE."
2522   (interactive "P")
2523   (setq score (gnus-score-delta-default score))
2524   (let (e)
2525     (save-excursion
2526       (let ((articles (gnus-summary-articles-in-thread)))
2527         (while articles
2528           (gnus-summary-goto-subject (car articles))
2529           (gnus-summary-raise-score score)
2530           (setq articles (cdr articles))))
2531       (setq e (point)))
2532     (let ((gnus-summary-check-current t))
2533       (unless (zerop (gnus-summary-next-subject 1 t))
2534         (goto-char e))))
2535   (gnus-summary-recenter)
2536   (gnus-summary-position-point)
2537   (gnus-set-mode-line 'summary))
2538
2539 (defun gnus-summary-lower-same-subject-and-select (score)
2540   "Raise articles which has the same subject with SCORE and select the next."
2541   (interactive "p")
2542   (gnus-summary-raise-same-subject-and-select (- score)))
2543
2544 (defun gnus-summary-lower-same-subject (score)
2545   "Raise articles which has the same subject with SCORE."
2546   (interactive "p")
2547   (gnus-summary-raise-same-subject (- score)))
2548
2549 (defun gnus-summary-lower-thread (&optional score)
2550   "Lower score of articles in the current thread with SCORE."
2551   (interactive "P")
2552   (gnus-summary-raise-thread (- (gnus-score-delta-default score))))
2553
2554 ;;; Finding score files.
2555
2556 (defun gnus-score-score-files (group)
2557   "Return a list of all possible score files."
2558   ;; Search and set any global score files.
2559   (when gnus-global-score-files
2560     (unless gnus-internal-global-score-files
2561       (gnus-score-search-global-directories gnus-global-score-files)))
2562   ;; Fix the kill-file dir variable.
2563   (setq gnus-kill-files-directory
2564         (file-name-as-directory gnus-kill-files-directory))
2565   ;; If we can't read it, there are no score files.
2566   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2567       (setq gnus-score-file-list nil)
2568     (if (not (gnus-use-long-file-name 'not-score))
2569         ;; We do not use long file names, so we have to do some
2570         ;; directory traversing.
2571         (setq gnus-score-file-list
2572               (cons nil
2573                     (or gnus-short-name-score-file-cache
2574                         (prog2
2575                             (gnus-message 6 "Finding all score files...")
2576                             (setq gnus-short-name-score-file-cache
2577                                   (gnus-score-score-files-1
2578                                    gnus-kill-files-directory))
2579                           (gnus-message 6 "Finding all score files...done")))))
2580       ;; We want long file names.
2581       (when (or (not gnus-score-file-list)
2582                 (not (car gnus-score-file-list))
2583                 (gnus-file-newer-than gnus-kill-files-directory
2584                                       (car gnus-score-file-list)))
2585         (setq gnus-score-file-list
2586               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2587                     (nreverse
2588                      (directory-files
2589                       gnus-kill-files-directory t
2590                       (gnus-score-file-regexp)))))))
2591     (cdr gnus-score-file-list)))
2592
2593 (defun gnus-score-score-files-1 (dir)
2594   "Return all possible score files under DIR."
2595   (let ((files (list (expand-file-name dir)))
2596         (regexp (gnus-score-file-regexp))
2597         (case-fold-search nil)
2598         seen out file)
2599     (while (setq file (pop files))
2600       (cond
2601        ;; Ignore files that start with a dot.
2602        ((string-match "^\\." (file-name-nondirectory file))
2603         nil)
2604        ;; Add subtrees of directory to also be searched.
2605        ((and (file-directory-p file)
2606              (not (member (file-truename file) seen)))
2607         (push (file-truename file) seen)
2608         (setq files (nconc (directory-files file t nil t) files)))
2609        ;; Add files to the list of score files.
2610        ((string-match regexp file)
2611         (push file out))))
2612     (or out
2613         ;; Return a dummy value.
2614         (list (expand-file-name "this.file.does.not.exist.SCORE"
2615                                 gnus-kill-files-directory)))))
2616
2617 (defun gnus-score-file-regexp ()
2618   "Return a regexp that match all score files."
2619   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2620           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2621
2622 (defun gnus-score-find-bnews (group)
2623   "Return a list of score files for GROUP.
2624 The score files are those files in the ~/News/ directory which matches
2625 GROUP using BNews sys file syntax."
2626   (let* ((sfiles (append (gnus-score-score-files group)
2627                          gnus-internal-global-score-files))
2628          (kill-dir (file-name-as-directory
2629                     (expand-file-name gnus-kill-files-directory)))
2630          (klen (length kill-dir))
2631          (score-regexp (gnus-score-file-regexp))
2632          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2633          (group-trans (nnheader-translate-file-chars group t))
2634          ofiles not-match regexp)
2635     (save-excursion
2636       (set-buffer (gnus-get-buffer-create "*gnus score files*"))
2637       (buffer-disable-undo)
2638       ;; Go through all score file names and create regexp with them
2639       ;; as the source.
2640       (while sfiles
2641         (erase-buffer)
2642         (insert (car sfiles))
2643         (goto-char (point-min))
2644         ;; First remove the suffix itself.
2645         (when (re-search-forward (concat "." score-regexp) nil t)
2646           (replace-match "" t t)
2647           (goto-char (point-min))
2648           (if (looking-at (regexp-quote kill-dir))
2649               ;; If the file name was just "SCORE", `klen' is one character
2650               ;; too much.
2651               (delete-char (min (1- (point-max)) klen))
2652             (goto-char (point-max))
2653             (if (re-search-backward gnus-directory-sep-char-regexp nil t)
2654                 (delete-region (1+ (point)) (point-min))
2655               (gnus-message 1 "Can't find directory separator in %s"
2656                             (car sfiles))))
2657           ;; If short file names were used, we have to translate slashes.
2658           (goto-char (point-min))
2659           (let ((regexp (concat
2660                          "[/:" (if trans (char-to-string trans)) "]")))
2661             (while (re-search-forward regexp nil t)
2662               (replace-match "." t t)))
2663           ;; Kludge to get rid of "nntp+" problems.
2664           (goto-char (point-min))
2665           (when (looking-at "nn[a-z]+\\+")
2666             (search-forward "+")
2667             (forward-char -1)
2668             (insert "\\")
2669             (forward-char 1))
2670           ;; Kludge to deal with "++".
2671           (while (search-forward "+" nil t)
2672             (replace-match "\\+" t t))
2673           ;; Translate "all" to ".*".
2674           (goto-char (point-min))
2675           (while (search-forward "all" nil t)
2676             (replace-match ".*" t t))
2677           (goto-char (point-min))
2678           ;; Deal with "not."s.
2679           (if (looking-at "not.")
2680               (progn
2681                 (setq not-match t)
2682                 (setq regexp
2683                       (concat "^" (buffer-substring 5 (point-max)) "$")))
2684             (setq regexp (concat "^" (buffer-substring 1 (point-max)) "$"))
2685             (setq not-match nil))
2686           ;; Finally - if this resulting regexp matches the group name,
2687           ;; we add this score file to the list of score files
2688           ;; applicable to this group.
2689           (when (or (and not-match
2690                          (ignore-errors
2691                            (not (string-match regexp group-trans))))
2692                     (and (not not-match)
2693                          (ignore-errors (string-match regexp group-trans))))
2694             (push (car sfiles) ofiles)))
2695         (setq sfiles (cdr sfiles)))
2696       (gnus-kill-buffer (current-buffer))
2697       ;; Slight kludge here - the last score file returned should be
2698       ;; the local score file, whether it exists or not.  This is so
2699       ;; that any score commands the user enters will go to the right
2700       ;; file, and not end up in some global score file.
2701       (let ((localscore (gnus-score-file-name group)))
2702         (setq ofiles (cons localscore (delete localscore ofiles))))
2703       (gnus-sort-score-files (nreverse ofiles)))))
2704
2705 (defun gnus-score-find-single (group)
2706   "Return list containing the score file for GROUP."
2707   (list (or gnus-newsgroup-adaptive-score-file
2708             (gnus-score-file-name group gnus-adaptive-file-suffix))
2709         (gnus-score-file-name group)))
2710
2711 (defun gnus-score-find-hierarchical (group)
2712   "Return list of score files for GROUP.
2713 This includes the score file for the group and all its parents."
2714   (let* ((prefix (gnus-group-real-prefix group))
2715          (all (list nil))
2716          (group (gnus-group-real-name group))
2717          (start 0))
2718     (while (string-match "\\." group (1+ start))
2719       (setq start (match-beginning 0))
2720       (push (substring group 0 start) all))
2721     (push group all)
2722     (setq all
2723           (nconc
2724            (mapcar (lambda (group)
2725                      (gnus-score-file-name group gnus-adaptive-file-suffix))
2726                    (setq all (nreverse all)))
2727            (mapcar 'gnus-score-file-name all)))
2728     (if (equal prefix "")
2729         all
2730       (mapcar
2731        (lambda (file)
2732          (nnheader-translate-file-chars
2733           (concat (file-name-directory file) prefix
2734                   (file-name-nondirectory file))))
2735        all))))
2736
2737 (defun gnus-score-file-rank (file)
2738   "Return a number that says how specific score FILE is.
2739 Destroys the current buffer."
2740   (if (member file gnus-internal-global-score-files)
2741       0
2742     (when (string-match
2743            (concat "^" (regexp-quote
2744                         (expand-file-name
2745                          (file-name-as-directory gnus-kill-files-directory))))
2746            file)
2747       (setq file (substring file (match-end 0))))
2748     (insert file)
2749     (goto-char (point-min))
2750     (let ((beg (point))
2751           elems)
2752       (while (re-search-forward "[./]" nil t)
2753         (push (buffer-substring beg (1- (point)))
2754               elems))
2755       (erase-buffer)
2756       (setq elems (delete "all" elems))
2757       (length elems))))
2758
2759 (defun gnus-sort-score-files (files)
2760   "Sort FILES so that the most general files come first."
2761   (with-temp-buffer
2762     (let ((alist
2763            (mapcar
2764             (lambda (file)
2765               (cons (inline (gnus-score-file-rank file)) file))
2766             files)))
2767       (mapcar
2768        (lambda (f) (cdr f))
2769        (sort alist 'car-less-than-car)))))
2770
2771 (defun gnus-score-find-alist (group)
2772   "Return list of score files for GROUP.
2773 The list is determined from the variable `gnus-score-file-alist'."
2774   (let ((alist gnus-score-file-multiple-match-alist)
2775         score-files)
2776     ;; if this group has been seen before, return the cached entry
2777     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2778         (cdr score-files)               ;ensures caching groups with no matches
2779       ;; handle the multiple match alist
2780       (while alist
2781         (when (string-match (caar alist) group)
2782           (setq score-files
2783                 (nconc score-files (copy-sequence (cdar alist)))))
2784         (setq alist (cdr alist)))
2785       (setq alist gnus-score-file-single-match-alist)
2786       ;; handle the single match alist
2787       (while alist
2788         (when (string-match (caar alist) group)
2789           ;; progn used just in case ("regexp") has no files
2790           ;; and score-files is still nil.  -sj
2791           ;; this can be construed as a "stop searching here" feature :>
2792           ;; and used to simplify regexps in the single-alist
2793           (setq score-files
2794                 (nconc score-files (copy-sequence (cdar alist))))
2795           (setq alist nil))
2796         (setq alist (cdr alist)))
2797       ;; cache the score files
2798       (push (cons group score-files) gnus-score-file-alist-cache)
2799       score-files)))
2800
2801 (defun gnus-all-score-files (&optional group)
2802   "Return a list of all score files for the current group."
2803   (let ((funcs gnus-score-find-score-files-function)
2804         (group (or group gnus-newsgroup-name))
2805         score-files)
2806     (when group
2807       ;; Make sure funcs is a list.
2808       (and funcs
2809            (not (listp funcs))
2810            (setq funcs (list funcs)))
2811       (when gnus-score-use-all-scores
2812         ;; Get the initial score files for this group.
2813         (when funcs
2814           (setq score-files (nreverse (gnus-score-find-alist group))))
2815         ;; Add any home adapt files.
2816         (let ((home (gnus-home-score-file group t)))
2817           (when home
2818             (push home score-files)
2819             (setq gnus-newsgroup-adaptive-score-file home)))
2820         ;; Check whether there is a `adapt-file' group parameter.
2821         (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2822           (when param-file
2823             (push param-file score-files)
2824             (setq gnus-newsgroup-adaptive-score-file param-file))))
2825       ;; Go through all the functions for finding score files (or actual
2826       ;; scores) and add them to a list.
2827       (while funcs
2828         (when (functionp (car funcs))
2829           (setq score-files
2830                 (append score-files
2831                         (nreverse (funcall (car funcs) group)))))
2832         (setq funcs (cdr funcs)))
2833       (when gnus-score-use-all-scores
2834         ;; Add any home score files.
2835         (let ((home (gnus-home-score-file group)))
2836           (when home
2837             (push home score-files)))
2838         ;; Check whether there is a `score-file' group parameter.
2839         (let ((param-file (gnus-group-find-parameter group 'score-file)))
2840           (when param-file
2841             (push param-file score-files))))
2842       ;; Expand all files names.
2843       (let ((files score-files))
2844         (while files
2845           (when (stringp (car files))
2846             (setcar files (expand-file-name
2847                            (car files) gnus-kill-files-directory)))
2848           (pop files)))
2849       (setq score-files (nreverse score-files))
2850       ;; Remove any duplicate score files.
2851       (while (and score-files
2852                   (member (car score-files) (cdr score-files)))
2853         (pop score-files))
2854       (let ((files score-files))
2855         (while (cdr files)
2856           (if (member (cadr files) (cddr files))
2857               (setcdr files (cddr files))
2858             (pop files))))
2859       ;; Do the scoring if there are any score files for this group.
2860       score-files)))
2861
2862 (defun gnus-possibly-score-headers (&optional trace)
2863   "Do scoring if scoring is required."
2864   (let ((score-files (gnus-all-score-files)))
2865     (when score-files
2866       (gnus-score-headers score-files trace))))
2867
2868 (defun gnus-score-file-name (newsgroup &optional suffix)
2869   "Return the name of a score file for NEWSGROUP."
2870   (let ((suffix (or suffix gnus-score-file-suffix)))
2871     (nnheader-translate-file-chars
2872      (cond
2873       ((or (null newsgroup)
2874            (string-equal newsgroup ""))
2875        ;; The global score file is placed at top of the directory.
2876        (expand-file-name suffix gnus-kill-files-directory))
2877       ((gnus-use-long-file-name 'not-score)
2878        ;; Append ".SCORE" to newsgroup name.
2879        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2880                                  "." suffix)
2881                          gnus-kill-files-directory))
2882       (t
2883        ;; Place "SCORE" under the hierarchical directory.
2884        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2885                                  "/" suffix)
2886                          gnus-kill-files-directory))))))
2887
2888 (defun gnus-score-search-global-directories (files)
2889   "Scan all global score directories for score files."
2890   ;; Set the variable `gnus-internal-global-score-files' to all
2891   ;; available global score files.
2892   (interactive (list gnus-global-score-files))
2893   (let (out)
2894     (while files
2895       ;; #### /$ Unix-specific?
2896       (if (file-directory-p (car files))
2897           (setq out (nconc (directory-files
2898                             (car files) t
2899                             (concat (gnus-score-file-regexp) "$"))))
2900         (push (car files) out))
2901       (setq files (cdr files)))
2902     (setq gnus-internal-global-score-files out)))
2903
2904 (defun gnus-score-default-fold-toggle ()
2905   "Toggle folding for new score file entries."
2906   (interactive)
2907   (setq gnus-score-default-fold (not gnus-score-default-fold))
2908   (if gnus-score-default-fold
2909       (gnus-message 1 "New score file entries will be case insensitive.")
2910     (gnus-message 1 "New score file entries will be case sensitive.")))
2911
2912 ;;; Home score file.
2913
2914 (defun gnus-home-score-file (group &optional adapt)
2915   "Return the home score file for GROUP.
2916 If ADAPT, return the home adaptive file instead."
2917   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2918         elem found)
2919     ;; Make sure we have a list.
2920     (unless (listp list)
2921       (setq list (list list)))
2922     ;; Go through the list and look for matches.
2923     (while (and (not found)
2924                 (setq elem (pop list)))
2925       (setq found
2926             (cond
2927              ;; Simple string.
2928              ((stringp elem)
2929               elem)
2930              ;; Function.
2931              ((functionp elem)
2932               (funcall elem group))
2933              ;; Regexp-file cons.
2934              ((consp elem)
2935               (when (string-match (gnus-globalify-regexp (car elem)) group)
2936                 (replace-match (cadr elem) t nil group))))))
2937     (when found
2938       (setq found (nnheader-translate-file-chars found))
2939       (if (file-name-absolute-p found)
2940           found
2941         (nnheader-concat gnus-kill-files-directory found)))))
2942
2943 (defun gnus-hierarchial-home-score-file (group)
2944   "Return the score file of the top-level hierarchy of GROUP."
2945   (if (string-match "^[^.]+\\." group)
2946       (concat (match-string 0 group) gnus-score-file-suffix)
2947     ;; Group name without any dots.
2948     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2949             gnus-score-file-suffix)))
2950
2951 (defun gnus-hierarchial-home-adapt-file (group)
2952   "Return the adapt file of the top-level hierarchy of GROUP."
2953   (if (string-match "^[^.]+\\." group)
2954       (concat (match-string 0 group) gnus-adaptive-file-suffix)
2955     ;; Group name without any dots.
2956     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2957             gnus-adaptive-file-suffix)))
2958
2959 (defun gnus-current-home-score-file (group)
2960   "Return the \"current\" regular score file."
2961   (car (nreverse (gnus-score-find-alist group))))
2962
2963 ;;;
2964 ;;; Score decays
2965 ;;;
2966
2967 (defun gnus-decay-score (score)
2968   "Decay SCORE according to `gnus-score-decay-constant' and `gnus-score-decay-scale'."
2969   (let ((n (- score
2970               (* (if (< score 0) -1 1)
2971                  (min (abs score)
2972                       (max gnus-score-decay-constant
2973                            (* (abs score)
2974                               gnus-score-decay-scale)))))))
2975     (if (and (featurep 'xemacs)
2976              ;; XEmacs' floor can handle only the floating point
2977              ;; number below the half of the maximum integer.
2978              (> (abs n) (lsh -1 -2)))
2979         (string-to-number
2980          (car (split-string (number-to-string n) "\\.")))
2981       (floor n))))
2982
2983 (defun gnus-decay-scores (alist day)
2984   "Decay non-permanent scores in ALIST."
2985   (let ((times (- (time-to-days (current-time)) day))
2986         kill entry updated score n)
2987     (unless (zerop times)               ;Done decays today already?
2988       (while (setq entry (pop alist))
2989         (when (stringp (car entry))
2990           (setq entry (cdr entry))
2991           (while (setq kill (pop entry))
2992             (when (nth 2 kill)
2993               (setq updated t)
2994               (setq score (or (nth 1 kill)
2995                               gnus-score-interactive-default-score)
2996                     n times)
2997               (while (natnump (decf n))
2998                 (setq score (funcall gnus-decay-score-function score)))
2999               (setcdr kill (cons score
3000                                  (cdr (cdr kill)))))))))
3001     ;; Return whether this score file needs to be saved.  By Je-haysuss!
3002     updated))
3003
3004 (defun gnus-score-regexp-bad-p (regexp)
3005   "Test whether REGEXP is safe for Gnus scoring.
3006 A regexp is unsafe if it matches newline or a buffer boundary.
3007
3008 If the regexp is good, return nil.  If the regexp is bad, return a
3009 cons cell (SYM . STRING), where the symbol SYM is `new' or `bad'.
3010 In the `new' case, the string is a safe replacement for REGEXP.
3011 In the `bad' case, the string is a unsafe subexpression of REGEXP,
3012 and we do not have a simple replacement to suggest.
3013
3014 See Info node `(gnus)Scoring Tips' for examples of good regular expressions."
3015   (let (case-fold-search)
3016     (and
3017      ;; First, try a relatively fast necessary condition.
3018      ;; Notice ranges (like [^:] or [\t-\r]), \s>, \Sw, \W, \', \`:
3019      (string-match "\n\\|\\\\[SsW`']\\|\\[\\^\\|[\0-\n]-" regexp)
3020      ;; Now break the regexp into tokens, and check each:
3021      (let ((tail regexp)                ; remaining regexp to check
3022            tok                          ; current token
3023            bad                          ; nil, or bad subexpression
3024            new                          ; nil, or replacement regexp so far
3025            end)                         ; length of current token
3026        (while (and (not bad)
3027                    (string-match
3028                     "\\`\\(\\\\[sS]?.\\|\\[\\^?]?[^]]*]\\|[^\\]\\)"
3029                     tail))
3030          (setq end (match-end 0)
3031                tok (substring tail 0 end)
3032                tail (substring tail end))
3033          (if;; Is token `bad' (matching newline or buffer ends)?
3034              (or (member tok '("\n" "\\W" "\\`" "\\'"))
3035                  ;; This next handles "[...]", "\\s.", and "\\S.":
3036                  (and (> end 2) (string-match tok "\n")))
3037              (let ((newtok
3038                     ;; Try to suggest a replacement for tok ...
3039                     (cond ((string-equal tok "\\`") "^") ; or "\\(^\\)"
3040                           ((string-equal tok "\\'") "$") ; or "\\($\\)"
3041                           ((string-match "\\[\\^" tok) ; very common
3042                            (concat (substring tok 0 -1) "\n]")))))
3043                (if newtok
3044                    (setq new
3045                          (concat
3046                           (or new
3047                               ;; good prefix so far:
3048                               (substring regexp 0 (- (+ (length tail) end))))
3049                           newtok))
3050                  ;; No replacement idea, so give up:
3051                  (setq bad tok)))
3052            ;; tok is good, may need to extend new
3053            (and new (setq new (concat new tok)))))
3054        ;; Now return a value:
3055        (cond
3056         (bad (cons 'bad bad))
3057         (new (cons 'new new))
3058         (t nil))))))
3059
3060 (provide 'gnus-score)
3061
3062 ;;; gnus-score.el ends here