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