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