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