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