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