*** 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 type)
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              (setq type (caar a))
891              (while (and sr (not err))
892                (setq s (pop sr))
893                (setq 
894                 err
895                 (cond
896                  ((if (member (downcase type) '("lines" "chars"))
897                       (not (numberp (car s)))
898                     (not (stringp (car s))))
899                   (format "Illegal match %s in %s" (car s) file))
900                  ((and (cadr s) (not (integerp (cadr s))))
901                   (format "Non-integer score %s in %s" (cadr s) file))
902                  ((and (caddr s) (not (integerp (caddr s))))
903                   (format "Non-integer date %s in %s" (caddr s) file))
904                  ((and (cadddr s) (not (symbolp (cadddr s))))
905                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
906              err)))))
907         (setq a (cdr a)))
908       (if err
909           (progn
910             (ding)
911             (gnus-message 3 err)
912             (sit-for 2)
913             nil)
914         alist)))))    
915
916 (defun gnus-score-transform-old-to-new (alist)
917   (let* ((alist (nth 2 alist))
918          out entry)
919     (if (eq (car alist) 'quote)
920         (setq alist (nth 1 alist)))
921     (while alist
922       (setq entry (car alist))
923       (if (stringp (car entry))
924           (let ((scor (cdr entry)))
925             (setq out (cons entry out))
926             (while scor
927               (setcar scor
928                       (list (car (car scor)) (nth 2 (car scor))
929                             (and (nth 3 (car scor))
930                                  (gnus-day-number (nth 3 (car scor))))
931                             (if (nth 1 (car scor)) 'r 's)))
932               (setq scor (cdr scor))))
933         (setq out (cons (if (not (listp (cdr entry))) 
934                             (list (car entry) (cdr entry))
935                           entry)
936                         out)))
937       (setq alist (cdr alist)))
938     (cons (list 'touched t) (nreverse out))))
939   
940 (defun gnus-score-save ()
941   ;; Save all score information.
942   (let ((cache gnus-score-cache))
943     (save-excursion
944       (setq gnus-score-alist nil)
945       (set-buffer (get-buffer-create "*Score*"))
946       (buffer-disable-undo (current-buffer))
947       (let (entry score file)
948         (while cache
949           (setq entry (car cache)
950                 cache (cdr cache)
951                 file (car entry)
952                 score (cdr entry))
953           (if (or (not (equal (gnus-score-get 'touched score) '(t)))
954                   (gnus-score-get 'read-only score)
955                   (and (file-exists-p file)
956                        (not (file-writable-p file))))
957               ()
958             (setq score (setcdr entry (delq (assq 'touched score) score)))
959             (erase-buffer)
960             (let (emacs-lisp-mode-hook)
961               (if (string-match (concat gnus-adaptive-file-suffix "$") file)
962                   ;; This is an adaptive score file, so we do not run
963                   ;; it through `pp'.  These files can get huge, and
964                   ;; are not meant to be edited by human hands.
965                   (insert (format "%S" score))
966                 ;; This is a normal score file, so we print it very
967                 ;; prettily. 
968                 (pp score (current-buffer))))
969             (if (not (gnus-make-directory (file-name-directory file)))
970                 ()
971               ;; If the score file is empty, we delete it.
972               (if (zerop (buffer-size))
973                   (delete-file file)
974                 ;; There are scores, so we write the file. 
975                 (and (file-writable-p file)
976                      (write-region (point-min) (point-max) 
977                                    file nil 'silent))))
978             (and gnus-score-uncacheable-files
979                  (string-match gnus-score-uncacheable-files file)
980                  (gnus-score-remove-from-cache file)))))
981       (kill-buffer (current-buffer)))))
982   
983 (defun gnus-score-headers (score-files &optional trace)
984   ;; Score `gnus-newsgroup-headers'.
985   (let (scores)
986     ;; PLM: probably this is not the best place to clear orphan-score
987     (setq gnus-orphan-score nil)
988     (setq gnus-scores-articles nil)
989     (setq gnus-scores-exclude-files nil)
990     ;; Load the score files.
991     (while score-files
992       (if (stringp (car score-files))
993           ;; It is a string, which means that it's a score file name,
994           ;; so we load the score file and add the score alist to
995           ;; the list of alists.
996           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
997         ;; It is an alist, so we just add it to the list directly.
998         (setq scores (nconc (car score-files) scores)))
999       (setq score-files (cdr score-files)))
1000     ;; Prune the score files that are to be excluded, if any.
1001     (when gnus-scores-exclude-files
1002       (let ((s scores)
1003             c)
1004         (while s
1005           (and (setq c (rassq (car s) gnus-score-cache))
1006                (member (car c) gnus-scores-exclude-files)
1007                (setq scores (delq (car s) scores)))
1008           (setq s (cdr s)))))
1009     ;; Do the scoring.
1010     (when (and gnus-summary-default-score
1011                scores
1012                (> (length gnus-newsgroup-headers)
1013                   (length gnus-newsgroup-scored)))
1014       (let* ((entries gnus-header-index)
1015              (now (gnus-day-number (current-time-string)))
1016              (expire (and gnus-score-expiry-days
1017                           (- now gnus-score-expiry-days)))
1018              (headers gnus-newsgroup-headers)
1019              (current-score-file gnus-current-score-file)
1020              entry header)
1021         (gnus-message 5 "Scoring...")
1022         ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1023         (while headers
1024           (setq header (car headers)
1025                 headers (cdr headers))
1026           ;; WARNING: The assq makes the function O(N*S) while it could
1027           ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1028           ;; and S is (length gnus-newsgroup-scored).
1029           (or (assq (mail-header-number header) gnus-newsgroup-scored)
1030               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1031                     (cons (cons header (or gnus-summary-default-score 0))
1032                           gnus-scores-articles))))
1033
1034         (save-excursion
1035           (set-buffer (get-buffer-create "*Headers*"))
1036           (buffer-disable-undo (current-buffer))
1037
1038           ;; Set the global variant of this variable.
1039           (setq gnus-current-score-file current-score-file)
1040           ;; score orphans
1041           (if gnus-orphan-score 
1042               (progn
1043                 (setq gnus-score-index 
1044                       (nth 1 (assoc "references" gnus-header-index)))
1045                 (gnus-score-orphans gnus-orphan-score)))
1046           ;; Run each header through the score process.
1047           (while entries
1048             (setq entry (car entries)
1049                   header (downcase (nth 0 entry))
1050                   entries (cdr entries))
1051             (setq gnus-score-index (nth 1 (assoc header gnus-header-index)))
1052             (if (< 0 (apply 'max (mapcar
1053                                   (lambda (score)
1054                                     (length (gnus-score-get header score)))
1055                                   scores)))
1056                 ;; Call the scoring function for this type of "header".
1057                 (funcall (nth 2 entry) scores header now expire trace)))
1058           ;; Remove the buffer.
1059           (kill-buffer (current-buffer)))
1060
1061         ;; Add articles to `gnus-newsgroup-scored'.
1062         (while gnus-scores-articles
1063           (or (= gnus-summary-default-score (cdr (car gnus-scores-articles)))
1064               (setq gnus-newsgroup-scored
1065                     (cons (cons (mail-header-number 
1066                                  (car (car gnus-scores-articles)))
1067                                 (cdr (car gnus-scores-articles)))
1068                           gnus-newsgroup-scored)))
1069           (setq gnus-scores-articles (cdr gnus-scores-articles)))
1070
1071         (gnus-message 5 "Scoring...done")))))
1072
1073
1074 (defun gnus-get-new-thread-ids (articles)
1075   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
1076         (refind gnus-score-index)
1077         id-list art this tref)
1078     (while articles
1079       (setq art (car articles)
1080             this (aref (car art) index)
1081             tref (aref (car art) refind)
1082             articles (cdr articles))
1083       (if (string-equal tref "")        ;no references line
1084           (setq id-list (cons this id-list))))
1085     id-list))
1086
1087 ;; Orphan functions written by plm@atcmp.nl (Peter Mutsaers).
1088 (defun gnus-score-orphans (score)
1089   (let ((new-thread-ids (gnus-get-new-thread-ids gnus-scores-articles))
1090         alike articles art arts this last this-id)
1091     
1092     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1093           articles gnus-scores-articles)
1094
1095     ;;more or less the same as in gnus-score-string
1096     (erase-buffer)
1097     (while articles
1098       (setq art (car articles)
1099             this (aref (car art) gnus-score-index)
1100             articles (cdr articles))
1101       ;;completely skip if this is empty (not a child, so not an orphan)
1102       (if (not (string= this ""))
1103           (if (equal last this)
1104               ;; O(N*H) cons-cells used here, where H is the number of
1105               ;; headers.
1106               (setq alike (cons art alike))
1107             (if last
1108                 (progn
1109                   ;; Insert the line, with a text property on the
1110                   ;; terminating newline referring to the articles with
1111                   ;; this line.
1112                   (insert last ?\n)
1113                   (put-text-property (1- (point)) (point) 'articles alike)))
1114             (setq alike (list art)
1115                   last this))))
1116     (and last                           ; Bwadr, duplicate code.
1117          (progn
1118            (insert last ?\n)                    
1119            (put-text-property (1- (point)) (point) 'articles alike)))
1120
1121     ;; PLM: now delete those lines that contain an entry from new-thread-ids
1122     (while new-thread-ids
1123       (setq this-id (car new-thread-ids)
1124             new-thread-ids (cdr new-thread-ids))
1125       (goto-char (point-min))
1126       (while (search-forward this-id nil t)
1127         ;; found a match. remove this line
1128         (beginning-of-line)
1129         (kill-line 1)))
1130
1131     ;; now for each line: update its articles with score by moving to
1132     ;; every end-of-line in the buffer and read the articles property
1133     (goto-char (point-min))
1134     (while (eq 0 (progn
1135                    (end-of-line)
1136                    (setq arts (get-text-property (point) 'articles))
1137                    (while arts
1138                      (setq art (car arts)
1139                            arts (cdr arts))
1140                      (setcdr art (+ score (cdr art))))
1141                    (forward-line))))))
1142              
1143
1144 (defun gnus-score-integer (scores header now expire &optional trace)
1145   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1146         entries alist)
1147
1148     ;; Find matches.
1149     (while scores
1150       (setq alist (car scores)
1151             scores (cdr scores)
1152             entries (assoc header alist))
1153       (while (cdr entries)              ;First entry is the header index.
1154         (let* ((rest (cdr entries))             
1155                (kill (car rest))
1156                (match (nth 0 kill))
1157                (type (or (nth 3 kill) '>))
1158                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1159                (date (nth 2 kill))
1160                (found nil)
1161                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1162                                    (eq type '>=) (eq type '=))
1163                                type
1164                              (error "Illegal match type: %s" type)))
1165                (articles gnus-scores-articles))
1166           ;; Instead of doing all the clever stuff that
1167           ;; `gnus-score-string' does to minimize searches and stuff,
1168           ;; I will assume that people generally will put so few
1169           ;; matches on numbers that any cleverness will take more
1170           ;; time than one would gain.
1171           (while articles
1172             (and (funcall match-func 
1173                           (or (aref (car (car articles)) gnus-score-index) 0)
1174                           match)
1175                  (progn
1176                    (and trace (setq gnus-score-trace 
1177                                     (cons
1178                                      (cons
1179                                       (car-safe (rassq alist gnus-score-cache))
1180                                       kill)
1181                                      gnus-score-trace)))
1182                    (setq found t)
1183                    (setcdr (car articles) (+ score (cdr (car articles))))))
1184             (setq articles (cdr articles)))
1185           ;; Update expire date
1186           (cond ((null date))           ;Permanent entry.
1187                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1188                  (gnus-score-set 'touched '(t) alist)
1189                  (setcar (nthcdr 2 kill) now))
1190                 ((and expire (< date expire)) ;Old entry, remove.
1191                  (gnus-score-set 'touched '(t) alist)
1192                  (setcdr entries (cdr rest))
1193                  (setq rest entries)))
1194           (setq entries rest))))))
1195
1196 (defun gnus-score-date (scores header now expire &optional trace)
1197   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1198         entries alist)
1199
1200     ;; Find matches.
1201     (while scores
1202       (setq alist (car scores)
1203             scores (cdr scores)
1204             entries (assoc header alist))
1205       (while (cdr entries)              ;First entry is the header index.
1206         (let* ((rest (cdr entries))             
1207                (kill (car rest))
1208                (match (timezone-make-date-sortable (nth 0 kill)))
1209                (type (or (nth 3 kill) 'before))
1210                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1211                (date (nth 2 kill))
1212                (found nil)
1213                (match-func 
1214                 (cond ((eq type 'after) 'string<)
1215                       ((eq type 'before) 'gnus-string>)
1216                       ((eq type 'at) 'string=)
1217                       (t (error "Illegal match type: %s" type))))
1218                (articles gnus-scores-articles)
1219                l)
1220           ;; Instead of doing all the clever stuff that
1221           ;; `gnus-score-string' does to minimize searches and stuff,
1222           ;; I will assume that people generally will put so few
1223           ;; matches on numbers that any cleverness will take more
1224           ;; time than one would gain.
1225           (while articles
1226             (and
1227              (setq l (aref (car (car articles)) gnus-score-index))
1228              (funcall match-func match (timezone-make-date-sortable l))
1229              (progn
1230                (and trace (setq gnus-score-trace 
1231                                 (cons
1232                                  (cons
1233                                   (car-safe (rassq alist gnus-score-cache))
1234                                   kill)
1235                                  gnus-score-trace)))
1236                (setq found t)
1237                (setcdr (car articles) (+ score (cdr (car articles))))))
1238             (setq articles (cdr articles)))
1239           ;; Update expire date
1240           (cond ((null date))           ;Permanent entry.
1241                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1242                  (gnus-score-set 'touched '(t) alist)
1243                  (setcar (nthcdr 2 kill) now))
1244                 ((and expire (< date expire))   ;Old entry, remove.
1245                  (gnus-score-set 'touched '(t) alist)
1246                  (setcdr entries (cdr rest))
1247                  (setq rest entries)))
1248           (setq entries rest))))))
1249
1250 (defun gnus-score-body (scores header now expire &optional trace)
1251   (save-excursion
1252     (set-buffer nntp-server-buffer)
1253     (save-restriction
1254       (let* ((buffer-read-only nil)
1255              (articles gnus-scores-articles)
1256              (last (mail-header-number (car (car gnus-scores-articles))))
1257              (all-scores scores)
1258              (request-func (cond ((string= "head" (downcase header))
1259                                   'gnus-request-head)
1260                                  ((string= "body" (downcase header))
1261                                   'gnus-request-body)
1262                                  (t 'gnus-request-article)))
1263              entries alist ofunc article)
1264         ;; Not all backends support partial fetching.  In that case,
1265         ;; we just fetch the entire article.
1266         (or (gnus-check-backend-function 
1267              (and (string-match "^gnus-" (symbol-name request-func))
1268                   (intern (substring (symbol-name request-func)
1269                                      (match-end 0))))
1270              gnus-newsgroup-name)
1271             (progn
1272               (setq ofunc request-func)
1273               (setq request-func 'gnus-request-article)))
1274         (while articles
1275           (setq article (mail-header-number (car (car articles))))
1276           (gnus-message 7 "Scoring on article %s of %s..." article last)
1277           (if (not (funcall request-func article gnus-newsgroup-name))
1278               ()
1279             (widen)
1280             (goto-char (point-min))
1281             ;; If just parts of the article is to be searched, but the
1282             ;; backend didn't support partial fetching, we just narrow
1283             ;; to the relevant parts.
1284             (if ofunc
1285                 (if (eq ofunc 'gnus-request-head)
1286                     (narrow-to-region
1287                      (point)
1288                      (or (search-forward "\n\n" nil t) (point-max)))
1289                   (narrow-to-region
1290                    (or (search-forward "\n\n" nil t) (point))
1291                    (point-max))))
1292             (setq scores all-scores)
1293             ;; Find matches.
1294             (while scores
1295               (setq alist (car scores)
1296                     scores (cdr scores)
1297                     entries (assoc header alist))
1298               (while (cdr entries)      ;First entry is the header index.
1299                 (let* ((rest (cdr entries))             
1300                        (kill (car rest))
1301                        (match (nth 0 kill))
1302                        (type (or (nth 3 kill) 's))
1303                        (score (or (nth 1 kill) 
1304                                   gnus-score-interactive-default-score))
1305                        (date (nth 2 kill))
1306                        (found nil)
1307                        (case-fold-search 
1308                         (not (or (eq type 'R) (eq type 'S)
1309                                  (eq type 'Regexp) (eq type 'String))))
1310                        (search-func 
1311                         (cond ((or (eq type 'r) (eq type 'R)
1312                                    (eq type 'regexp) (eq type 'Regexp))
1313                                're-search-forward)
1314                               ((or (eq type 's) (eq type 'S)
1315                                    (eq type 'string) (eq type 'String))
1316                                'search-forward)
1317                               (t
1318                                (error "Illegal match type: %s" type)))))
1319                   (goto-char (point-min))
1320                   (if (funcall search-func match nil t)
1321                       ;; Found a match, update scores.
1322                       (progn
1323                         (setcdr (car articles) (+ score (cdr (car articles))))
1324                         (setq found t)
1325                         (and trace (setq gnus-score-trace 
1326                                          (cons
1327                                           (cons
1328                                            (car-safe
1329                                             (rassq alist gnus-score-cache))
1330                                            kill)
1331                                           gnus-score-trace)))))
1332                   ;; Update expire date
1333                   (cond
1334                    ((null date))        ;Permanent entry.
1335                    ((and found gnus-update-score-entry-dates) ;Match, update date.
1336                     (gnus-score-set 'touched '(t) alist)
1337                     (setcar (nthcdr 2 kill) now))
1338                    ((and expire (< date expire)) ;Old entry, remove.
1339                     (gnus-score-set 'touched '(t) alist)
1340                     (setcdr entries (cdr rest))
1341                     (setq rest entries)))
1342                   (setq entries rest)))))
1343           (setq articles (cdr articles)))))))
1344
1345 (defun gnus-score-followup (scores header now expire &optional trace thread)
1346   ;; Insert the unique article headers in the buffer.
1347   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1348         (current-score-file gnus-current-score-file)
1349         (all-scores scores)
1350         ;; gnus-score-index is used as a free variable.
1351         alike last this art entries alist articles)
1352
1353     ;; Change score file to the adaptive score file.  All entries that
1354     ;; this function makes will be put into this file.
1355     (gnus-score-load-file (gnus-score-file-name 
1356                            gnus-newsgroup-name gnus-adaptive-file-suffix))
1357
1358     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1359           articles gnus-scores-articles)
1360
1361     (erase-buffer)
1362     (while articles
1363       (setq art (car articles)
1364             this (aref (car art) gnus-score-index)
1365             articles (cdr articles))
1366       (if (equal last this)
1367           (setq alike (cons art alike))
1368         (if last
1369             (progn
1370               (insert last ?\n)
1371               (put-text-property (1- (point)) (point) 'articles alike)))
1372         (setq alike (list art)
1373               last this)))
1374     (and last                           ; Bwadr, duplicate code.
1375          (progn
1376            (insert last ?\n)                    
1377            (put-text-property (1- (point)) (point) 'articles alike)))
1378   
1379     ;; Find matches.
1380     (while scores
1381       (setq alist (car scores)
1382             scores (cdr scores)
1383             entries (assoc header alist))
1384       (while (cdr entries)              ;First entry is the header index.
1385         (let* ((rest (cdr entries))             
1386                (kill (car rest))
1387                (match (nth 0 kill))
1388                (type (or (nth 3 kill) 's))
1389                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1390                (date (nth 2 kill))
1391                (found nil)
1392                (mt (aref (symbol-name type) 0))
1393                (case-fold-search 
1394                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1395                (dmt (downcase mt))
1396                (search-func 
1397                 (cond ((= dmt ?r) 're-search-forward)
1398                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1399                       (t (error "Illegal match type: %s" type))))
1400                arts art)
1401           (goto-char (point-min))
1402           (if (= dmt ?e)
1403               (while (funcall search-func match nil t)
1404                 (and (= (progn (beginning-of-line) (point))
1405                         (match-beginning 0))
1406                      (= (progn (end-of-line) (point))
1407                         (match-end 0))
1408                      (progn
1409                        (setq found (setq arts (get-text-property 
1410                                                (point) 'articles)))
1411                        ;; Found a match, update scores.
1412                        (while arts
1413                          (setq art (car arts)
1414                                arts (cdr arts))
1415                          (gnus-score-add-followups 
1416                           (car art) score all-scores thread)))))
1417             (while (funcall search-func match nil t)
1418               (end-of-line)
1419               (setq found (setq arts (get-text-property (point) 'articles)))
1420               ;; Found a match, update scores.
1421               (while arts
1422                 (setq art (car arts)
1423                       arts (cdr arts))
1424                 (gnus-score-add-followups (car art) score all-scores thread))))
1425           ;; Update expire date
1426           (cond ((null date))           ;Permanent entry.
1427                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1428                  (gnus-score-set 'touched '(t) alist)
1429                  (setcar (nthcdr 2 kill) now))
1430                 ((and expire (< date expire))   ;Old entry, remove.
1431                  (gnus-score-set 'touched '(t) alist)
1432                  (setcdr entries (cdr rest))
1433                  (setq rest entries)))
1434           (setq entries rest))))
1435     ;; We change the score file back to the previous one.
1436     (gnus-score-load-file current-score-file)))
1437
1438 (defun gnus-score-add-followups (header score scores &optional thread)
1439   (save-excursion
1440     (set-buffer gnus-summary-buffer)
1441     (let* ((id (mail-header-id header))
1442            (scores (car scores))
1443            entry dont)
1444       ;; Don't enter a score if there already is one.
1445       (while scores
1446         (setq entry (car scores))
1447         (and (equal "references" (car entry))
1448              (or (null (nth 3 (car (cdr entry))))
1449                  (eq 's (nth 3 (car (cdr entry)))))
1450              (progn
1451                (if (assoc id entry)
1452                    (setq dont t))))
1453         (setq scores (cdr scores)))
1454       (or dont
1455           (gnus-summary-score-entry 
1456            (if thread "thread" "references")
1457            id 's score (current-time-string) nil t)))))
1458
1459
1460 (defun gnus-score-string (score-list header now expire &optional trace)
1461   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1462   ;; Update matching entries to NOW and remove unmatched entries older
1463   ;; than EXPIRE.
1464   
1465   ;; Insert the unique article headers in the buffer.
1466   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1467         ;; gnus-score-index is used as a free variable.
1468         alike last this art entries alist articles scores fuzzy)
1469
1470     ;; Sorting the articles costs os O(N*log N) but will allow us to
1471     ;; only match with each unique header.  Thus the actual matching
1472     ;; will be O(M*U) where M is the number of strings to match with,
1473     ;; and U is the number of unique headers.  It is assumed (but
1474     ;; untested) this will be a net win because of the large constant
1475     ;; factor involved with string matching.
1476     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1477           articles gnus-scores-articles)
1478
1479     (erase-buffer)
1480     (while articles
1481       (setq art (car articles)
1482             this (aref (car art) gnus-score-index)
1483             articles (cdr articles))
1484       (if (equal last this)
1485           ;; O(N*H) cons-cells used here, where H is the number of
1486           ;; headers.
1487           (setq alike (cons art alike))
1488         (if last
1489             (progn
1490               ;; Insert the line, with a text property on the
1491               ;; terminating newline referring to the articles with
1492               ;; this line.
1493               (insert last ?\n)
1494               (put-text-property (1- (point)) (point) 'articles alike)))
1495         (setq alike (list art)
1496               last this)))
1497     (and last                           ; Bwadr, duplicate code.
1498          (progn
1499            (insert last ?\n)                    
1500            (put-text-property (1- (point)) (point) 'articles alike)))
1501
1502     ;; Find ordinary matches.
1503     (setq scores score-list) 
1504     (while scores
1505       (setq alist (car scores)
1506             scores (cdr scores)
1507             entries (assoc header alist))
1508       (while (cdr entries)              ;First entry is the header index.
1509         (let* ((rest (cdr entries))             
1510                (kill (car rest))
1511                (match (nth 0 kill))
1512                (type (or (nth 3 kill) 's))
1513                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1514                (date (nth 2 kill))
1515                (found nil)
1516                (mt (aref (symbol-name type) 0))
1517                (case-fold-search 
1518                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1519                (dmt (downcase mt))
1520                (search-func 
1521                 (cond ((= dmt ?r) 're-search-forward)
1522                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1523                       (t (error "Illegal match type: %s" type))))
1524                arts art)
1525           (if (= dmt ?f)
1526               (setq fuzzy t)
1527             ;; Do non-fuzzy matching.
1528             (goto-char (point-min))
1529             (if (= dmt ?e)
1530                 ;; Do exact matching.
1531                 (while (and (not (eobp)) 
1532                             (funcall search-func match nil t))
1533                   (and (= (progn (beginning-of-line) (point))
1534                           (match-beginning 0))
1535                        (= (progn (end-of-line) (point))
1536                           (match-end 0))
1537                        (progn
1538                          (setq found (setq arts (get-text-property 
1539                                                  (point) 'articles)))
1540                          ;; Found a match, update scores.
1541                          (if trace
1542                              (while arts
1543                                (setq art (car arts)
1544                                      arts (cdr arts))
1545                                (setcdr art (+ score (cdr art)))
1546                                (setq gnus-score-trace
1547                                      (cons
1548                                       (cons
1549                                        (car-safe
1550                                         (rassq alist gnus-score-cache))
1551                                        kill)
1552                                       gnus-score-trace)))
1553                            (while arts
1554                              (setq art (car arts)
1555                                    arts (cdr arts))
1556                              (setcdr art (+ score (cdr art)))))))
1557                   (forward-line 1))
1558               ;; Do regexp and substring matching.
1559               (and (string= match "") (setq match "\n"))
1560               (while (and (not (eobp))
1561                           (funcall search-func match nil t))
1562                 (goto-char (match-beginning 0))
1563                 (end-of-line)
1564                 (setq found (setq arts (get-text-property (point) 'articles)))
1565                 ;; Found a match, update scores.
1566                 (if trace
1567                     (while arts
1568                       (setq art (pop arts))
1569                       (setcdr art (+ score (cdr art)))
1570                       (push (cons
1571                               (car-safe (rassq alist gnus-score-cache))
1572                               kill)
1573                             gnus-score-trace))
1574                   (while arts
1575                     (setq art (pop arts))
1576                     (setcdr art (+ score (cdr art)))))
1577                 (forward-line 1)))
1578             ;; Update expire date
1579             (cond 
1580              ((null date))              ;Permanent entry.
1581              ((and found gnus-update-score-entry-dates) ;Match, update date.
1582               (gnus-score-set 'touched '(t) alist)
1583               (setcar (nthcdr 2 kill) now))
1584              ((and expire (< date expire)) ;Old entry, remove.
1585               (gnus-score-set 'touched '(t) alist)
1586               (setcdr entries (cdr rest))
1587               (setq rest entries))))
1588           (setq entries rest))))
1589
1590     ;; Find fuzzy matches.
1591     (when fuzzy
1592       (setq scores score-list)
1593       (gnus-simplify-buffer-fuzzy)
1594       (while scores
1595         (setq alist (car scores)
1596               scores (cdr scores)
1597               entries (assoc header alist))
1598         (while (cdr entries)            ;First entry is the header index.
1599           (let* ((rest (cdr entries))           
1600                  (kill (car rest))
1601                  (match (nth 0 kill))
1602                  (type (or (nth 3 kill) 's))
1603                  (score (or (nth 1 kill) gnus-score-interactive-default-score))
1604                  (date (nth 2 kill))
1605                  (found nil)
1606                  (mt (aref (symbol-name type) 0))
1607                  (case-fold-search (not (= mt ?F)))
1608                  (dmt (downcase mt))
1609                  arts art)
1610             (when (= dmt ?f)
1611               (goto-char (point-min))
1612               (while (and (not (eobp)) 
1613                           (search-forward match nil t))
1614                 (when (and (= (progn (beginning-of-line) (point))
1615                               (match-beginning 0))
1616                            (= (progn (end-of-line) (point))
1617                               (match-end 0)))
1618                   (setq found (setq arts (get-text-property 
1619                                           (point) 'articles)))
1620                   ;; Found a match, update scores.
1621                   (if trace
1622                       (while arts
1623                         (setq art (pop arts))
1624                         (setcdr art (+ score (cdr art)))
1625                         (push (cons
1626                                (car-safe (rassq alist gnus-score-cache))
1627                                kill)
1628                               gnus-score-trace))
1629                     (while arts
1630                       (setq art (pop arts))
1631                       (setcdr art (+ score (cdr art))))))
1632                 (forward-line 1))
1633               ;; Update expire date
1634               (unless trace
1635                 (cond 
1636                  ((null date))          ;Permanent entry.
1637                  ((and found gnus-update-score-entry-dates) ;Match, update date.
1638                   (gnus-score-set 'touched '(t) alist)
1639                   (setcar (nthcdr 2 kill) now))
1640                  ((and expire (< date expire)) ;Old entry, remove.
1641                   (gnus-score-set 'touched '(t) alist)
1642                   (setcdr entries (cdr rest))
1643                   (setq rest entries)))))
1644             (setq entries rest)))))))
1645
1646 (defun gnus-score-string< (a1 a2)
1647   ;; Compare headers in articles A2 and A2.
1648   ;; The header index used is the free variable `gnus-score-index'.
1649   (string-lessp (aref (car a1) gnus-score-index)
1650                 (aref (car a2) gnus-score-index)))
1651
1652 (defun gnus-score-build-cons (article)
1653   ;; Build a `gnus-newsgroup-scored' type cons from ARTICLE.
1654   (cons (mail-header-number (car article)) (cdr article)))
1655
1656 (defconst gnus-header-index
1657   ;; Name to index alist.
1658   '(("number" 0 gnus-score-integer)
1659     ("subject" 1 gnus-score-string)
1660     ("from" 2 gnus-score-string)
1661     ("date" 3 gnus-score-date)
1662     ("message-id" 4 gnus-score-string) 
1663     ("references" 5 gnus-score-string) 
1664     ("chars" 6 gnus-score-integer) 
1665     ("lines" 7 gnus-score-integer) 
1666     ("xref" 8 gnus-score-string)
1667     ("head" -1 gnus-score-body)
1668     ("body" -1 gnus-score-body)
1669     ("all" -1 gnus-score-body)
1670     ("followup" 2 gnus-score-followup)
1671     ("thread" 5 gnus-score-thread)))
1672
1673 (defun gnus-current-score-file-nondirectory (&optional score-file)
1674   (let ((score-file (or score-file gnus-current-score-file)))
1675     (if score-file 
1676         (gnus-short-group-name (file-name-nondirectory score-file))
1677       "none")))
1678
1679 (defun gnus-score-adaptive ()
1680   (save-excursion
1681     (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
1682            (alist malist)
1683            (date (current-time-string)) 
1684            (data gnus-newsgroup-data)
1685            elem headers match)
1686       ;; First we transform the adaptive rule alist into something
1687       ;; that's faster to process.
1688       (while malist
1689         (setq elem (car malist))
1690         (if (symbolp (car elem))
1691             (setcar elem (symbol-value (car elem))))
1692         (setq elem (cdr elem))
1693         (while elem
1694           (setcdr (car elem) 
1695                   (cons (if (eq (car (car elem)) 'followup)
1696                             "references"
1697                           (symbol-name (car (car elem))))
1698                         (cdr (car elem))))
1699           (setcar (car elem) 
1700                   `(lambda (h)
1701                      (,(intern 
1702                         (concat "mail-header-" 
1703                                 (if (eq (car (car elem)) 'followup)
1704                                     "message-id"
1705                                   (downcase (symbol-name (car (car elem)))))))
1706                       h)))
1707           (setq elem (cdr elem)))
1708         (setq malist (cdr malist)))
1709       ;; We change the score file to the adaptive score file.
1710       (gnus-score-load-file 
1711        (or gnus-newsgroup-adaptive-score-file
1712            (gnus-score-file-name 
1713             gnus-newsgroup-name gnus-adaptive-file-suffix)))
1714       ;; The we score away.
1715       (while data
1716         (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
1717         (if (or (not elem)
1718                 (gnus-data-pseudo-p (car data)))
1719             ()
1720           (when (setq headers (gnus-data-header (car data)))
1721             (while elem 
1722               (setq match (funcall (car (car elem)) headers))
1723               (gnus-summary-score-entry 
1724                (nth 1 (car elem)) match
1725                (cond
1726                 ((numberp match)
1727                  '=)
1728                 ((equal (nth 1 (car elem)) "date")
1729                  'a)
1730                 (t
1731                  ;; Whether we use substring or exact matches are controlled
1732                  ;; here.  
1733                  (if (or (not gnus-score-exact-adapt-limit)
1734                          (< (length match) gnus-score-exact-adapt-limit))
1735                      'e 
1736                    (if (equal (nth 1 (car elem)) "subject")
1737                        'f 's))))
1738                (nth 2 (car elem)) date nil t)
1739               (setq elem (cdr elem)))))
1740         (setq data (cdr data))))))
1741
1742 ;;;
1743 ;;; Score mode.
1744 ;;;
1745
1746 (defvar gnus-score-mode-map nil)
1747 (defvar gnus-score-mode-hook nil)
1748
1749 (if gnus-score-mode-map
1750     ()
1751   (setq gnus-score-mode-map (copy-keymap emacs-lisp-mode-map))
1752   (define-key gnus-score-mode-map "\C-c\C-c" 'gnus-score-edit-done)
1753   (define-key gnus-score-mode-map "\C-c\C-d" 'gnus-score-edit-insert-date))
1754
1755 (defun gnus-score-mode ()
1756   "Mode for editing score files.
1757 This mode is an extended emacs-lisp mode.
1758
1759 \\{gnus-score-mode-map}"
1760   (interactive)
1761   (kill-all-local-variables)
1762   (use-local-map gnus-score-mode-map)
1763   (set-syntax-table emacs-lisp-mode-syntax-table)
1764   (setq major-mode 'gnus-score-mode)
1765   (setq mode-name "Score")
1766   (lisp-mode-variables nil)
1767   (run-hooks 'emacs-lisp-mode-hook 'gnus-score-mode-hook))
1768
1769 (defun gnus-score-edit-insert-date ()
1770   "Insert date in numerical format."
1771   (interactive)
1772   (insert (int-to-string (gnus-day-number (current-time-string)))))
1773
1774 (defun gnus-score-edit-done ()
1775   "Save the score file and return to the summary buffer."
1776   (interactive)
1777   (let ((bufnam (buffer-file-name (current-buffer)))
1778         (winconf gnus-prev-winconf))
1779     (gnus-make-directory (file-name-directory (buffer-file-name)))
1780     (save-buffer)
1781     (kill-buffer (current-buffer))
1782     (gnus-score-remove-from-cache bufnam)
1783     (gnus-score-load-file bufnam)
1784     (and winconf (set-window-configuration winconf))))
1785
1786 (defun gnus-score-find-trace ()
1787   "Find all score rules that applies to the current article."
1788   (interactive)
1789   (let ((gnus-newsgroup-headers
1790          (list (gnus-summary-article-header)))
1791         (gnus-newsgroup-scored nil)
1792         (buf (current-buffer))
1793         trace)
1794     (setq gnus-score-trace nil)
1795     (gnus-possibly-score-headers 'trace)
1796     (or (setq trace gnus-score-trace)
1797         (error "No score rules apply to the current article."))
1798     (pop-to-buffer "*Gnus Scores*")
1799     (gnus-add-current-to-buffer-list)
1800     (erase-buffer)
1801     (while trace
1802       (insert (format "%S  ->  %s\n"  (cdr (car trace))
1803                       (file-name-nondirectory (car (car trace)))))
1804       (setq trace (cdr trace)))
1805     (goto-char (point-min))
1806     (pop-to-buffer buf)))
1807
1808 (defun gnus-summary-rescore ()
1809   "Redo the entire scoring process in the current summary."
1810   (interactive)
1811   (setq gnus-newsgroup-scored nil)
1812   (setq gnus-score-cache nil)
1813   (setq gnus-newsgroup-scored nil)
1814   (gnus-possibly-score-headers)
1815   (gnus-score-update-all-lines))
1816   
1817 (defun gnus-score-flush-cache ()
1818   "Flush the cache of score files."
1819   (interactive)
1820   (setq gnus-score-cache nil)
1821   (gnus-message 6 "The score cache is now flushed"))
1822
1823 (defun gnus-score-close ()
1824   "Clear all internal score variables."
1825   (setq gnus-score-cache nil
1826         gnus-internal-global-score-files nil))
1827
1828 ;; Summary score marking commands.
1829
1830 (defun gnus-summary-raise-same-subject-and-select (score)
1831   "Raise articles which has the same subject with SCORE and select the next."
1832   (interactive "p")
1833   (let ((subject (gnus-summary-article-subject)))
1834     (gnus-summary-raise-score score)
1835     (while (gnus-summary-find-subject subject)
1836       (gnus-summary-raise-score score))
1837     (gnus-summary-next-article t)))
1838
1839 (defun gnus-summary-raise-same-subject (score)
1840   "Raise articles which has the same subject with SCORE."
1841   (interactive "p")
1842   (let ((subject (gnus-summary-article-subject)))
1843     (gnus-summary-raise-score score)
1844     (while (gnus-summary-find-subject subject)
1845       (gnus-summary-raise-score score))
1846     (gnus-summary-next-subject 1 t)))
1847
1848 (defun gnus-score-default (level)
1849   (if level (prefix-numeric-value level) 
1850     gnus-score-interactive-default-score))
1851
1852 (defun gnus-summary-raise-thread (&optional score)
1853   "Raise the score of the articles in the current thread with SCORE."
1854   (interactive "P")
1855   (setq score (gnus-score-default score))
1856   (let (e)
1857     (save-excursion
1858       (let ((articles (gnus-summary-articles-in-thread)))
1859         (while articles
1860           (gnus-summary-goto-subject (car articles))
1861           (gnus-summary-raise-score score)
1862           (setq articles (cdr articles))))
1863       (setq e (point)))
1864     (let ((gnus-summary-check-current t))
1865       (or (zerop (gnus-summary-next-subject 1 t))
1866           (goto-char e))))
1867   (gnus-summary-recenter)
1868   (gnus-summary-position-point)
1869   (gnus-set-mode-line 'summary))
1870
1871 (defun gnus-summary-lower-same-subject-and-select (score)
1872   "Raise articles which has the same subject with SCORE and select the next."
1873   (interactive "p")
1874   (gnus-summary-raise-same-subject-and-select (- score)))
1875
1876 (defun gnus-summary-lower-same-subject (score)
1877   "Raise articles which has the same subject with SCORE."
1878   (interactive "p")
1879   (gnus-summary-raise-same-subject (- score)))
1880
1881 (defun gnus-summary-lower-thread (&optional score)
1882   "Lower score of articles in the current thread with SCORE."
1883   (interactive "P")
1884   (gnus-summary-raise-thread (- (1- (gnus-score-default score)))))
1885
1886 ;;; Finding score files. 
1887
1888 (defun gnus-score-score-files (group)
1889   "Return a list of all possible score files."
1890   ;; Search and set any global score files.
1891   (and gnus-global-score-files 
1892        (or gnus-internal-global-score-files
1893            (gnus-score-search-global-directories gnus-global-score-files)))
1894   ;; Fix the kill-file dir variable.
1895   (setq gnus-kill-files-directory 
1896         (file-name-as-directory
1897          (or gnus-kill-files-directory "~/News/")))
1898   ;; If we can't read it, there are no score files.
1899   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
1900       (setq gnus-score-file-list nil)
1901     (if (not (gnus-use-long-file-name 'not-score))
1902         ;; We do not use long file names, so we have to do some
1903         ;; directory traversing.  
1904         (setq gnus-score-file-list 
1905               (cons nil (gnus-score-score-files-1 gnus-kill-files-directory)))
1906       ;; We want long file names.
1907       (when (or (not gnus-score-file-list)
1908                 (not (car gnus-score-file-list))
1909                 (gnus-file-newer-than gnus-kill-files-directory
1910                                       (car gnus-score-file-list)))
1911         (setq gnus-score-file-list 
1912               (cons (nth 5 (file-attributes gnus-kill-files-directory))
1913                     (nreverse 
1914                      (directory-files 
1915                       gnus-kill-files-directory t 
1916                       (gnus-score-file-regexp)))))))
1917     (cdr gnus-score-file-list)))
1918
1919 (defun gnus-score-score-files-1 (dir)
1920   "Return all possible score files under DIR."
1921   (let ((files (directory-files (expand-file-name dir) t nil t))
1922         (regexp (gnus-score-file-regexp))
1923         out file)
1924     (while files
1925       (setq file (pop files))
1926       (cond 
1927        ((string-match "/\\.\\.?\\'" file)
1928         nil)
1929        ((file-directory-p file)
1930         (setq out (nconc (gnus-score-score-files-1 file) out)))
1931        ((string-match regexp file)
1932         (push file out))))
1933     out))
1934        
1935 (defun gnus-score-file-regexp ()
1936   "Return a regexp that match all score files."
1937   (concat "\\(" gnus-score-file-suffix 
1938           "\\|" gnus-adaptive-file-suffix "\\)\\'"))
1939         
1940 (defun gnus-score-find-bnews (group)
1941   "Return a list of score files for GROUP.
1942 The score files are those files in the ~/News/ directory which matches
1943 GROUP using BNews sys file syntax."
1944   (let* ((sfiles (append (gnus-score-score-files group)
1945                          gnus-internal-global-score-files))
1946          (kill-dir (file-name-as-directory 
1947                     (expand-file-name gnus-kill-files-directory)))
1948          (klen (length kill-dir))
1949          (score-regexp (gnus-score-file-regexp))
1950          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
1951          ofiles not-match regexp)
1952     (save-excursion
1953       (set-buffer (get-buffer-create "*gnus score files*"))
1954       (buffer-disable-undo (current-buffer))
1955       ;; Go through all score file names and create regexp with them
1956       ;; as the source.  
1957       (while sfiles
1958         (erase-buffer)
1959         (insert (car sfiles))
1960         (goto-char (point-min))
1961         ;; First remove the suffix itself.
1962         (when (re-search-forward (concat "." score-regexp) nil t)
1963           (replace-match "" t t) 
1964           (goto-char (point-min))
1965           (if (looking-at (regexp-quote kill-dir))
1966               ;; If the file name was just "SCORE", `klen' is one character
1967               ;; too much.
1968               (delete-char (min (1- (point-max)) klen))
1969             (goto-char (point-max))
1970             (search-backward "/")
1971             (delete-region (1+ (point)) (point-min)))
1972           ;; If short file names were used, we have to translate slashes.
1973           (goto-char (point-min))
1974           (let ((regexp (concat
1975                          "[/:" (if trans (char-to-string trans) "") "]")))
1976             (while (re-search-forward regexp nil t)
1977               (replace-match "." t t)))
1978           ;; Cludge to get rid of "nntp+" problems.
1979           (goto-char (point-min))
1980           (and (looking-at "nn[a-z]+\\+")
1981                (progn
1982                  (search-forward "+")
1983                  (forward-char -1)
1984                  (insert "\\")))
1985           ;; Translate "all" to ".*".
1986           (while (search-forward "all" nil t)
1987             (replace-match ".*" t t))
1988           (goto-char (point-min))
1989           ;; Deal with "not."s.
1990           (if (looking-at "not.")
1991               (progn
1992                 (setq not-match t)
1993                 (setq regexp (buffer-substring 5 (point-max))))
1994             (setq regexp (buffer-substring 1 (point-max)))
1995             (setq not-match nil))
1996           ;; Finally - if this resulting regexp matches the group name,
1997           ;; we add this score file to the list of score files
1998           ;; applicable to this group.
1999           (if (or (and not-match
2000                        (not (string-match regexp group)))
2001                   (and (not not-match)
2002                        (string-match regexp group)))
2003               (setq ofiles (cons (car sfiles) ofiles))))
2004         (setq sfiles (cdr sfiles)))
2005       (kill-buffer (current-buffer))
2006       ;; Slight kludge here - the last score file returned should be
2007       ;; the local score file, whether it exists or not. This is so
2008       ;; that any score commands the user enters will go to the right
2009       ;; file, and not end up in some global score file.
2010       (let ((localscore (gnus-score-file-name group)))
2011         (setq ofiles (cons localscore (delete localscore ofiles))))
2012       (nreverse ofiles))))
2013
2014 (defun gnus-score-find-single (group)
2015   "Return list containing the score file for GROUP."
2016   (list (gnus-score-file-name group gnus-adaptive-file-suffix)
2017         (gnus-score-file-name group)))
2018
2019 (defun gnus-score-find-hierarchical (group)
2020   "Return list of score files for GROUP.
2021 This includes the score file for the group and all its parents."
2022   (let ((all (copy-sequence '(nil)))
2023         (start 0))
2024     (while (string-match "\\." group (1+ start))
2025       (setq start (match-beginning 0))
2026       (setq all (cons (substring group 0 start) all)))
2027     (setq all (cons group all))
2028     (nconc
2029      (mapcar (lambda (newsgroup)
2030                (gnus-score-file-name newsgroup gnus-adaptive-file-suffix))
2031              (setq all (nreverse all)))
2032      (mapcar 'gnus-score-file-name all))))
2033
2034 (defvar gnus-score-file-alist-cache nil)
2035
2036 (defun gnus-score-find-alist (group)
2037   "Return list of score files for GROUP.
2038 The list is determined from the variable gnus-score-file-alist."
2039   (let ((alist gnus-score-file-multiple-match-alist)
2040         score-files)
2041     ;; if this group has been seen before, return the cached entry
2042     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2043         (cdr score-files)               ;ensures caching groups with no matches
2044       ;; handle the multiple match alist
2045       (while alist
2046         (and (string-match (car (car alist)) group)
2047              (setq score-files
2048                    (nconc score-files (copy-sequence (cdr (car alist))))))
2049         (setq alist (cdr alist)))
2050       (setq alist gnus-score-file-single-match-alist)
2051       ;; handle the single match alist
2052       (while alist
2053         (and (string-match (car (car alist)) group)
2054              ;; progn used just in case ("regexp") has no files
2055              ;; and score-files is still nil. -sj
2056              ;; this can be construed as a "stop searching here" feature :>
2057              ;; and used to simplify regexps in the single-alist 
2058              (progn
2059                (setq score-files
2060                      (nconc score-files (copy-sequence (cdr (car alist)))))
2061                (setq alist nil)))
2062         (setq alist (cdr alist)))
2063       ;; cache the score files
2064       (setq gnus-score-file-alist-cache
2065             (cons (cons group score-files) gnus-score-file-alist-cache))
2066       score-files)))
2067
2068 (defun gnus-possibly-score-headers (&optional trace)
2069   (let ((funcs gnus-score-find-score-files-function)
2070         score-files)
2071     ;; Make sure funcs is a list.
2072     (and funcs
2073          (not (listp funcs))
2074          (setq funcs (list funcs)))
2075     ;; Get the initial score files for this group.
2076     (when funcs 
2077       (setq score-files (gnus-score-find-alist gnus-newsgroup-name)))
2078     ;; Go through all the functions for finding score files (or actual
2079     ;; scores) and add them to a list.
2080     (while funcs
2081       (when (gnus-functionp (car funcs))
2082         (setq score-files 
2083               (nconc score-files (funcall (car funcs) gnus-newsgroup-name))))
2084       (setq funcs (cdr funcs)))
2085     ;; Check whether there is a `score-file' group parameter.
2086     (let ((param-file (gnus-group-get-parameter 
2087                        gnus-newsgroup-name 'score-file)))
2088       (when param-file
2089         (push param-file score-files)))
2090     ;; Do the scoring if there are any score files for this group.
2091     (when score-files
2092       (gnus-score-headers score-files trace))))
2093
2094 (defun gnus-score-file-name (newsgroup &optional suffix)
2095   "Return the name of a score file for NEWSGROUP."
2096   (let ((suffix (or suffix gnus-score-file-suffix)))
2097     (nnheader-translate-file-chars
2098      (cond
2099       ((or (null newsgroup)
2100            (string-equal newsgroup ""))
2101        ;; The global score file is placed at top of the directory.
2102        (expand-file-name 
2103         suffix (or gnus-kill-files-directory "~/News")))
2104       ((gnus-use-long-file-name 'not-score)
2105        ;; Append ".SCORE" to newsgroup name.
2106        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2107                                  "." suffix)
2108                          (or gnus-kill-files-directory "~/News")))
2109       (t
2110        ;; Place "SCORE" under the hierarchical directory.
2111        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2112                                  "/" suffix)
2113                          (or gnus-kill-files-directory "~/News")))))))
2114
2115 (defun gnus-score-search-global-directories (files)
2116   "Scan all global score directories for score files."
2117   ;; Set the variable `gnus-internal-global-score-files' to all
2118   ;; available global score files.
2119   (interactive (list gnus-global-score-files))
2120   (let (out)
2121     (while files
2122       (if (string-match "/$" (car files))
2123           (setq out (nconc (directory-files 
2124                             (car files) t
2125                             (concat (gnus-score-file-regexp) "$"))))
2126         (setq out (cons (car files) out)))
2127       (setq files (cdr files)))
2128     (setq gnus-internal-global-score-files out)))
2129
2130 (provide 'gnus-score)
2131
2132 ;;; gnus-score.el ends here