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