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