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