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