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