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