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