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