*** empty log message ***
[gnus] / lisp / gnus-score.el
1 ;;; gnus-score.el --- scoring code for Gnus
2 ;; Copyright (C) 1995,96,97,98 Free Software Foundation, Inc.
3
4 ;; Author: Per Abrahamsen <amanda@iesd.auc.dk>
5 ;;      Lars Magne Ingebrigtsen <larsi@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          ;; This is a kludge; yes...
637          (cond
638           ((eq gnus-score-find-score-files-function
639                'gnus-score-find-hierarchical)
640            (gnus-score-file-name ""))
641           ((eq gnus-score-find-score-files-function 'gnus-score-find-single)
642            current-score-file)
643           (t
644            (gnus-score-file-name "all"))))))
645     
646     (gnus-summary-score-entry
647      (nth 1 entry)                      ; Header
648      match                              ; Match
649      type                               ; Type
650      (if (eq score 's) nil score)       ; Score
651      (if (eq temporary 'perm)           ; Temp
652          nil
653        temporary)
654      (not (nth 3 entry)))               ; Prompt
655
656     (when (eq symp 'a)
657       ;; We change the score file back to the previous one.
658       (save-excursion
659         (set-buffer gnus-summary-buffer)
660         (gnus-score-load-file current-score-file)))))
661
662 (defun gnus-score-insert-help (string alist idx)
663   (setq gnus-score-help-winconf (current-window-configuration))
664   (save-excursion
665     (set-buffer (get-buffer-create "*Score Help*"))
666     (buffer-disable-undo (current-buffer))
667     (delete-windows-on (current-buffer))
668     (erase-buffer)
669     (insert string ":\n\n")
670     (let ((max -1)
671           (list alist)
672           (i 0)
673           n width pad format)
674       ;; find the longest string to display
675       (while list
676         (setq n (length (nth idx (car list))))
677         (unless (> max n)
678           (setq max n))
679         (setq list (cdr list)))
680       (setq max (+ max 4))              ; %c, `:', SPACE, a SPACE at end
681       (setq n (/ (1- (window-width)) max)) ; items per line
682       (setq width (/ (1- (window-width)) n)) ; width of each item
683       ;; insert `n' items, each in a field of width `width'
684       (while alist
685         (if (< i n)
686             ()
687           (setq i 0)
688           (delete-char -1)              ; the `\n' takes a char
689           (insert "\n"))
690         (setq pad (- width 3))
691         (setq format (concat "%c: %-" (int-to-string pad) "s"))
692         (insert (format format (caar alist) (nth idx (car alist))))
693         (setq alist (cdr alist))
694         (setq i (1+ i))))
695     ;; display ourselves in a small window at the bottom
696     (gnus-appt-select-lowest-window)
697     (split-window)
698     (pop-to-buffer "*Score Help*")
699     (let ((window-min-height 1))
700       (shrink-window-if-larger-than-buffer))
701     (select-window (get-buffer-window gnus-summary-buffer))))
702
703 (defun gnus-summary-header (header &optional no-err)
704   ;; Return HEADER for current articles, or error.
705   (let ((article (gnus-summary-article-number))
706         headers)
707     (if article
708         (if (and (setq headers (gnus-summary-article-header article))
709                  (vectorp headers))
710             (aref headers (nth 1 (assoc header gnus-header-index)))
711           (if no-err
712               nil
713             (error "Pseudo-articles can't be scored")))
714       (if no-err
715           (error "No article on current line")
716         nil))))
717
718 (defun gnus-newsgroup-score-alist ()
719   (or
720    (let ((param-file (gnus-group-find-parameter
721                       gnus-newsgroup-name 'score-file)))
722      (when param-file
723        (gnus-score-load param-file)))
724    (gnus-score-load
725     (gnus-score-file-name gnus-newsgroup-name)))
726   gnus-score-alist)
727
728 (defsubst gnus-score-get (symbol &optional alist)
729   ;; Get SYMBOL's definition in ALIST.
730   (cdr (assoc symbol
731               (or alist
732                   gnus-score-alist
733                   (gnus-newsgroup-score-alist)))))
734
735 (defun gnus-summary-score-entry (header match type score date
736                                         &optional prompt silent)
737   "Enter score file entry.
738 HEADER is the header being scored.
739 MATCH is the string we are looking for.
740 TYPE is the match type: substring, regexp, exact, fuzzy.
741 SCORE is the score to add.
742 DATE is the expire date, or nil for no expire, or 'now for immediate expire.
743 If optional argument `PROMPT' is non-nil, allow user to edit match.
744 If optional argument `SILENT' is nil, show effect of score entry."
745   (interactive
746    (list (completing-read "Header: "
747                           gnus-header-index
748                           (lambda (x) (fboundp (nth 2 x)))
749                           t)
750          (read-string "Match: ")
751          (if (y-or-n-p "Use regexp match? ") 'r 's)
752          (and current-prefix-arg
753               (prefix-numeric-value current-prefix-arg))
754          (cond ((not (y-or-n-p "Add to score file? "))
755                 'now)
756                ((y-or-n-p "Expire kill? ")
757                 (current-time-string))
758                (t nil))))
759   ;; Regexp is the default type.
760   (when (eq type t)
761     (setq type 'r))
762   ;; Simplify matches...
763   (cond ((or (eq type 'r) (eq type 's) (eq type nil))
764          (setq match (if match (gnus-simplify-subject-re match) "")))
765         ((eq type 'f)
766          (setq match (gnus-simplify-subject-fuzzy match))))
767   (let ((score (gnus-score-default score))
768         (header (format "%s" (downcase header)))
769         new)
770     (when prompt
771       (setq match (read-string
772                    (format "Match %s on %s, %s: "
773                            (cond ((eq date 'now)
774                                   "now")
775                                  ((stringp date)
776                                   "temp")
777                                  (t "permanent"))
778                            header
779                            (if (< score 0) "lower" "raise"))
780                    (if (numberp match)
781                        (int-to-string match)
782                      match))))
783
784     ;; Get rid of string props.
785     (setq match (format "%s" match))
786
787     ;; If this is an integer comparison, we transform from string to int.
788     (when (eq (nth 2 (assoc header gnus-header-index)) 'gnus-score-integer)
789       (setq match (string-to-int match)))
790
791     (unless (eq date 'now)
792       ;; Add the score entry to the score file.
793       (when (= score gnus-score-interactive-default-score)
794         (setq score nil))
795       (let ((old (gnus-score-get header))
796             elem)
797         (setq new
798               (cond
799                (type
800                 (list match score
801                       (and date (if (numberp date) date
802                                   (gnus-day-number date)))
803                       type))
804                (date (list match score (gnus-day-number date)))
805                (score (list match score))
806                (t (list match))))
807         ;; We see whether we can collapse some score entries.
808         ;; This isn't quite correct, because there may be more elements
809         ;; later on with the same key that have matching elems...  Hm.
810         (if (and old
811                  (setq elem (assoc match old))
812                  (eq (nth 3 elem) (nth 3 new))
813                  (or (and (numberp (nth 2 elem)) (numberp (nth 2 new)))
814                      (and (not (nth 2 elem)) (not (nth 2 new)))))
815             ;; Yup, we just add this new score to the old elem.
816             (setcar (cdr elem) (+ (or (nth 1 elem)
817                                       gnus-score-interactive-default-score)
818                                   (or (nth 1 new)
819                                       gnus-score-interactive-default-score)))
820           ;; Nope, we have to add a new elem.
821           (gnus-score-set header (if old (cons new old) (list new))))
822         (gnus-score-set 'touched '(t))))
823
824     ;; Score the current buffer.
825     (unless silent
826       (if (and (>= (nth 1 (assoc header gnus-header-index)) 0)
827                (eq (nth 2 (assoc header gnus-header-index))
828                    'gnus-score-string))
829           (gnus-summary-score-effect header match type score)
830         (gnus-summary-rescore)))
831
832     ;; Return the new scoring rule.
833     new))
834
835 (defun gnus-summary-score-effect (header match type score)
836   "Simulate the effect of a score file entry.
837 HEADER is the header being scored.
838 MATCH is the string we are looking for.
839 TYPE is the score type.
840 SCORE is the score to add."
841   (interactive (list (completing-read "Header: "
842                                       gnus-header-index
843                                       (lambda (x) (fboundp (nth 2 x)))
844                                       t)
845                      (read-string "Match: ")
846                      (y-or-n-p "Use regexp match? ")
847                      (prefix-numeric-value current-prefix-arg)))
848   (save-excursion
849     (unless (and (stringp match) (> (length match) 0))
850       (error "No match"))
851     (goto-char (point-min))
852     (let ((regexp (cond ((eq type 'f)
853                          (gnus-simplify-subject-fuzzy match))
854                         ((eq type 'r)
855                          match)
856                         ((eq type 'e)
857                          (concat "\\`" (regexp-quote match) "\\'"))
858                         (t
859                          (regexp-quote match)))))
860       (while (not (eobp))
861         (let ((content (gnus-summary-header header 'noerr))
862               (case-fold-search t))
863           (and content
864                (when (if (eq type 'f)
865                          (string-equal (gnus-simplify-subject-fuzzy content)
866                                        regexp)
867                        (string-match regexp content))
868                  (gnus-summary-raise-score score))))
869         (beginning-of-line 2))))
870   (gnus-set-mode-line 'summary))
871
872 (defun gnus-summary-score-crossposting (score date)
873   ;; Enter score file entry for current crossposting.
874   ;; SCORE is the score to add.
875   ;; DATE is the expire date.
876   (let ((xref (gnus-summary-header "xref"))
877         (start 0)
878         group)
879     (unless xref
880       (error "This article is not crossposted"))
881     (while (string-match " \\([^ \t]+\\):" xref start)
882       (setq start (match-end 0))
883       (when (not (string=
884                   (setq group
885                         (substring xref (match-beginning 1) (match-end 1)))
886                   gnus-newsgroup-name))
887         (gnus-summary-score-entry
888          "xref" (concat " " group ":") nil score date t)))))
889
890 \f
891 ;;;
892 ;;; Gnus Score Files
893 ;;;
894
895 ;; All score code written by Per Abrahamsen <abraham@iesd.auc.dk>.
896
897 ;; Added by Per Abrahamsen <amanda@iesd.auc.dk>.
898 (defun gnus-score-set-mark-below (score)
899   "Automatically mark articles with score below SCORE as read."
900   (interactive
901    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
902              (string-to-int (read-string "Mark below: ")))))
903   (setq score (or score gnus-summary-default-score 0))
904   (gnus-score-set 'mark (list score))
905   (gnus-score-set 'touched '(t))
906   (setq gnus-summary-mark-below score)
907   (gnus-score-update-lines))
908
909 (defun gnus-score-update-lines ()
910   "Update all lines in the summary buffer."
911   (save-excursion
912     (goto-char (point-min))
913     (while (not (eobp))
914       (gnus-summary-update-line)
915       (forward-line 1))))
916
917 (defun gnus-score-update-all-lines ()
918   "Update all lines in the summary buffer, even the hidden ones."
919   (save-excursion
920     (goto-char (point-min))
921     (let (hidden)
922       (while (not (eobp))
923         (when (gnus-summary-show-thread)
924           (push (point) hidden))
925         (gnus-summary-update-line)
926         (forward-line 1))
927       ;; Re-hide the hidden threads.
928       (while hidden
929         (goto-char (pop hidden))
930         (gnus-summary-hide-thread)))))
931
932 (defun gnus-score-set-expunge-below (score)
933   "Automatically expunge articles with score below SCORE."
934   (interactive
935    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
936              (string-to-int (read-string "Set expunge below: ")))))
937   (setq score (or score gnus-summary-default-score 0))
938   (gnus-score-set 'expunge (list score))
939   (gnus-score-set 'touched '(t)))
940
941 (defun gnus-score-followup-article (&optional score)
942   "Add SCORE to all followups to the article in the current buffer."
943   (interactive "P")
944   (setq score (gnus-score-default score))
945   (when (gnus-buffer-live-p gnus-summary-buffer)
946     (save-excursion
947       (save-restriction
948         (message-narrow-to-headers)
949         (let ((id (mail-fetch-field "message-id")))
950           (when id
951             (set-buffer gnus-summary-buffer)
952             (gnus-summary-score-entry
953              "references" (concat id "[ \t]*$") 'r
954              score (current-time-string) nil t)))))))
955
956 (defun gnus-score-followup-thread (&optional score)
957   "Add SCORE to all later articles in the thread the current buffer is part of."
958   (interactive "P")
959   (setq score (gnus-score-default score))
960   (when (gnus-buffer-live-p gnus-summary-buffer)
961     (save-excursion
962       (save-restriction
963         (goto-char (point-min))
964         (let ((id (mail-fetch-field "message-id")))
965           (when id
966             (set-buffer gnus-summary-buffer)
967             (gnus-summary-score-entry
968              "references" id 's
969              score (current-time-string))))))))
970
971 (defun gnus-score-set (symbol value &optional alist)
972   ;; Set SYMBOL to VALUE in ALIST.
973   (let* ((alist
974           (or alist
975               gnus-score-alist
976               (gnus-newsgroup-score-alist)))
977          (entry (assoc symbol alist)))
978     (cond ((gnus-score-get 'read-only alist)
979            ;; This is a read-only score file, so we do nothing.
980            )
981           (entry
982            (setcdr entry value))
983           ((null alist)
984            (error "Empty alist"))
985           (t
986            (setcdr alist
987                    (cons (cons symbol value) (cdr alist)))))))
988
989 (defun gnus-summary-raise-score (n)
990   "Raise the score of the current article by N."
991   (interactive "p")
992   (gnus-summary-set-score (+ (gnus-summary-article-score)
993                              (or n gnus-score-interactive-default-score ))))
994
995 (defun gnus-summary-set-score (n)
996   "Set the score of the current article to N."
997   (interactive "p")
998   (save-excursion
999     (gnus-summary-show-thread)
1000     (let ((buffer-read-only nil))
1001       ;; Set score.
1002       (gnus-summary-update-mark
1003        (if (= n (or gnus-summary-default-score 0)) ? 
1004          (if (< n (or gnus-summary-default-score 0))
1005              gnus-score-below-mark gnus-score-over-mark))
1006        'score))
1007     (let* ((article (gnus-summary-article-number))
1008            (score (assq article gnus-newsgroup-scored)))
1009       (if score (setcdr score n)
1010         (push (cons article n) gnus-newsgroup-scored)))
1011     (gnus-summary-update-line)))
1012
1013 (defun gnus-summary-current-score ()
1014   "Return the score of the current article."
1015   (interactive)
1016   (gnus-message 1 "%s" (gnus-summary-article-score)))
1017
1018 (defun gnus-score-change-score-file (file)
1019   "Change current score alist."
1020   (interactive
1021    (list (read-file-name "Change to score file: " gnus-kill-files-directory)))
1022   (gnus-score-load-file file)
1023   (gnus-set-mode-line 'summary))
1024
1025 (defvar gnus-score-edit-exit-function)
1026 (defun gnus-score-edit-current-scores (file)
1027   "Edit the current score alist."
1028   (interactive (list gnus-current-score-file))
1029   (if (not gnus-current-score-file)
1030       (error "No current score file")
1031     (let ((winconf (current-window-configuration)))
1032       (when (buffer-name gnus-summary-buffer)
1033         (gnus-score-save))
1034       (gnus-make-directory (file-name-directory file))
1035       (setq gnus-score-edit-buffer (find-file-noselect file))
1036       (gnus-configure-windows 'edit-score)
1037       (gnus-score-mode)
1038       (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1039       (make-local-variable 'gnus-prev-winconf)
1040       (setq gnus-prev-winconf winconf))
1041     (gnus-message
1042      4 (substitute-command-keys
1043         "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits"))))
1044
1045 (defun gnus-score-edit-file (file)
1046   "Edit a score file."
1047   (interactive
1048    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
1049   (gnus-make-directory (file-name-directory file))
1050   (when (buffer-name gnus-summary-buffer)
1051     (gnus-score-save))
1052   (let ((winconf (current-window-configuration)))
1053     (setq gnus-score-edit-buffer (find-file-noselect file))
1054     (gnus-configure-windows 'edit-score)
1055     (gnus-score-mode)
1056     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1057     (make-local-variable 'gnus-prev-winconf)
1058     (setq gnus-prev-winconf winconf))
1059   (gnus-message
1060    4 (substitute-command-keys
1061       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
1062
1063 (defun gnus-score-load-file (file)
1064   ;; Load score file FILE.  Returns a list a retrieved score-alists.
1065   (let* ((file (expand-file-name
1066                 (or (and (string-match
1067                           (concat "^" (expand-file-name
1068                                        gnus-kill-files-directory))
1069                           (expand-file-name file))
1070                          file)
1071                     (concat (file-name-as-directory gnus-kill-files-directory)
1072                             file))))
1073          (cached (assoc file gnus-score-cache))
1074          (global (member file gnus-internal-global-score-files))
1075          lists alist)
1076     (if cached
1077         ;; The score file was already loaded.
1078         (setq alist (cdr cached))
1079       ;; We load the score file.
1080       (setq gnus-score-alist nil)
1081       (setq alist (gnus-score-load-score-alist file))
1082       ;; We add '(touched) to the alist to signify that it hasn't been
1083       ;; touched (yet).
1084       (unless (assq 'touched alist)
1085         (push (list 'touched nil) alist))
1086       ;; If it is a global score file, we make it read-only.
1087       (and global
1088            (not (assq 'read-only alist))
1089            (push (list 'read-only t) alist))
1090       (push (cons file alist) gnus-score-cache))
1091     (let ((a alist)
1092           found)
1093       (while a
1094         ;; Downcase all header names.
1095         (when (stringp (caar a))
1096           (setcar (car a) (downcase (caar a)))
1097           (setq found t))
1098         (pop a))
1099       ;; If there are actual scores in the alist, we add it to the
1100       ;; return value of this function.
1101       (when found
1102         (setq lists (list alist))))
1103     ;; Treat the other possible atoms in the score alist.
1104     (let ((mark (car (gnus-score-get 'mark alist)))
1105           (expunge (car (gnus-score-get 'expunge alist)))
1106           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
1107           (files (gnus-score-get 'files alist))
1108           (exclude-files (gnus-score-get 'exclude-files alist))
1109           (orphan (car (gnus-score-get 'orphan alist)))
1110           (adapt (gnus-score-get 'adapt alist))
1111           (thread-mark-and-expunge
1112            (car (gnus-score-get 'thread-mark-and-expunge alist)))
1113           (adapt-file (car (gnus-score-get 'adapt-file alist)))
1114           (local (gnus-score-get 'local alist))
1115           (decay (car (gnus-score-get 'decay alist)))
1116           (eval (car (gnus-score-get 'eval alist))))
1117       ;; Perform possible decays.
1118       (when (and gnus-decay-scores
1119                  (or cached (file-exists-p file))
1120                  (or (not decay)
1121                      (gnus-decay-scores alist decay)))
1122         (gnus-score-set 'touched '(t) alist)
1123         (gnus-score-set 'decay (list (gnus-time-to-day (current-time)))))
1124       ;; We do not respect eval and files atoms from global score
1125       ;; files.
1126       (when (and files (not global))
1127         (setq lists (apply 'append lists
1128                            (mapcar (lambda (file)
1129                                      (gnus-score-load-file file))
1130                                    (if adapt-file (cons adapt-file files)
1131                                      files)))))
1132       (when (and eval (not global))
1133         (eval eval))
1134       ;; We then expand any exclude-file directives.
1135       (setq gnus-scores-exclude-files
1136             (nconc
1137              (apply
1138               'nconc
1139               (mapcar
1140                (lambda (sfile)
1141                  (list
1142                   (expand-file-name sfile (file-name-directory file))
1143                   (expand-file-name sfile gnus-kill-files-directory)))
1144                exclude-files))
1145              gnus-scores-exclude-files))
1146       (unless local
1147         (save-excursion
1148           (set-buffer gnus-summary-buffer)
1149           (while local
1150             (and (consp (car local))
1151                  (symbolp (caar local))
1152                  (progn
1153                    (make-local-variable (caar local))
1154                    (set (caar local) (nth 1 (car local)))))
1155             (setq local (cdr local)))))
1156       (when orphan
1157         (setq gnus-orphan-score orphan))
1158       (setq gnus-adaptive-score-alist
1159             (cond ((equal adapt '(t))
1160                    (setq gnus-newsgroup-adaptive t)
1161                    gnus-default-adaptive-score-alist)
1162                   ((equal adapt '(ignore))
1163                    (setq gnus-newsgroup-adaptive nil))
1164                   ((consp adapt)
1165                    (setq gnus-newsgroup-adaptive t)
1166                    adapt)
1167                   (t
1168                    ;;(setq gnus-newsgroup-adaptive gnus-use-adaptive-scoring)
1169                    gnus-default-adaptive-score-alist)))
1170       (setq gnus-thread-expunge-below
1171             (or thread-mark-and-expunge gnus-thread-expunge-below))
1172       (setq gnus-summary-mark-below
1173             (or mark mark-and-expunge gnus-summary-mark-below))
1174       (setq gnus-summary-expunge-below
1175             (or expunge mark-and-expunge gnus-summary-expunge-below))
1176       (setq gnus-newsgroup-adaptive-score-file
1177             (or adapt-file gnus-newsgroup-adaptive-score-file)))
1178     (setq gnus-current-score-file file)
1179     (setq gnus-score-alist alist)
1180     lists))
1181
1182 (defun gnus-score-load (file)
1183   ;; Load score FILE.
1184   (let ((cache (assoc file gnus-score-cache)))
1185     (if cache
1186         (setq gnus-score-alist (cdr cache))
1187       (setq gnus-score-alist nil)
1188       (gnus-score-load-score-alist file)
1189       (unless gnus-score-alist
1190         (setq gnus-score-alist (copy-alist '((touched nil)))))
1191       (push (cons file gnus-score-alist) gnus-score-cache))))
1192
1193 (defun gnus-score-remove-from-cache (file)
1194   (setq gnus-score-cache
1195         (delq (assoc file gnus-score-cache) gnus-score-cache)))
1196
1197 (defun gnus-score-load-score-alist (file)
1198   "Read score FILE."
1199   (let (alist)
1200     (if (not (file-readable-p file))
1201         ;; Couldn't read file.
1202         (setq gnus-score-alist nil)
1203       ;; Read file.
1204       (save-excursion
1205         (gnus-set-work-buffer)
1206         (insert-file-contents file)
1207         (goto-char (point-min))
1208         ;; Only do the loading if the score file isn't empty.
1209         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
1210           (setq alist
1211                 (condition-case ()
1212                     (read (current-buffer))
1213                   (error
1214                    (gnus-error 3.2 "Problem with score file %s" file))))))
1215       (if (eq (car alist) 'setq)
1216           ;; This is an old-style score file.
1217           (setq gnus-score-alist (gnus-score-transform-old-to-new alist))
1218         (setq gnus-score-alist alist))
1219       ;; Check the syntax of the score file.
1220       (setq gnus-score-alist
1221             (gnus-score-check-syntax gnus-score-alist file)))))
1222
1223 (defun gnus-score-check-syntax (alist file)
1224   "Check the syntax of the score ALIST."
1225   (cond
1226    ((null alist)
1227     nil)
1228    ((not (consp alist))
1229     (gnus-message 1 "Score file is not a list: %s" file)
1230     (ding)
1231     nil)
1232    (t
1233     (let ((a alist)
1234           sr err s type)
1235       (while (and a (not err))
1236         (setq
1237          err
1238          (cond
1239           ((not (listp (car a)))
1240            (format "Illegal score element %s in %s" (car a) file))
1241           ((stringp (caar a))
1242            (cond
1243             ((not (listp (setq sr (cdar a))))
1244              (format "Illegal header match %s in %s" (nth 1 (car a)) file))
1245             (t
1246              (setq type (caar a))
1247              (while (and sr (not err))
1248                (setq s (pop sr))
1249                (setq
1250                 err
1251                 (cond
1252                  ((if (member (downcase type) '("lines" "chars"))
1253                       (not (numberp (car s)))
1254                     (not (stringp (car s))))
1255                   (format "Illegal match %s in %s" (car s) file))
1256                  ((and (cadr s) (not (integerp (cadr s))))
1257                   (format "Non-integer score %s in %s" (cadr s) file))
1258                  ((and (caddr s) (not (integerp (caddr s))))
1259                   (format "Non-integer date %s in %s" (caddr s) file))
1260                  ((and (cadddr s) (not (symbolp (cadddr s))))
1261                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1262              err)))))
1263         (setq a (cdr a)))
1264       (if err
1265           (progn
1266             (ding)
1267             (gnus-message 3 err)
1268             (sit-for 2)
1269             nil)
1270         alist)))))
1271
1272 (defun gnus-score-transform-old-to-new (alist)
1273   (let* ((alist (nth 2 alist))
1274          out entry)
1275     (when (eq (car alist) 'quote)
1276       (setq alist (nth 1 alist)))
1277     (while alist
1278       (setq entry (car alist))
1279       (if (stringp (car entry))
1280           (let ((scor (cdr entry)))
1281             (push entry out)
1282             (while scor
1283               (setcar scor
1284                       (list (caar scor) (nth 2 (car scor))
1285                             (and (nth 3 (car scor))
1286                                  (gnus-day-number (nth 3 (car scor))))
1287                             (if (nth 1 (car scor)) 'r 's)))
1288               (setq scor (cdr scor))))
1289         (push (if (not (listp (cdr entry)))
1290                   (list (car entry) (cdr entry))
1291                 entry)
1292               out))
1293       (setq alist (cdr alist)))
1294     (cons (list 'touched t) (nreverse out))))
1295
1296 (defun gnus-score-save ()
1297   ;; Save all score information.
1298   (let ((cache gnus-score-cache)
1299         entry score file)
1300     (save-excursion
1301       (setq gnus-score-alist nil)
1302       (nnheader-set-temp-buffer " *Gnus Scores*")
1303       (while cache
1304         (current-buffer)
1305         (setq entry (pop cache)
1306               file (car entry)
1307               score (cdr entry))
1308         (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1309                 (gnus-score-get 'read-only score)
1310                 (and (file-exists-p file)
1311                      (not (file-writable-p file))))
1312             ()
1313           (setq score (setcdr entry (delq (assq 'touched score) score)))
1314           (erase-buffer)
1315           (let (emacs-lisp-mode-hook)
1316             (if (string-match
1317                  (concat (regexp-quote gnus-adaptive-file-suffix) "$")
1318                  file)
1319                 ;; This is an adaptive score file, so we do not run
1320                 ;; it through `pp'.  These files can get huge, and
1321                 ;; are not meant to be edited by human hands.
1322                 (gnus-prin1 score)
1323               ;; This is a normal score file, so we print it very
1324               ;; prettily.
1325               (pp score (current-buffer))))
1326           (gnus-make-directory (file-name-directory file))
1327           ;; If the score file is empty, we delete it.
1328           (if (zerop (buffer-size))
1329               (delete-file file)
1330             ;; There are scores, so we write the file.
1331             (when (file-writable-p file)
1332               (gnus-write-buffer file)
1333               (when gnus-score-after-write-file-function
1334                 (funcall gnus-score-after-write-file-function file)))))
1335         (and gnus-score-uncacheable-files
1336              (string-match gnus-score-uncacheable-files file)
1337              (gnus-score-remove-from-cache file)))
1338       (kill-buffer (current-buffer)))))
1339
1340 (defun gnus-score-load-files (score-files)
1341   "Load all score files in SCORE-FILES."
1342   ;; Load the score files.
1343   (let (scores)
1344     (while score-files
1345       (if (stringp (car score-files))
1346           ;; It is a string, which means that it's a score file name,
1347           ;; so we load the score file and add the score alist to
1348           ;; the list of alists.
1349           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1350         ;; It is an alist, so we just add it to the list directly.
1351         (setq scores (nconc (car score-files) scores)))
1352       (setq score-files (cdr score-files)))
1353     ;; Prune the score files that are to be excluded, if any.
1354     (when gnus-scores-exclude-files
1355       (let ((s scores)
1356             c)
1357         (while s
1358           (and (setq c (rassq (car s) gnus-score-cache))
1359                (member (car c) gnus-scores-exclude-files)
1360                (setq scores (delq (car s) scores)))
1361           (setq s (cdr s)))))
1362     scores))
1363
1364 (defun gnus-score-headers (score-files &optional trace)
1365   ;; Score `gnus-newsgroup-headers'.
1366   (let (scores news)
1367     ;; PLM: probably this is not the best place to clear orphan-score
1368     (setq gnus-orphan-score nil
1369           gnus-scores-articles nil
1370           gnus-scores-exclude-files nil
1371           scores (gnus-score-load-files score-files))
1372     (setq news scores)
1373     ;; Do the scoring.
1374     (while news
1375       (setq scores news
1376             news nil)
1377       (when (and gnus-summary-default-score
1378                  scores)
1379         (let* ((entries gnus-header-index)
1380                (now (gnus-day-number (current-time-string)))
1381                (expire (and gnus-score-expiry-days
1382                             (- now gnus-score-expiry-days)))
1383                (headers gnus-newsgroup-headers)
1384                (current-score-file gnus-current-score-file)
1385                entry header new)
1386           (gnus-message 5 "Scoring...")
1387           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1388           (while (setq header (pop headers))
1389             ;; WARNING: The assq makes the function O(N*S) while it could
1390             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1391             ;; and S is (length gnus-newsgroup-scored).
1392             (unless (assq (mail-header-number header) gnus-newsgroup-scored)
1393               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1394                     (cons (cons header (or gnus-summary-default-score 0))
1395                           gnus-scores-articles))))
1396
1397           (save-excursion
1398             (set-buffer (get-buffer-create "*Headers*"))
1399             (buffer-disable-undo (current-buffer))
1400             (when (gnus-buffer-live-p gnus-summary-buffer)
1401               (message-clone-locals gnus-summary-buffer))
1402
1403             ;; Set the global variant of this variable.
1404             (setq gnus-current-score-file current-score-file)
1405             ;; score orphans
1406             (when gnus-orphan-score
1407               (setq gnus-score-index
1408                     (nth 1 (assoc "references" gnus-header-index)))
1409               (gnus-score-orphans gnus-orphan-score))
1410             ;; Run each header through the score process.
1411             (while entries
1412               (setq entry (pop entries)
1413                     header (nth 0 entry)
1414                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1415               (when (< 0 (apply 'max (mapcar
1416                                       (lambda (score)
1417                                         (length (gnus-score-get header score)))
1418                                       scores)))
1419                 ;; Call the scoring function for this type of "header".
1420                 (when (setq new (funcall (nth 2 entry) scores header
1421                                          now expire trace))
1422                   (push new news))))
1423             ;; Remove the buffer.
1424             (kill-buffer (current-buffer)))
1425
1426           ;; Add articles to `gnus-newsgroup-scored'.
1427           (while gnus-scores-articles
1428             (when (or (/= gnus-summary-default-score
1429                           (cdar gnus-scores-articles))
1430                       gnus-save-score)
1431               (push (cons (mail-header-number (caar gnus-scores-articles))
1432                           (cdar gnus-scores-articles))
1433                     gnus-newsgroup-scored))
1434             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1435
1436           (let (score)
1437             (while (setq score (pop scores))
1438               (while score
1439                 (when (listp (caar score))
1440                   (gnus-score-advanced (car score) trace))
1441                 (pop score))))
1442
1443           (gnus-message 5 "Scoring...done"))))))
1444
1445
1446 (defun gnus-get-new-thread-ids (articles)
1447   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
1448         (refind gnus-score-index)
1449         id-list art this tref)
1450     (while articles
1451       (setq art (car articles)
1452             this (aref (car art) index)
1453             tref (aref (car art) refind)
1454             articles (cdr articles))
1455       (when (string-equal tref "")      ;no references line
1456         (push this id-list)))
1457     id-list))
1458
1459 ;; Orphan functions written by plm@atcmp.nl (Peter Mutsaers).
1460 (defun gnus-score-orphans (score)
1461   (let ((new-thread-ids (gnus-get-new-thread-ids gnus-scores-articles))
1462         alike articles art arts this last this-id)
1463
1464     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1465           articles gnus-scores-articles)
1466
1467     ;;more or less the same as in gnus-score-string
1468     (erase-buffer)
1469     (while articles
1470       (setq art (car articles)
1471             this (aref (car art) gnus-score-index)
1472             articles (cdr articles))
1473       ;;completely skip if this is empty (not a child, so not an orphan)
1474       (when (not (string= this ""))
1475         (if (equal last this)
1476             ;; O(N*H) cons-cells used here, where H is the number of
1477             ;; headers.
1478             (push art alike)
1479           (when last
1480             ;; Insert the line, with a text property on the
1481             ;; terminating newline referring to the articles with
1482             ;; this line.
1483             (insert last ?\n)
1484             (put-text-property (1- (point)) (point) 'articles alike))
1485           (setq alike (list art)
1486                 last this))))
1487     (when last                          ; Bwadr, duplicate code.
1488       (insert last ?\n)
1489       (put-text-property (1- (point)) (point) 'articles alike))
1490
1491     ;; PLM: now delete those lines that contain an entry from new-thread-ids
1492     (while new-thread-ids
1493       (setq this-id (car new-thread-ids)
1494             new-thread-ids (cdr new-thread-ids))
1495       (goto-char (point-min))
1496       (while (search-forward this-id nil t)
1497         ;; found a match.  remove this line
1498         (beginning-of-line)
1499         (kill-line 1)))
1500
1501     ;; now for each line: update its articles with score by moving to
1502     ;; every end-of-line in the buffer and read the articles property
1503     (goto-char (point-min))
1504     (while (eq 0 (progn
1505                    (end-of-line)
1506                    (setq arts (get-text-property (point) 'articles))
1507                    (while arts
1508                      (setq art (car arts)
1509                            arts (cdr arts))
1510                      (setcdr art (+ score (cdr art))))
1511                    (forward-line))))))
1512
1513
1514 (defun gnus-score-integer (scores header now expire &optional trace)
1515   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1516         entries alist)
1517
1518     ;; Find matches.
1519     (while scores
1520       (setq alist (car scores)
1521             scores (cdr scores)
1522             entries (assoc header alist))
1523       (while (cdr entries)              ;First entry is the header index.
1524         (let* ((rest (cdr entries))
1525                (kill (car rest))
1526                (match (nth 0 kill))
1527                (type (or (nth 3 kill) '>))
1528                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1529                (date (nth 2 kill))
1530                (found nil)
1531                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1532                                    (eq type '>=) (eq type '=))
1533                                type
1534                              (error "Illegal match type: %s" type)))
1535                (articles gnus-scores-articles))
1536           ;; Instead of doing all the clever stuff that
1537           ;; `gnus-score-string' does to minimize searches and stuff,
1538           ;; I will assume that people generally will put so few
1539           ;; matches on numbers that any cleverness will take more
1540           ;; time than one would gain.
1541           (while articles
1542             (when (funcall match-func
1543                            (or (aref (caar articles) gnus-score-index) 0)
1544                            match)
1545               (when trace
1546                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1547                       gnus-score-trace))
1548               (setq found t)
1549               (setcdr (car articles) (+ score (cdar articles))))
1550             (setq articles (cdr articles)))
1551           ;; Update expire date
1552           (cond ((null date))           ;Permanent entry.
1553                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1554                  (gnus-score-set 'touched '(t) alist)
1555                  (setcar (nthcdr 2 kill) now))
1556                 ((and expire (< date expire)) ;Old entry, remove.
1557                  (gnus-score-set 'touched '(t) alist)
1558                  (setcdr entries (cdr rest))
1559                  (setq rest entries)))
1560           (setq entries rest)))))
1561   nil)
1562
1563 (defun gnus-score-date (scores header now expire &optional trace)
1564   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1565         entries alist match match-func article)
1566
1567     ;; Find matches.
1568     (while scores
1569       (setq alist (car scores)
1570             scores (cdr scores)
1571             entries (assoc header alist))
1572       (while (cdr entries)              ;First entry is the header index.
1573         (let* ((rest (cdr entries))
1574                (kill (car rest))
1575                (type (or (nth 3 kill) 'before))
1576                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1577                (date (nth 2 kill))
1578                (found nil)
1579                (articles gnus-scores-articles)
1580                l)
1581           (cond
1582            ((eq type 'after)
1583             (setq match-func 'string<
1584                   match (gnus-date-iso8601 (nth 0 kill))))
1585            ((eq type 'before)
1586             (setq match-func 'gnus-string>
1587                   match (gnus-date-iso8601 (nth 0 kill))))
1588            ((eq type 'at)
1589             (setq match-func 'string=
1590                   match (gnus-date-iso8601 (nth 0 kill))))
1591            ((eq type 'regexp)
1592             (setq match-func 'string-match
1593                   match (nth 0 kill)))
1594            (t (error "Illegal match type: %s" type)))
1595           ;; Instead of doing all the clever stuff that
1596           ;; `gnus-score-string' does to minimize searches and stuff,
1597           ;; I will assume that people generally will put so few
1598           ;; matches on numbers that any cleverness will take more
1599           ;; time than one would gain.
1600           (while (setq article (pop articles))
1601             (when (and
1602                    (setq l (aref (car article) gnus-score-index))
1603                    (funcall match-func match (gnus-date-iso8601 l)))
1604               (when trace
1605                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1606                       gnus-score-trace))
1607               (setq found t)
1608               (setcdr article (+ score (cdr article)))))
1609           ;; Update expire date
1610           (cond ((null date))           ;Permanent entry.
1611                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1612                  (gnus-score-set 'touched '(t) alist)
1613                  (setcar (nthcdr 2 kill) now))
1614                 ((and expire (< date expire)) ;Old entry, remove.
1615                  (gnus-score-set 'touched '(t) alist)
1616                  (setcdr entries (cdr rest))
1617                  (setq rest entries)))
1618           (setq entries rest)))))
1619   nil)
1620
1621 (defun gnus-score-body (scores header now expire &optional trace)
1622   (save-excursion
1623     (setq gnus-scores-articles
1624           (sort gnus-scores-articles
1625                 (lambda (a1 a2)
1626                   (< (mail-header-number (car a1))
1627                      (mail-header-number (car a2))))))
1628     (set-buffer nntp-server-buffer)
1629     (save-restriction
1630       (let* ((buffer-read-only nil)
1631              (articles gnus-scores-articles)
1632              (all-scores scores)
1633              (request-func (cond ((string= "head" header)
1634                                   'gnus-request-head)
1635                                  ((string= "body" header)
1636                                   'gnus-request-body)
1637                                  (t 'gnus-request-article)))
1638              entries alist ofunc article last)
1639         (when articles
1640           (setq last (mail-header-number (caar (last articles))))
1641           ;; Not all backends support partial fetching.  In that case,
1642           ;; we just fetch the entire article.
1643           (unless (gnus-check-backend-function
1644                    (and (string-match "^gnus-" (symbol-name request-func))
1645                         (intern (substring (symbol-name request-func)
1646                                            (match-end 0))))
1647                    gnus-newsgroup-name)
1648             (setq ofunc request-func)
1649             (setq request-func 'gnus-request-article))
1650           (while articles
1651             (setq article (mail-header-number (caar articles)))
1652             (gnus-message 7 "Scoring on article %s of %s..." article last)
1653             (when (funcall request-func article gnus-newsgroup-name)
1654               (widen)
1655               (goto-char (point-min))
1656               ;; If just parts of the article is to be searched, but the
1657               ;; backend didn't support partial fetching, we just narrow
1658               ;; to the relevant parts.
1659               (when ofunc
1660                 (if (eq ofunc 'gnus-request-head)
1661                     (narrow-to-region
1662                      (point)
1663                      (or (search-forward "\n\n" nil t) (point-max)))
1664                   (narrow-to-region
1665                    (or (search-forward "\n\n" nil t) (point))
1666                    (point-max))))
1667               (setq scores all-scores)
1668               ;; Find matches.
1669               (while scores
1670                 (setq alist (pop scores)
1671                       entries (assoc header alist))
1672                 (while (cdr entries)    ;First entry is the header index.
1673                   (let* ((rest (cdr entries))
1674                          (kill (car rest))
1675                          (match (nth 0 kill))
1676                          (type (or (nth 3 kill) 's))
1677                          (score (or (nth 1 kill)
1678                                     gnus-score-interactive-default-score))
1679                          (date (nth 2 kill))
1680                          (found nil)
1681                          (case-fold-search
1682                           (not (or (eq type 'R) (eq type 'S)
1683                                    (eq type 'Regexp) (eq type 'String))))
1684                          (search-func
1685                           (cond ((or (eq type 'r) (eq type 'R)
1686                                      (eq type 'regexp) (eq type 'Regexp))
1687                                  're-search-forward)
1688                                 ((or (eq type 's) (eq type 'S)
1689                                      (eq type 'string) (eq type 'String))
1690                                  'search-forward)
1691                                 (t
1692                                  (error "Illegal match type: %s" type)))))
1693                     (goto-char (point-min))
1694                     (when (funcall search-func match nil t)
1695                       ;; Found a match, update scores.
1696                       (setcdr (car articles) (+ score (cdar articles)))
1697                       (setq found t)
1698                       (when trace
1699                         (push
1700                          (cons (car-safe (rassq alist gnus-score-cache)) kill)
1701                          gnus-score-trace)))
1702                     ;; Update expire date
1703                     (unless trace
1704                       (cond
1705                        ((null date))    ;Permanent entry.
1706                        ((and found gnus-update-score-entry-dates)
1707                         ;; Match, update date.
1708                         (gnus-score-set 'touched '(t) alist)
1709                         (setcar (nthcdr 2 kill) now))
1710                        ((and expire (< date expire)) ;Old entry, remove.
1711                         (gnus-score-set 'touched '(t) alist)
1712                         (setcdr entries (cdr rest))
1713                         (setq rest entries))))
1714                     (setq entries rest)))))
1715             (setq articles (cdr articles)))))))
1716   nil)
1717
1718 (defun gnus-score-thread (scores header now expire &optional trace)
1719   (gnus-score-followup scores header now expire trace t))
1720
1721 (defun gnus-score-followup (scores header now expire &optional trace thread)
1722   ;; Insert the unique article headers in the buffer.
1723   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1724         (current-score-file gnus-current-score-file)
1725         (all-scores scores)
1726         ;; gnus-score-index is used as a free variable.
1727         alike last this art entries alist articles
1728         new news)
1729
1730     ;; Change score file to the adaptive score file.  All entries that
1731     ;; this function makes will be put into this file.
1732     (save-excursion
1733       (set-buffer gnus-summary-buffer)
1734       (gnus-score-load-file
1735        (or gnus-newsgroup-adaptive-score-file
1736            (gnus-score-file-name
1737             gnus-newsgroup-name gnus-adaptive-file-suffix))))
1738
1739     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1740           articles gnus-scores-articles)
1741
1742     (erase-buffer)
1743     (while articles
1744       (setq art (car articles)
1745             this (aref (car art) gnus-score-index)
1746             articles (cdr articles))
1747       (if (equal last this)
1748           (push art alike)
1749         (when last
1750           (insert last ?\n)
1751           (put-text-property (1- (point)) (point) 'articles alike))
1752         (setq alike (list art)
1753               last this)))
1754     (when last                          ; Bwadr, duplicate code.
1755       (insert last ?\n)
1756       (put-text-property (1- (point)) (point) 'articles alike))
1757
1758     ;; Find matches.
1759     (while scores
1760       (setq alist (car scores)
1761             scores (cdr scores)
1762             entries (assoc header alist))
1763       (while (cdr entries)              ;First entry is the header index.
1764         (let* ((rest (cdr entries))
1765                (kill (car rest))
1766                (match (nth 0 kill))
1767                (type (or (nth 3 kill) 's))
1768                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1769                (date (nth 2 kill))
1770                (found nil)
1771                (mt (aref (symbol-name type) 0))
1772                (case-fold-search
1773                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1774                (dmt (downcase mt))
1775                (search-func
1776                 (cond ((= dmt ?r) 're-search-forward)
1777                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1778                       (t (error "Illegal match type: %s" type))))
1779                arts art)
1780           (goto-char (point-min))
1781           (if (= dmt ?e)
1782               (while (funcall search-func match nil t)
1783                 (and (= (progn (beginning-of-line) (point))
1784                         (match-beginning 0))
1785                      (= (progn (end-of-line) (point))
1786                         (match-end 0))
1787                      (progn
1788                        (setq found (setq arts (get-text-property
1789                                                (point) 'articles)))
1790                        ;; Found a match, update scores.
1791                        (while arts
1792                          (setq art (car arts)
1793                                arts (cdr arts))
1794                          (gnus-score-add-followups
1795                           (car art) score all-scores thread))))
1796                 (end-of-line))
1797             (while (funcall search-func match nil t)
1798               (end-of-line)
1799               (setq found (setq arts (get-text-property (point) 'articles)))
1800               ;; Found a match, update scores.
1801               (while (setq art (pop arts))
1802                 (when (setq new (gnus-score-add-followups
1803                                  (car art) score all-scores thread))
1804                   (push new news)))))
1805           ;; Update expire date
1806           (cond ((null date))           ;Permanent entry.
1807                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1808                  (gnus-score-set 'touched '(t) alist)
1809                  (setcar (nthcdr 2 kill) now))
1810                 ((and expire (< date expire)) ;Old entry, remove.
1811                  (gnus-score-set 'touched '(t) alist)
1812                  (setcdr entries (cdr rest))
1813                  (setq rest entries)))
1814           (setq entries rest))))
1815     ;; We change the score file back to the previous one.
1816     (save-excursion
1817       (set-buffer gnus-summary-buffer)
1818       (gnus-score-load-file current-score-file))
1819     (list (cons "references" news))))
1820
1821 (defun gnus-score-add-followups (header score scores &optional thread)
1822   "Add a score entry to the adapt file."
1823   (save-excursion
1824     (set-buffer gnus-summary-buffer)
1825     (let* ((id (mail-header-id header))
1826            (scores (car scores))
1827            entry dont)
1828       ;; Don't enter a score if there already is one.
1829       (while (setq entry (pop scores))
1830         (and (equal "references" (car entry))
1831              (or (null (nth 3 (cadr entry)))
1832                  (eq 's (nth 3 (cadr entry))))
1833              (assoc id entry)
1834              (setq dont t)))
1835       (unless dont
1836         (gnus-summary-score-entry
1837          (if thread "thread" "references")
1838          id 's score (current-time-string) nil t)))))
1839
1840 (defun gnus-score-string (score-list header now expire &optional trace)
1841   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1842   ;; Update matching entries to NOW and remove unmatched entries older
1843   ;; than EXPIRE.
1844
1845   ;; Insert the unique article headers in the buffer.
1846   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1847         ;; gnus-score-index is used as a free variable.
1848         (simplify (and gnus-score-thread-simplify
1849                        (string= "subject" header)))
1850         alike last this art entries alist articles
1851         fuzzies arts words kill)
1852
1853     ;; Sorting the articles costs os O(N*log N) but will allow us to
1854     ;; only match with each unique header.  Thus the actual matching
1855     ;; will be O(M*U) where M is the number of strings to match with,
1856     ;; and U is the number of unique headers.  It is assumed (but
1857     ;; untested) this will be a net win because of the large constant
1858     ;; factor involved with string matching.
1859     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1860           articles gnus-scores-articles)
1861
1862     (erase-buffer)
1863     (while (setq art (pop articles))
1864       (setq this (aref (car art) gnus-score-index))
1865       (if simplify
1866         (setq this (gnus-map-function gnus-simplify-subject-functions this)))
1867       (if (equal last this)
1868           ;; O(N*H) cons-cells used here, where H is the number of
1869           ;; headers.
1870           (push art alike)
1871         (when last
1872           ;; Insert the line, with a text property on the
1873           ;; terminating newline referring to the articles with
1874           ;; this line.
1875           (insert last ?\n)
1876           (put-text-property (1- (point)) (point) 'articles alike))
1877         (setq alike (list art)
1878               last this)))
1879     (when last                          ; Bwadr, duplicate code.
1880       (insert last ?\n)
1881       (put-text-property (1- (point)) (point) 'articles alike))
1882
1883     ;; Go through all the score alists and pick out the entries
1884     ;; for this header.
1885     (while score-list
1886       (setq alist (pop score-list)
1887             ;; There's only one instance of this header for
1888             ;; each score alist.
1889             entries (assoc header alist))
1890       (while (cdr entries)              ;First entry is the header index.
1891         (let* ((kill (cadr entries))
1892                (type (or (nth 3 kill) 's))
1893                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1894                (date (nth 2 kill))
1895                (found nil)
1896                (mt (aref (symbol-name type) 0))
1897                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
1898                (dmt (downcase mt))
1899                ; Assume user already simplified regexp and fuzzies
1900                (match (if (and simplify (not (memq dmt '(?f ?r))))
1901                           (gnus-map-function
1902                            gnus-simplify-subject-functions
1903                            (nth 0 kill))
1904                         (nth 0 kill)))
1905                (search-func
1906                 (cond ((= dmt ?r) 're-search-forward)
1907                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1908                       ((= dmt ?w) nil)
1909                       (t (error "Illegal match type: %s" type)))))
1910           (cond
1911            ;; Fuzzy matches.  We save these for later.
1912            ((= dmt ?f)
1913             (push (cons entries alist) fuzzies))
1914            ;; Word matches.  Save these for even later.
1915            ((= dmt ?w)
1916             (push (cons entries alist) words))
1917            ;; Exact matches.
1918            ((= dmt ?e)
1919             ;; Do exact matching.
1920             (goto-char (point-min))
1921             (while (and (not (eobp))
1922                         (funcall search-func match nil t))
1923               ;; Is it really exact?
1924               (and (eolp)
1925                    (= (gnus-point-at-bol) (match-beginning 0))
1926                    ;; Yup.
1927                    (progn
1928                      (setq found (setq arts (get-text-property
1929                                              (point) 'articles)))
1930                      ;; Found a match, update scores.
1931                      (if trace
1932                          (while (setq art (pop arts))
1933                            (setcdr art (+ score (cdr art)))
1934                            (push
1935                             (cons
1936                              (car-safe (rassq alist gnus-score-cache))
1937                              kill)
1938                             gnus-score-trace))
1939                        (while (setq art (pop arts))
1940                          (setcdr art (+ score (cdr art)))))))
1941               (forward-line 1)))
1942            ;; Regexp and substring matching.
1943            (t
1944             (goto-char (point-min))
1945             (when (string= match "")
1946               (setq match "\n"))
1947             (while (and (not (eobp))
1948                         (funcall search-func match nil t))
1949               (goto-char (match-beginning 0))
1950               (end-of-line)
1951               (setq found (setq arts (get-text-property (point) 'articles)))
1952               ;; Found a match, update scores.
1953               (if trace
1954                   (while (setq art (pop arts))
1955                     (setcdr art (+ score (cdr art)))
1956                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1957                           gnus-score-trace))
1958                 (while (setq art (pop arts))
1959                   (setcdr art (+ score (cdr art)))))
1960               (forward-line 1))))
1961           ;; Update expiry date
1962           (if trace
1963               (setq entries (cdr entries))
1964             (cond
1965              ;; Permanent entry.
1966              ((null date)
1967               (setq entries (cdr entries)))
1968              ;; We have a match, so we update the date.
1969              ((and found gnus-update-score-entry-dates)
1970               (gnus-score-set 'touched '(t) alist)
1971               (setcar (nthcdr 2 kill) now)
1972               (setq entries (cdr entries)))
1973              ;; This entry has expired, so we remove it.
1974              ((and expire (< date expire))
1975               (gnus-score-set 'touched '(t) alist)
1976               (setcdr entries (cddr entries)))
1977              ;; No match; go to next entry.
1978              (t
1979               (setq entries (cdr entries))))))))
1980
1981     ;; Find fuzzy matches.
1982     (when fuzzies
1983       ;; Simplify the entire buffer for easy matching.
1984       (gnus-simplify-buffer-fuzzy)
1985       (while (setq kill (cadaar fuzzies))
1986         (let* ((match (nth 0 kill))
1987                (type (nth 3 kill))
1988                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1989                (date (nth 2 kill))
1990                (mt (aref (symbol-name type) 0))
1991                (case-fold-search (not (= mt ?F)))
1992                found)
1993           (goto-char (point-min))
1994           (while (and (not (eobp))
1995                       (search-forward match nil t))
1996             (when (and (= (gnus-point-at-bol) (match-beginning 0))
1997                        (eolp))
1998               (setq found (setq arts (get-text-property (point) 'articles)))
1999               (if trace
2000                   (while (setq art (pop arts))
2001                     (setcdr art (+ score (cdr art)))
2002                     (push (cons
2003                            (car-safe (rassq (cdar fuzzies) gnus-score-cache))
2004                            kill)
2005                           gnus-score-trace))
2006                 ;; Found a match, update scores.
2007                 (while (setq art (pop arts))
2008                   (setcdr art (+ score (cdr art))))))
2009             (forward-line 1))
2010           ;; Update expiry date
2011           (cond
2012            ;; Permanent.
2013            ((null date)
2014             )
2015            ;; Match, update date.
2016            ((and found gnus-update-score-entry-dates)
2017             (gnus-score-set 'touched '(t) (cdar fuzzies))
2018             (setcar (nthcdr 2 kill) now))
2019            ;; Old entry, remove.
2020            ((and expire (< date expire))
2021             (gnus-score-set 'touched '(t) (cdar fuzzies))
2022             (setcdr (caar fuzzies) (cddaar fuzzies))))
2023           (setq fuzzies (cdr fuzzies)))))
2024
2025     (when words
2026       ;; Enter all words into the hashtb.
2027       (let ((hashtb (gnus-make-hashtable
2028                      (* 10 (count-lines (point-min) (point-max))))))
2029         (gnus-enter-score-words-into-hashtb hashtb)
2030         (while (setq kill (cadaar words))
2031           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
2032                  (date (nth 2 kill))
2033                  found)
2034             (when (setq arts (intern-soft (nth 0 kill) hashtb))
2035               (setq arts (symbol-value arts))
2036               (setq found t)
2037               (if trace
2038                   (while (setq art (pop arts))
2039                     (setcdr art (+ score (cdr art)))
2040                     (push (cons
2041                            (car-safe (rassq (cdar words) gnus-score-cache))
2042                            kill)
2043                           gnus-score-trace))
2044                 ;; Found a match, update scores.
2045                 (while (setq art (pop arts))
2046                   (setcdr art (+ score (cdr art))))))
2047             ;; Update expiry date
2048             (cond
2049              ;; Permanent.
2050              ((null date)
2051               )
2052              ;; Match, update date.
2053              ((and found gnus-update-score-entry-dates)
2054               (gnus-score-set 'touched '(t) (cdar words))
2055               (setcar (nthcdr 2 kill) now))
2056              ;; Old entry, remove.
2057              ((and expire (< date expire))
2058               (gnus-score-set 'touched '(t) (cdar words))
2059               (setcdr (caar words) (cddaar words))))
2060             (setq words (cdr words))))))
2061     nil))
2062
2063 (defun gnus-enter-score-words-into-hashtb (hashtb)
2064   ;; Find all the words in the buffer and enter them into
2065   ;; the hashtable.
2066   (let ((syntab (syntax-table))
2067         word val)
2068     (goto-char (point-min))
2069     (unwind-protect
2070         (progn
2071           (set-syntax-table gnus-adaptive-word-syntax-table)
2072           (while (re-search-forward "\\b\\w+\\b" nil t)
2073             (setq val
2074                   (gnus-gethash
2075                    (setq word (downcase (buffer-substring
2076                                          (match-beginning 0) (match-end 0))))
2077                    hashtb))
2078             (gnus-sethash
2079              word
2080              (append (get-text-property (gnus-point-at-eol) 'articles) val)
2081              hashtb)))
2082       (set-syntax-table syntab))
2083     ;; Make all the ignorable words ignored.
2084     (let ((ignored (append gnus-ignored-adaptive-words
2085                            gnus-default-ignored-adaptive-words)))
2086       (while ignored
2087         (gnus-sethash (pop ignored) nil hashtb)))))
2088
2089 (defun gnus-score-string< (a1 a2)
2090   ;; Compare headers in articles A2 and A2.
2091   ;; The header index used is the free variable `gnus-score-index'.
2092   (string-lessp (aref (car a1) gnus-score-index)
2093                 (aref (car a2) gnus-score-index)))
2094
2095 (defun gnus-current-score-file-nondirectory (&optional score-file)
2096   (let ((score-file (or score-file gnus-current-score-file)))
2097     (if score-file
2098         (gnus-short-group-name (file-name-nondirectory score-file))
2099       "none")))
2100
2101 (defun gnus-score-adaptive ()
2102   "Create adaptive score rules for this newsgroup."
2103   (when gnus-newsgroup-adaptive
2104     ;; We change the score file to the adaptive score file.
2105     (save-excursion
2106       (set-buffer gnus-summary-buffer)
2107       (gnus-score-load-file
2108        (or gnus-newsgroup-adaptive-score-file
2109            (gnus-home-score-file gnus-newsgroup-name t)
2110            (gnus-score-file-name
2111             gnus-newsgroup-name gnus-adaptive-file-suffix))))
2112     ;; Perform ordinary line scoring.
2113     (when (or (not (listp gnus-newsgroup-adaptive))
2114               (memq 'line gnus-newsgroup-adaptive))
2115       (save-excursion
2116         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
2117                (alist malist)
2118                (date (current-time-string))
2119                (data gnus-newsgroup-data)
2120                elem headers match func)
2121           ;; First we transform the adaptive rule alist into something
2122           ;; that's faster to process.
2123           (while malist
2124             (setq elem (car malist))
2125             (when (symbolp (car elem))
2126               (setcar elem (symbol-value (car elem))))
2127             (setq elem (cdr elem))
2128             (while elem
2129               (when (fboundp
2130                      (setq func
2131                            (intern
2132                             (concat "mail-header-"
2133                                     (if (eq (caar elem) 'followup)
2134                                         "message-id"
2135                                       (downcase (symbol-name (caar elem))))))))
2136                 (setcdr (car elem)
2137                         (cons (if (eq (caar elem) 'followup)
2138                                   "references"
2139                                 (symbol-name (caar elem)))
2140                               (cdar elem)))
2141                 (setcar (car elem)
2142                         `(lambda (h)
2143                            (,func h))))
2144               (setq elem (cdr elem)))
2145             (setq malist (cdr malist)))
2146           ;; Then we score away.
2147           (while data
2148             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2149             (if (or (not elem)
2150                     (gnus-data-pseudo-p (car data)))
2151                 ()
2152               (when (setq headers (gnus-data-header (car data)))
2153                 (while elem
2154                   (setq match (funcall (caar elem) headers))
2155                   (gnus-summary-score-entry
2156                    (nth 1 (car elem)) match
2157                    (cond
2158                     ((numberp match)
2159                      '=)
2160                     ((equal (nth 1 (car elem)) "date")
2161                      'a)
2162                     (t
2163                      ;; Whether we use substring or exact matches is
2164                      ;; controlled here.
2165                      (if (or (not gnus-score-exact-adapt-limit)
2166                              (< (length match) gnus-score-exact-adapt-limit))
2167                          'e
2168                        (if (equal (nth 1 (car elem)) "subject")
2169                            'f 's))))
2170                    (nth 2 (car elem)) date nil t)
2171                   (setq elem (cdr elem)))))
2172             (setq data (cdr data))))))
2173
2174     ;; Perform adaptive word scoring.
2175     (when (and (listp gnus-newsgroup-adaptive)
2176                (memq 'word gnus-newsgroup-adaptive))
2177       (nnheader-temp-write nil
2178         (let* ((hashtb (gnus-make-hashtable 1000))
2179                (date (gnus-day-number (current-time-string)))
2180                (data gnus-newsgroup-data)
2181                (syntab (syntax-table))
2182                word d score val)
2183           (unwind-protect
2184               (progn
2185                 (set-syntax-table gnus-adaptive-word-syntax-table)
2186                 ;; Go through all articles.
2187                 (while (setq d (pop data))
2188                   (when (and
2189                          (not (gnus-data-pseudo-p d))
2190                          (setq score
2191                                (cdr (assq
2192                                      (gnus-data-mark d)
2193                                      gnus-adaptive-word-score-alist))))
2194                     ;; This article has a mark that should lead to
2195                     ;; adaptive word rules, so we insert the subject
2196                     ;; and find all words in that string.
2197                     (insert (mail-header-subject (gnus-data-header d)))
2198                     (downcase-region (point-min) (point-max))
2199                     (goto-char (point-min))
2200                     (while (re-search-forward "\\b\\w+\\b" nil t)
2201                       ;; Put the word and score into the hashtb.
2202                       (setq val (gnus-gethash (setq word (match-string 0))
2203                                               hashtb))
2204                       (setq val (+ score (or val 0)))
2205                       (if (and gnus-adaptive-word-minimum
2206                                (< val gnus-adaptive-word-minimum))
2207                           (setq val gnus-adaptive-word-minimum))
2208                       (gnus-sethash word val hashtb))
2209                     (erase-buffer))))
2210             (set-syntax-table syntab))
2211           ;; Make all the ignorable words ignored.
2212           (let ((ignored (append gnus-ignored-adaptive-words
2213                                  gnus-default-ignored-adaptive-words)))
2214             (while ignored
2215               (gnus-sethash (pop ignored) nil hashtb)))
2216           ;; Now we have all the words and scores, so we
2217           ;; add these rules to the ADAPT file.
2218           (set-buffer gnus-summary-buffer)
2219           (mapatoms
2220            (lambda (word)
2221              (when (symbol-value word)
2222                (gnus-summary-score-entry
2223                 "subject" (symbol-name word) 'w (symbol-value word)
2224                 date nil t)))
2225            hashtb))))))
2226
2227 (defun gnus-score-edit-done ()
2228   (let ((bufnam (buffer-file-name (current-buffer)))
2229         (winconf gnus-prev-winconf))
2230     (when winconf
2231       (set-window-configuration winconf))
2232     (gnus-score-remove-from-cache bufnam)
2233     (gnus-score-load-file bufnam)))
2234
2235 (defun gnus-score-find-trace ()
2236   "Find all score rules that applies to the current article."
2237   (interactive)
2238   (let ((old-scored gnus-newsgroup-scored))
2239     (let ((gnus-newsgroup-headers
2240            (list (gnus-summary-article-header)))
2241           (gnus-newsgroup-scored nil)
2242           trace)
2243       (save-excursion
2244         (nnheader-set-temp-buffer "*Score Trace*"))
2245       (setq gnus-score-trace nil)
2246       (gnus-possibly-score-headers 'trace)
2247       (if (not (setq trace gnus-score-trace))
2248           (gnus-error
2249            1 "No score rules apply to the current article (default score %d)."
2250            gnus-summary-default-score)
2251         (set-buffer "*Score Trace*")
2252         (gnus-add-current-to-buffer-list)
2253         (while trace
2254           (insert (format "%S  ->  %s\n" (cdar trace)
2255                           (if (caar trace)
2256                               (file-name-nondirectory (caar trace))
2257                             "(non-file rule)")))
2258           (setq trace (cdr trace)))
2259         (goto-char (point-min))
2260         (gnus-configure-windows 'score-trace)))
2261     (set-buffer gnus-summary-buffer)
2262     (setq gnus-newsgroup-scored old-scored)))
2263
2264 (defun gnus-score-find-favourite-words ()
2265   "List words used in scoring."
2266   (interactive)
2267   (let ((alists (gnus-score-load-files (gnus-all-score-files)))
2268         alist rule rules kill)
2269     ;; Go through all the score alists for this group
2270     ;; and find all `w' rules.
2271     (while (setq alist (pop alists))
2272       (while (setq rule (pop alist))
2273         (when (and (stringp (car rule))
2274                    (equal "subject" (downcase (pop rule))))
2275           (while (setq kill (pop rule))
2276             (when (memq (nth 3 kill) '(w W word Word))
2277               (push (cons (or (nth 1 kill)
2278                               gnus-score-interactive-default-score)
2279                           (car kill))
2280                     rules))))))
2281     (setq rules (sort rules (lambda (r1 r2)
2282                               (string-lessp (cdr r1) (cdr r2)))))
2283     ;; Add up words that have appeared several times.
2284     (let ((r rules))
2285       (while (cdr r)
2286         (if (equal (cdar r) (cdadr r))
2287             (progn
2288               (setcar (car r) (+ (caar r) (caadr r)))
2289               (setcdr r (cddr r)))
2290           (pop r))))
2291     ;; Insert the words.
2292     (nnheader-set-temp-buffer "*Score Words*")
2293     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2294         (gnus-error 3 "No word score rules")
2295       (while rules
2296         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2297         (pop rules))
2298       (gnus-add-current-to-buffer-list)
2299       (goto-char (point-min))
2300       (gnus-configure-windows 'score-words))))
2301
2302 (defun gnus-summary-rescore ()
2303   "Redo the entire scoring process in the current summary."
2304   (interactive)
2305   (gnus-score-save)
2306   (setq gnus-score-cache nil)
2307   (setq gnus-newsgroup-scored nil)
2308   (gnus-possibly-score-headers)
2309   (gnus-score-update-all-lines))
2310
2311 (defun gnus-score-flush-cache ()
2312   "Flush the cache of score files."
2313   (interactive)
2314   (gnus-score-save)
2315   (setq gnus-score-cache nil
2316         gnus-score-alist nil
2317         gnus-short-name-score-file-cache nil)
2318   (gnus-message 6 "The score cache is now flushed"))
2319
2320 (gnus-add-shutdown 'gnus-score-close 'gnus)
2321
2322 (defvar gnus-score-file-alist-cache nil)
2323
2324 (defun gnus-score-close ()
2325   "Clear all internal score variables."
2326   (setq gnus-score-cache nil
2327         gnus-internal-global-score-files nil
2328         gnus-score-file-list nil
2329         gnus-score-file-alist-cache nil))
2330
2331 ;; Summary score marking commands.
2332
2333 (defun gnus-summary-raise-same-subject-and-select (score)
2334   "Raise articles which has the same subject with SCORE and select the next."
2335   (interactive "p")
2336   (let ((subject (gnus-summary-article-subject)))
2337     (gnus-summary-raise-score score)
2338     (while (gnus-summary-find-subject subject)
2339       (gnus-summary-raise-score score))
2340     (gnus-summary-next-article t)))
2341
2342 (defun gnus-summary-raise-same-subject (score)
2343   "Raise articles which has the same subject with SCORE."
2344   (interactive "p")
2345   (let ((subject (gnus-summary-article-subject)))
2346     (gnus-summary-raise-score score)
2347     (while (gnus-summary-find-subject subject)
2348       (gnus-summary-raise-score score))
2349     (gnus-summary-next-subject 1 t)))
2350
2351 (defun gnus-score-default (level)
2352   (if level (prefix-numeric-value level)
2353     gnus-score-interactive-default-score))
2354
2355 (defun gnus-summary-raise-thread (&optional score)
2356   "Raise the score of the articles in the current thread with SCORE."
2357   (interactive "P")
2358   (setq score (gnus-score-default score))
2359   (let (e)
2360     (save-excursion
2361       (let ((articles (gnus-summary-articles-in-thread)))
2362         (while articles
2363           (gnus-summary-goto-subject (car articles))
2364           (gnus-summary-raise-score score)
2365           (setq articles (cdr articles))))
2366       (setq e (point)))
2367     (let ((gnus-summary-check-current t))
2368       (unless (zerop (gnus-summary-next-subject 1 t))
2369         (goto-char e))))
2370   (gnus-summary-recenter)
2371   (gnus-summary-position-point)
2372   (gnus-set-mode-line 'summary))
2373
2374 (defun gnus-summary-lower-same-subject-and-select (score)
2375   "Raise articles which has the same subject with SCORE and select the next."
2376   (interactive "p")
2377   (gnus-summary-raise-same-subject-and-select (- score)))
2378
2379 (defun gnus-summary-lower-same-subject (score)
2380   "Raise articles which has the same subject with SCORE."
2381   (interactive "p")
2382   (gnus-summary-raise-same-subject (- score)))
2383
2384 (defun gnus-summary-lower-thread (&optional score)
2385   "Lower score of articles in the current thread with SCORE."
2386   (interactive "P")
2387   (gnus-summary-raise-thread (- (1- (gnus-score-default score)))))
2388
2389 ;;; Finding score files.
2390
2391 (defun gnus-score-score-files (group)
2392   "Return a list of all possible score files."
2393   ;; Search and set any global score files.
2394   (when gnus-global-score-files
2395     (unless gnus-internal-global-score-files
2396       (gnus-score-search-global-directories gnus-global-score-files)))
2397   ;; Fix the kill-file dir variable.
2398   (setq gnus-kill-files-directory
2399         (file-name-as-directory gnus-kill-files-directory))
2400   ;; If we can't read it, there are no score files.
2401   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2402       (setq gnus-score-file-list nil)
2403     (if (not (gnus-use-long-file-name 'not-score))
2404         ;; We do not use long file names, so we have to do some
2405         ;; directory traversing.
2406         (setq gnus-score-file-list
2407               (cons nil
2408                     (or gnus-short-name-score-file-cache
2409                         (prog2
2410                             (gnus-message 6 "Finding all score files...")
2411                             (setq gnus-short-name-score-file-cache
2412                                   (gnus-score-score-files-1
2413                                    gnus-kill-files-directory))
2414                           (gnus-message 6 "Finding all score files...done")))))
2415       ;; We want long file names.
2416       (when (or (not gnus-score-file-list)
2417                 (not (car gnus-score-file-list))
2418                 (gnus-file-newer-than gnus-kill-files-directory
2419                                       (car gnus-score-file-list)))
2420         (setq gnus-score-file-list
2421               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2422                     (nreverse
2423                      (directory-files
2424                       gnus-kill-files-directory t
2425                       (gnus-score-file-regexp)))))))
2426     (cdr gnus-score-file-list)))
2427
2428 (defun gnus-score-score-files-1 (dir)
2429   "Return all possible score files under DIR."
2430   (let ((files (list (expand-file-name dir)))
2431         (regexp (gnus-score-file-regexp))
2432         (case-fold-search nil)
2433         seen out file)
2434     (while (setq file (pop files))
2435       (cond
2436        ;; Ignore "." and "..".
2437        ((member (file-name-nondirectory file) '("." ".."))
2438         nil)
2439        ;; Add subtrees of directory to also be searched.
2440        ((and (file-directory-p file)
2441              (not (member (file-truename file) seen)))
2442         (push (file-truename file) seen)
2443         (setq files (nconc (directory-files file t nil t) files)))
2444        ;; Add files to the list of score files.
2445        ((string-match regexp file)
2446         (push file out))))
2447     (or out
2448         ;; Return a dummy value.
2449         (list "~/News/this.file.does.not.exist.SCORE"))))
2450
2451 (defun gnus-score-file-regexp ()
2452   "Return a regexp that match all score files."
2453   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2454           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2455
2456 (defun gnus-score-find-bnews (group)
2457   "Return a list of score files for GROUP.
2458 The score files are those files in the ~/News/ directory which matches
2459 GROUP using BNews sys file syntax."
2460   (let* ((sfiles (append (gnus-score-score-files group)
2461                          gnus-internal-global-score-files))
2462          (kill-dir (file-name-as-directory
2463                     (expand-file-name gnus-kill-files-directory)))
2464          (klen (length kill-dir))
2465          (score-regexp (gnus-score-file-regexp))
2466          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2467          ofiles not-match regexp)
2468     (save-excursion
2469       (set-buffer (get-buffer-create "*gnus score files*"))
2470       (buffer-disable-undo (current-buffer))
2471       ;; Go through all score file names and create regexp with them
2472       ;; as the source.
2473       (while sfiles
2474         (erase-buffer)
2475         (insert (car sfiles))
2476         (goto-char (point-min))
2477         ;; First remove the suffix itself.
2478         (when (re-search-forward (concat "." score-regexp) nil t)
2479           (replace-match "" t t)
2480           (goto-char (point-min))
2481           (if (looking-at (regexp-quote kill-dir))
2482               ;; If the file name was just "SCORE", `klen' is one character
2483               ;; too much.
2484               (delete-char (min (1- (point-max)) klen))
2485             (goto-char (point-max))
2486             (search-backward "/")
2487             (delete-region (1+ (point)) (point-min)))
2488           ;; If short file names were used, we have to translate slashes.
2489           (goto-char (point-min))
2490           (let ((regexp (concat
2491                          "[/:" (if trans (char-to-string trans) "") "]")))
2492             (while (re-search-forward regexp nil t)
2493               (replace-match "." t t)))
2494           ;; Kludge to get rid of "nntp+" problems.
2495           (goto-char (point-min))
2496           (when (looking-at "nn[a-z]+\\+")
2497             (search-forward "+")
2498             (forward-char -1)
2499             (insert "\\")
2500             (forward-char 1))
2501           ;; Kludge to deal with "++".
2502           (while (search-forward "+" nil t)
2503             (replace-match "\\+" t t))
2504           ;; Translate "all" to ".*".
2505           (goto-char (point-min))
2506           (while (search-forward "all" nil t)
2507             (replace-match ".*" t t))
2508           (goto-char (point-min))
2509           ;; Deal with "not."s.
2510           (if (looking-at "not.")
2511               (progn
2512                 (setq not-match t)
2513                 (setq regexp (concat "^" (buffer-substring 5 (point-max)) "$")))
2514             (setq regexp (concat "^" (buffer-substring 1 (point-max)) "$"))
2515             (setq not-match nil))
2516           ;; Finally - if this resulting regexp matches the group name,
2517           ;; we add this score file to the list of score files
2518           ;; applicable to this group.
2519           (when (or (and not-match
2520                          (not (string-match regexp group)))
2521                     (and (not not-match)
2522                          (string-match regexp group)))
2523             (push (car sfiles) ofiles)))
2524         (setq sfiles (cdr sfiles)))
2525       (kill-buffer (current-buffer))
2526       ;; Slight kludge here - the last score file returned should be
2527       ;; the local score file, whether it exists or not.  This is so
2528       ;; that any score commands the user enters will go to the right
2529       ;; file, and not end up in some global score file.
2530       (let ((localscore (gnus-score-file-name group)))
2531         (setq ofiles (cons localscore (delete localscore ofiles))))
2532       (gnus-sort-score-files (nreverse ofiles)))))
2533
2534 (defun gnus-score-find-single (group)
2535   "Return list containing the score file for GROUP."
2536   (list (or gnus-newsgroup-adaptive-score-file
2537             (gnus-score-file-name group gnus-adaptive-file-suffix))
2538         (gnus-score-file-name group)))
2539
2540 (defun gnus-score-find-hierarchical (group)
2541   "Return list of score files for GROUP.
2542 This includes the score file for the group and all its parents."
2543   (let* ((prefix (gnus-group-real-prefix group))
2544          (all (list nil))
2545          (group (gnus-group-real-name group))
2546          (start 0))
2547     (while (string-match "\\." group (1+ start))
2548       (setq start (match-beginning 0))
2549       (push (substring group 0 start) all))
2550     (push group all)
2551     (setq all
2552           (nconc
2553            (mapcar (lambda (group)
2554                      (gnus-score-file-name group gnus-adaptive-file-suffix))
2555                    (setq all (nreverse all)))
2556            (mapcar 'gnus-score-file-name all)))
2557     (if (equal prefix "")
2558         all
2559       (mapcar
2560        (lambda (file)
2561          (nnheader-translate-file-chars
2562           (concat (file-name-directory file) prefix
2563                   (file-name-nondirectory file))))
2564        all))))
2565
2566 (defun gnus-score-file-rank (file)
2567   "Return a number that says how specific score FILE is.
2568 Destroys the current buffer."
2569   (if (member file gnus-internal-global-score-files)
2570       0
2571     (when (string-match
2572            (concat "^" (regexp-quote
2573                         (expand-file-name
2574                          (file-name-as-directory gnus-kill-files-directory))))
2575            file)
2576       (setq file (substring file (match-end 0))))
2577     (insert file)
2578     (goto-char (point-min))
2579     (let ((beg (point))
2580           elems)
2581       (while (re-search-forward "[./]" nil t)
2582         (push (buffer-substring beg (1- (point)))
2583               elems))
2584       (erase-buffer)
2585       (setq elems (delete "all" elems))
2586       (length elems))))
2587
2588 (defun gnus-sort-score-files (files)
2589   "Sort FILES so that the most general files come first."
2590   (nnheader-temp-write nil
2591     (let ((alist
2592            (mapcar
2593             (lambda (file)
2594               (cons (inline (gnus-score-file-rank file)) file))
2595             files)))
2596       (mapcar
2597        (lambda (f) (cdr f))
2598        (sort alist 'car-less-than-car)))))
2599
2600 (defun gnus-score-find-alist (group)
2601   "Return list of score files for GROUP.
2602 The list is determined from the variable gnus-score-file-alist."
2603   (let ((alist gnus-score-file-multiple-match-alist)
2604         score-files)
2605     ;; if this group has been seen before, return the cached entry
2606     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2607         (cdr score-files)               ;ensures caching groups with no matches
2608       ;; handle the multiple match alist
2609       (while alist
2610         (when (string-match (caar alist) group)
2611           (setq score-files
2612                 (nconc score-files (copy-sequence (cdar alist)))))
2613         (setq alist (cdr alist)))
2614       (setq alist gnus-score-file-single-match-alist)
2615       ;; handle the single match alist
2616       (while alist
2617         (when (string-match (caar alist) group)
2618           ;; progn used just in case ("regexp") has no files
2619           ;; and score-files is still nil.  -sj
2620           ;; this can be construed as a "stop searching here" feature :>
2621           ;; and used to simplify regexps in the single-alist
2622           (setq score-files
2623                 (nconc score-files (copy-sequence (cdar alist))))
2624           (setq alist nil))
2625         (setq alist (cdr alist)))
2626       ;; cache the score files
2627       (push (cons group score-files) gnus-score-file-alist-cache)
2628       score-files)))
2629
2630 (defun gnus-all-score-files (&optional group)
2631   "Return a list of all score files for the current group."
2632   (let ((funcs gnus-score-find-score-files-function)
2633         (group (or group gnus-newsgroup-name))
2634         score-files)
2635     (when group
2636       ;; Make sure funcs is a list.
2637       (and funcs
2638            (not (listp funcs))
2639            (setq funcs (list funcs)))
2640       ;; Get the initial score files for this group.
2641       (when funcs
2642         (setq score-files (nreverse (gnus-score-find-alist group))))
2643       ;; Add any home adapt files.
2644       (let ((home (gnus-home-score-file group t)))
2645         (when home
2646           (push home score-files)
2647           (setq gnus-newsgroup-adaptive-score-file home)))
2648       ;; Check whether there is a `adapt-file' group parameter.
2649       (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2650         (when param-file
2651           (push param-file score-files)
2652           (setq gnus-newsgroup-adaptive-score-file param-file)))
2653       ;; Go through all the functions for finding score files (or actual
2654       ;; scores) and add them to a list.
2655       (while funcs
2656         (when (gnus-functionp (car funcs))
2657           (setq score-files
2658                 (nconc score-files (nreverse (funcall (car funcs) group)))))
2659         (setq funcs (cdr funcs)))
2660       ;; Add any home score files.
2661       (let ((home (gnus-home-score-file group)))
2662         (when home
2663           (push home score-files)))
2664       ;; Check whether there is a `score-file' group parameter.
2665       (let ((param-file (gnus-group-find-parameter group 'score-file)))
2666         (when param-file
2667           (push param-file score-files)))
2668       ;; Expand all files names.
2669       (let ((files score-files))
2670         (while files
2671           (when (stringp (car files))
2672             (setcar files (expand-file-name
2673                            (car files) gnus-kill-files-directory)))
2674           (pop files)))
2675       (setq score-files (nreverse score-files))
2676       ;; Remove any duplicate score files.
2677       (while (and score-files
2678                   (member (car score-files) (cdr score-files)))
2679         (pop score-files))
2680       (let ((files score-files))
2681         (while (cdr files)
2682           (if (member (cadr files) (cddr files))
2683               (setcdr files (cddr files))
2684             (pop files))))
2685       ;; Do the scoring if there are any score files for this group.
2686       score-files)))
2687
2688 (defun gnus-possibly-score-headers (&optional trace)
2689   "Do scoring if scoring is required."
2690   (let ((score-files (gnus-all-score-files)))
2691     (when score-files
2692       (gnus-score-headers score-files trace))))
2693
2694 (defun gnus-score-file-name (newsgroup &optional suffix)
2695   "Return the name of a score file for NEWSGROUP."
2696   (let ((suffix (or suffix gnus-score-file-suffix)))
2697     (nnheader-translate-file-chars
2698      (cond
2699       ((or (null newsgroup)
2700            (string-equal newsgroup ""))
2701        ;; The global score file is placed at top of the directory.
2702        (expand-file-name suffix gnus-kill-files-directory))
2703       ((gnus-use-long-file-name 'not-score)
2704        ;; Append ".SCORE" to newsgroup name.
2705        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2706                                  "." suffix)
2707                          gnus-kill-files-directory))
2708       (t
2709        ;; Place "SCORE" under the hierarchical directory.
2710        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2711                                  "/" suffix)
2712                          gnus-kill-files-directory))))))
2713
2714 (defun gnus-score-search-global-directories (files)
2715   "Scan all global score directories for score files."
2716   ;; Set the variable `gnus-internal-global-score-files' to all
2717   ;; available global score files.
2718   (interactive (list gnus-global-score-files))
2719   (let (out)
2720     (while files
2721       (if (string-match "/$" (car files))
2722           (setq out (nconc (directory-files
2723                             (car files) t
2724                             (concat (gnus-score-file-regexp) "$"))))
2725         (push (car files) out))
2726       (setq files (cdr files)))
2727     (setq gnus-internal-global-score-files out)))
2728
2729 (defun gnus-score-default-fold-toggle ()
2730   "Toggle folding for new score file entries."
2731   (interactive)
2732   (setq gnus-score-default-fold (not gnus-score-default-fold))
2733   (if gnus-score-default-fold
2734       (gnus-message 1 "New score file entries will be case insensitive.")
2735     (gnus-message 1 "New score file entries will be case sensitive.")))
2736
2737 ;;; Home score file.
2738
2739 (defun gnus-home-score-file (group &optional adapt)
2740   "Return the home score file for GROUP.
2741 If ADAPT, return the home adaptive file instead."
2742   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2743         elem found)
2744     ;; Make sure we have a list.
2745     (unless (listp list)
2746       (setq list (list list)))
2747     ;; Go through the list and look for matches.
2748     (while (and (not found)
2749                 (setq elem (pop list)))
2750       (setq found
2751             (cond
2752              ;; Simple string.
2753              ((stringp elem)
2754               elem)
2755              ;; Function.
2756              ((gnus-functionp elem)
2757               (funcall elem group))
2758              ;; Regexp-file cons
2759              ((consp elem)
2760               (when (string-match (car elem) group)
2761                 (cadr elem))))))
2762     (when found
2763       (nnheader-concat gnus-kill-files-directory found))))
2764
2765 (defun gnus-hierarchial-home-score-file (group)
2766   "Return the score file of the top-level hierarchy of GROUP."
2767   (if (string-match "^[^.]+\\." group)
2768       (concat (match-string 0 group) gnus-score-file-suffix)
2769     ;; Group name without any dots.
2770     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2771             gnus-score-file-suffix)))
2772
2773 (defun gnus-hierarchial-home-adapt-file (group)
2774   "Return the adapt file of the top-level hierarchy of GROUP."
2775   (if (string-match "^[^.]+\\." group)
2776       (concat (match-string 0 group) gnus-adaptive-file-suffix)
2777     ;; Group name without any dots.
2778     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2779             gnus-adaptive-file-suffix)))
2780
2781 ;;;
2782 ;;; Score decays
2783 ;;;
2784
2785 (defun gnus-decay-score (score)
2786   "Decay SCORE according to `gnus-score-decay-constant' and `gnus-score-decay-scale'."
2787   (floor
2788    (- score
2789       (* (if (< score 0) -1 1)
2790          (min (abs score)
2791               (max gnus-score-decay-constant
2792                    (* (abs score)
2793                       gnus-score-decay-scale)))))))
2794
2795 (defun gnus-decay-scores (alist day)
2796   "Decay non-permanent scores in ALIST."
2797   (let ((times (- (gnus-time-to-day (current-time)) day))
2798         kill entry updated score n)
2799     (unless (zerop times)               ;Done decays today already?
2800       (while (setq entry (pop alist))
2801         (when (stringp (car entry))
2802           (setq entry (cdr entry))
2803           (while (setq kill (pop entry))
2804             (when (nth 2 kill)
2805               (setq updated t)
2806               (setq score (or (nth 1 kill)
2807                               gnus-score-interactive-default-score)
2808                     n times)
2809               (while (natnump (decf n))
2810                 (setq score (funcall gnus-decay-score-function score)))
2811               (setcdr kill (cons score 
2812                                  (cdr (cdr kill)))))))))
2813     ;; Return whether this score file needs to be saved.  By Je-haysuss!
2814     updated))
2815
2816 (defun gnus-score-regexp-bad-p (regexp)
2817   "Test whether REGEXP is safe for Gnus scoring.
2818 A regexp is unsafe if it matches newline or a buffer boundary.
2819
2820 If the regexp is good, return nil.  If the regexp is bad, return a
2821 cons cell (SYM . STRING), where the symbol SYM is `new' or `bad'.
2822 In the `new' case, the string is a safe replacement for REGEXP.
2823 In the `bad' case, the string is a unsafe subexpression of REGEXP,
2824 and we do not have a simple replacement to suggest.
2825
2826 See `(Gnus)Scoring Tips' for examples of good regular expressions."
2827   (let (case-fold-search)
2828     (and
2829      ;; First, try a relatively fast necessary condition.
2830      ;; Notice ranges (like [^:] or [\t-\r]), \s>, \Sw, \W, \', \`:
2831      (string-match "\n\\|\\\\[SsW`']\\|\\[\\^\\|[\0-\n]-" regexp)
2832      ;; Now break the regexp into tokens, and check each:
2833      (let ((tail regexp)                ; remaining regexp to check
2834            tok                          ; current token
2835            bad                          ; nil, or bad subexpression
2836            new                          ; nil, or replacement regexp so far
2837            end)                         ; length of current token
2838        (while (and (not bad)
2839                    (string-match
2840                     "\\`\\(\\\\[sS]?.\\|\\[\\^?]?[^]]*]\\|[^\\]\\)"
2841                     tail))
2842          (setq end (match-end 0)
2843                tok (substring tail 0 end)
2844                tail (substring tail end))
2845          (if;; Is token `bad' (matching newline or buffer ends)?
2846              (or (member tok '("\n" "\\W" "\\`" "\\'"))
2847                  ;; This next handles "[...]", "\\s.", and "\\S.":
2848                  (and (> end 2) (string-match tok "\n")))
2849              (let ((newtok
2850                     ;; Try to suggest a replacement for tok ...
2851                     (cond ((string-equal tok "\\`") "^") ; or "\\(^\\)"
2852                           ((string-equal tok "\\'") "$") ; or "\\($\\)"
2853                           ((string-match "\\[\\^" tok) ; very common
2854                            (concat (substring tok 0 -1) "\n]")))))
2855                (if newtok
2856                    (setq new
2857                          (concat
2858                           (or new
2859                               ;; good prefix so far:
2860                               (substring regexp 0 (- (+ (length tail) end))))
2861                           newtok))
2862                  ;; No replacement idea, so give up:
2863                  (setq bad tok)))
2864            ;; tok is good, may need to extend new
2865            (and new (setq new (concat new tok)))))
2866        ;; Now return a value:
2867        (cond
2868         (bad (cons 'bad bad))
2869         (new (cons 'new new))
2870         ;; or nil
2871         )))))
2872
2873 (provide 'gnus-score)
2874
2875 ;;; gnus-score.el ends here