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