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