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