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