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