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