*** 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       (set-buffer gnus-summary-buffer)
724       (save-restriction
725         (goto-char (point-min))
726         (let ((id (mail-fetch-field "message-id")))
727           (when id
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       (set-buffer gnus-summary-buffer)
739       (save-restriction
740         (goto-char (point-min))
741         (let ((id (mail-fetch-field "message-id")))
742           (when id
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 gnus-kill-files-directory file))))
847          (cached (assoc file gnus-score-cache))
848          (global (member file gnus-internal-global-score-files))
849          lists alist)
850     (if cached
851         ;; The score file was already loaded.
852         (setq alist (cdr cached))
853       ;; We load the score file.
854       (setq gnus-score-alist nil)
855       (setq alist (gnus-score-load-score-alist file))
856       ;; We add '(touched) to the alist to signify that it hasn't been
857       ;; touched (yet). 
858       (or (assq 'touched alist) (setq alist (cons (list 'touched nil) alist)))
859       ;; If it is a global score file, we make it read-only.
860       (and global
861            (not (assq 'read-only alist))
862            (setq alist (cons (list 'read-only t) alist)))
863       (setq gnus-score-cache
864             (cons (cons file alist) gnus-score-cache)))
865     (let ((a alist)
866           found)
867       (while a
868         ;; Downcase all header names.
869         (when (stringp (caar a))
870           (setcar (car a) (downcase (caar a)))
871           (setq found t))
872         (pop a))
873       ;; If there are actual scores in the alist, we add it to the
874       ;; return value of this function.
875       (when found
876         (setq lists (list alist))))
877     ;; Treat the other possible atoms in the score alist.
878     (let ((mark (car (gnus-score-get 'mark alist)))
879           (expunge (car (gnus-score-get 'expunge alist)))
880           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
881           (files (gnus-score-get 'files alist))
882           (exclude-files (gnus-score-get 'exclude-files alist))
883           (orphan (car (gnus-score-get 'orphan alist)))
884           (adapt (gnus-score-get 'adapt alist))
885           (thread-mark-and-expunge
886            (car (gnus-score-get 'thread-mark-and-expunge alist)))
887           (adapt-file (car (gnus-score-get 'adapt-file alist)))
888           (local (gnus-score-get 'local alist))
889           (eval (car (gnus-score-get 'eval alist))))
890       ;; We do not respect eval and files atoms from global score
891       ;; files. 
892       (and files (not global)
893            (setq lists (apply 'append lists
894                               (mapcar (lambda (file)
895                                         (gnus-score-load-file file)) 
896                                       (if adapt-file (cons adapt-file files)
897                                         files)))))
898       (and eval (not global) (eval eval))
899       ;; We then expand any exclude-file directives.
900       (setq gnus-scores-exclude-files 
901             (nconc 
902              (mapcar 
903               (lambda (sfile) 
904                 (expand-file-name sfile (file-name-directory file)))
905               exclude-files) gnus-scores-exclude-files))
906       (if (not local)
907           ()
908         (save-excursion
909           (set-buffer gnus-summary-buffer)
910           (while local
911             (and (consp (car local))
912                  (symbolp (caar local))
913                  (progn
914                    (make-local-variable (caar local))
915                    (set (caar local) (nth 1 (car local)))))
916             (setq local (cdr local)))))
917       (if orphan (setq gnus-orphan-score orphan))
918       (setq gnus-adaptive-score-alist
919             (cond ((equal adapt '(t))
920                    (setq gnus-newsgroup-adaptive t)
921                    gnus-default-adaptive-score-alist)
922                   ((equal adapt '(ignore))
923                    (setq gnus-newsgroup-adaptive nil))
924                   ((consp adapt)
925                    (setq gnus-newsgroup-adaptive t)
926                    adapt)
927                   (t
928                    ;;(setq gnus-newsgroup-adaptive gnus-use-adaptive-scoring)
929                    gnus-default-adaptive-score-alist)))
930       (setq gnus-thread-expunge-below 
931             (or thread-mark-and-expunge gnus-thread-expunge-below))
932       (setq gnus-summary-mark-below 
933             (or mark mark-and-expunge gnus-summary-mark-below))
934       (setq gnus-summary-expunge-below 
935             (or expunge mark-and-expunge gnus-summary-expunge-below))
936       (setq gnus-newsgroup-adaptive-score-file 
937             (or adapt-file gnus-newsgroup-adaptive-score-file)))
938     (setq gnus-current-score-file file)
939     (setq gnus-score-alist alist)
940     lists))
941
942 (defun gnus-score-load (file)
943   ;; Load score FILE.
944   (let ((cache (assoc file gnus-score-cache)))
945     (if cache
946         (setq gnus-score-alist (cdr cache))
947       (setq gnus-score-alist nil)
948       (gnus-score-load-score-alist file)
949       (or gnus-score-alist
950           (setq gnus-score-alist (copy-alist '((touched nil)))))
951       (setq gnus-score-cache
952             (cons (cons file gnus-score-alist) gnus-score-cache)))))
953
954 (defun gnus-score-remove-from-cache (file)
955   (setq gnus-score-cache 
956         (delq (assoc file gnus-score-cache) gnus-score-cache)))
957
958 (defun gnus-score-load-score-alist (file)
959   (let (alist)
960     (if (not (file-readable-p file))
961         (setq gnus-score-alist nil)
962       (save-excursion
963         (gnus-set-work-buffer)
964         (insert-file-contents file)
965         (goto-char (point-min))
966         ;; Only do the loading if the score file isn't empty.
967         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
968           (setq alist
969                 (condition-case ()
970                     (read (current-buffer))
971                   (error 
972                    (progn
973                      (gnus-message 3 "Problem with score file %s" file)
974                      (ding) 
975                      (sit-for 2)
976                      nil))))))
977       (if (eq (car alist) 'setq)
978           ;; This is an old-style score file.
979           (setq gnus-score-alist (gnus-score-transform-old-to-new alist))
980         (setq gnus-score-alist alist))
981       ;; Check the syntax of the score file.
982       (setq gnus-score-alist
983             (gnus-score-check-syntax gnus-score-alist file)))))
984
985 (defun gnus-score-check-syntax (alist file)
986   "Check the syntax of the score ALIST."
987   (cond 
988    ((null alist)
989     nil)
990    ((not (consp alist))
991     (gnus-message 1 "Score file is not a list: %s" file)
992     (ding)
993     nil)
994    (t
995     (let ((a alist)
996           sr err s type)
997       (while (and a (not err))
998         (setq
999          err
1000          (cond
1001           ((not (listp (car a)))
1002            (format "Illegal score element %s in %s" (car a) file))
1003           ((stringp (caar a))
1004            (cond 
1005             ((not (listp (setq sr (cdar a))))
1006              (format "Illegal header match %s in %s" (nth 1 (car a)) file))
1007             (t
1008              (setq type (caar a))
1009              (while (and sr (not err))
1010                (setq s (pop sr))
1011                (setq 
1012                 err
1013                 (cond
1014                  ((if (member (downcase type) '("lines" "chars"))
1015                       (not (numberp (car s)))
1016                     (not (stringp (car s))))
1017                   (format "Illegal match %s in %s" (car s) file))
1018                  ((and (cadr s) (not (integerp (cadr s))))
1019                   (format "Non-integer score %s in %s" (cadr s) file))
1020                  ((and (caddr s) (not (integerp (caddr s))))
1021                   (format "Non-integer date %s in %s" (caddr s) file))
1022                  ((and (cadddr s) (not (symbolp (cadddr s))))
1023                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1024              err)))))
1025         (setq a (cdr a)))
1026       (if err
1027           (progn
1028             (ding)
1029             (gnus-message 3 err)
1030             (sit-for 2)
1031             nil)
1032         alist)))))    
1033
1034 (defun gnus-score-transform-old-to-new (alist)
1035   (let* ((alist (nth 2 alist))
1036          out entry)
1037     (if (eq (car alist) 'quote)
1038         (setq alist (nth 1 alist)))
1039     (while alist
1040       (setq entry (car alist))
1041       (if (stringp (car entry))
1042           (let ((scor (cdr entry)))
1043             (setq out (cons entry out))
1044             (while scor
1045               (setcar scor
1046                       (list (caar scor) (nth 2 (car scor))
1047                             (and (nth 3 (car scor))
1048                                  (gnus-day-number (nth 3 (car scor))))
1049                             (if (nth 1 (car scor)) 'r 's)))
1050               (setq scor (cdr scor))))
1051         (setq out (cons (if (not (listp (cdr entry))) 
1052                             (list (car entry) (cdr entry))
1053                           entry)
1054                         out)))
1055       (setq alist (cdr alist)))
1056     (cons (list 'touched t) (nreverse out))))
1057   
1058 (defun gnus-score-save ()
1059   ;; Save all score information.
1060   (let ((cache gnus-score-cache))
1061     (save-excursion
1062       (setq gnus-score-alist nil)
1063       (set-buffer (get-buffer-create "*Score*"))
1064       (buffer-disable-undo (current-buffer))
1065       (let (entry score file)
1066         (while cache
1067           (setq entry (car cache)
1068                 cache (cdr cache)
1069                 file (car entry)
1070                 score (cdr entry))
1071           (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1072                   (gnus-score-get 'read-only score)
1073                   (and (file-exists-p file)
1074                        (not (file-writable-p file))))
1075               ()
1076             (setq score (setcdr entry (delq (assq 'touched score) score)))
1077             (erase-buffer)
1078             (let (emacs-lisp-mode-hook)
1079               (if (string-match 
1080                    (concat (regexp-quote gnus-adaptive-file-suffix)
1081                            "$") file)
1082                   ;; This is an adaptive score file, so we do not run
1083                   ;; it through `pp'.  These files can get huge, and
1084                   ;; are not meant to be edited by human hands.
1085                   (prin1 score (current-buffer))
1086                 ;; This is a normal score file, so we print it very
1087                 ;; prettily. 
1088                 (pp score (current-buffer))))
1089             (if (not (gnus-make-directory (file-name-directory file)))
1090                 ()
1091               ;; If the score file is empty, we delete it.
1092               (if (zerop (buffer-size))
1093                   (delete-file file)
1094                 ;; There are scores, so we write the file. 
1095                 (when (file-writable-p file)
1096                   (write-region (point-min) (point-max) file nil 'silent)
1097                   (and gnus-score-after-write-file-function
1098                        (funcall gnus-score-after-write-file-function file)))))
1099             (and gnus-score-uncacheable-files
1100                  (string-match gnus-score-uncacheable-files file)
1101                  (gnus-score-remove-from-cache file)))))
1102       (kill-buffer (current-buffer)))))
1103   
1104 (defun gnus-score-headers (score-files &optional trace)
1105   ;; Score `gnus-newsgroup-headers'.
1106   (let (scores news)
1107     ;; PLM: probably this is not the best place to clear orphan-score
1108     (setq gnus-orphan-score nil)
1109     (setq gnus-scores-articles nil)
1110     (setq gnus-scores-exclude-files nil)
1111     ;; Load the score files.
1112     (while score-files
1113       (if (stringp (car score-files))
1114           ;; It is a string, which means that it's a score file name,
1115           ;; so we load the score file and add the score alist to
1116           ;; the list of alists.
1117           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1118         ;; It is an alist, so we just add it to the list directly.
1119         (setq scores (nconc (car score-files) scores)))
1120       (setq score-files (cdr score-files)))
1121     ;; Prune the score files that are to be excluded, if any.
1122     (when gnus-scores-exclude-files
1123       (let ((s scores)
1124             c)
1125         (while s
1126           (and (setq c (rassq (car s) gnus-score-cache))
1127                (member (car c) gnus-scores-exclude-files)
1128                (setq scores (delq (car s) scores)))
1129           (setq s (cdr s)))))
1130     (setq news scores)
1131     ;; Do the scoring.
1132     (while news
1133       (setq scores news
1134             news nil)
1135       (when (and gnus-summary-default-score
1136                  scores)
1137         (let* ((entries gnus-header-index)
1138                (now (gnus-day-number (current-time-string)))
1139                (expire (and gnus-score-expiry-days
1140                             (- now gnus-score-expiry-days)))
1141                (headers gnus-newsgroup-headers)
1142                (current-score-file gnus-current-score-file)
1143                entry header new)
1144           (gnus-message 5 "Scoring...")
1145           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1146           (while (setq header (pop headers))
1147             ;; WARNING: The assq makes the function O(N*S) while it could
1148             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1149             ;; and S is (length gnus-newsgroup-scored).
1150             (or (assq (mail-header-number header) gnus-newsgroup-scored)
1151                 (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1152                       (cons (cons header (or gnus-summary-default-score 0))
1153                             gnus-scores-articles))))
1154
1155           (save-excursion
1156             (set-buffer (get-buffer-create "*Headers*"))
1157             (buffer-disable-undo (current-buffer))
1158
1159             ;; Set the global variant of this variable.
1160             (setq gnus-current-score-file current-score-file)
1161             ;; score orphans
1162             (when gnus-orphan-score 
1163               (setq gnus-score-index 
1164                     (nth 1 (assoc "references" gnus-header-index)))
1165               (gnus-score-orphans gnus-orphan-score))
1166             ;; Run each header through the score process.
1167             (while entries
1168               (setq entry (pop entries)
1169                     header (nth 0 entry)
1170                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1171               (when (< 0 (apply 'max (mapcar
1172                                       (lambda (score)
1173                                         (length (gnus-score-get header score)))
1174                                       scores)))
1175                 ;; Call the scoring function for this type of "header".
1176                 (when (setq new (funcall (nth 2 entry) scores header
1177                                          now expire trace))
1178                   (push new news))))
1179             ;; Remove the buffer.
1180             (kill-buffer (current-buffer)))
1181
1182           ;; Add articles to `gnus-newsgroup-scored'.
1183           (while gnus-scores-articles
1184             (or (= gnus-summary-default-score (cdar gnus-scores-articles))
1185                 (setq gnus-newsgroup-scored
1186                       (cons (cons (mail-header-number 
1187                                    (caar gnus-scores-articles))
1188                                   (cdar gnus-scores-articles))
1189                             gnus-newsgroup-scored)))
1190             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1191
1192           (gnus-message 5 "Scoring...done"))))))
1193
1194
1195 (defun gnus-get-new-thread-ids (articles)
1196   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
1197         (refind gnus-score-index)
1198         id-list art this tref)
1199     (while articles
1200       (setq art (car articles)
1201             this (aref (car art) index)
1202             tref (aref (car art) refind)
1203             articles (cdr articles))
1204       (if (string-equal tref "")        ;no references line
1205           (setq id-list (cons this id-list))))
1206     id-list))
1207
1208 ;; Orphan functions written by plm@atcmp.nl (Peter Mutsaers).
1209 (defun gnus-score-orphans (score)
1210   (let ((new-thread-ids (gnus-get-new-thread-ids gnus-scores-articles))
1211         alike articles art arts this last this-id)
1212     
1213     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1214           articles gnus-scores-articles)
1215
1216     ;;more or less the same as in gnus-score-string
1217     (erase-buffer)
1218     (while articles
1219       (setq art (car articles)
1220             this (aref (car art) gnus-score-index)
1221             articles (cdr articles))
1222       ;;completely skip if this is empty (not a child, so not an orphan)
1223       (if (not (string= this ""))
1224           (if (equal last this)
1225               ;; O(N*H) cons-cells used here, where H is the number of
1226               ;; headers.
1227               (setq alike (cons art alike))
1228             (if last
1229                 (progn
1230                   ;; Insert the line, with a text property on the
1231                   ;; terminating newline referring to the articles with
1232                   ;; this line.
1233                   (insert last ?\n)
1234                   (put-text-property (1- (point)) (point) 'articles alike)))
1235             (setq alike (list art)
1236                   last this))))
1237     (and last                           ; Bwadr, duplicate code.
1238          (progn
1239            (insert last ?\n)                    
1240            (put-text-property (1- (point)) (point) 'articles alike)))
1241
1242     ;; PLM: now delete those lines that contain an entry from new-thread-ids
1243     (while new-thread-ids
1244       (setq this-id (car new-thread-ids)
1245             new-thread-ids (cdr new-thread-ids))
1246       (goto-char (point-min))
1247       (while (search-forward this-id nil t)
1248         ;; found a match. remove this line
1249         (beginning-of-line)
1250         (kill-line 1)))
1251
1252     ;; now for each line: update its articles with score by moving to
1253     ;; every end-of-line in the buffer and read the articles property
1254     (goto-char (point-min))
1255     (while (eq 0 (progn
1256                    (end-of-line)
1257                    (setq arts (get-text-property (point) 'articles))
1258                    (while arts
1259                      (setq art (car arts)
1260                            arts (cdr arts))
1261                      (setcdr art (+ score (cdr art))))
1262                    (forward-line))))))
1263              
1264
1265 (defun gnus-score-integer (scores header now expire &optional trace)
1266   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1267         entries alist)
1268
1269     ;; Find matches.
1270     (while scores
1271       (setq alist (car scores)
1272             scores (cdr scores)
1273             entries (assoc header alist))
1274       (while (cdr entries)              ;First entry is the header index.
1275         (let* ((rest (cdr entries))             
1276                (kill (car rest))
1277                (match (nth 0 kill))
1278                (type (or (nth 3 kill) '>))
1279                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1280                (date (nth 2 kill))
1281                (found nil)
1282                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1283                                    (eq type '>=) (eq type '=))
1284                                type
1285                              (error "Illegal match type: %s" type)))
1286                (articles gnus-scores-articles))
1287           ;; Instead of doing all the clever stuff that
1288           ;; `gnus-score-string' does to minimize searches and stuff,
1289           ;; I will assume that people generally will put so few
1290           ;; matches on numbers that any cleverness will take more
1291           ;; time than one would gain.
1292           (while articles
1293             (and (funcall match-func 
1294                           (or (aref (caar articles) gnus-score-index) 0)
1295                           match)
1296                  (progn
1297                    (and trace (setq gnus-score-trace 
1298                                     (cons
1299                                      (cons
1300                                       (car-safe (rassq alist gnus-score-cache))
1301                                       kill)
1302                                      gnus-score-trace)))
1303                    (setq found t)
1304                    (setcdr (car articles) (+ score (cdar articles)))))
1305             (setq articles (cdr articles)))
1306           ;; Update expire date
1307           (cond ((null date))           ;Permanent entry.
1308                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1309                  (gnus-score-set 'touched '(t) alist)
1310                  (setcar (nthcdr 2 kill) now))
1311                 ((and expire (< date expire)) ;Old entry, remove.
1312                  (gnus-score-set 'touched '(t) alist)
1313                  (setcdr entries (cdr rest))
1314                  (setq rest entries)))
1315           (setq entries rest)))))
1316   nil)
1317
1318 (defun gnus-score-date (scores header now expire &optional trace)
1319   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1320         entries alist)
1321
1322     ;; Find matches.
1323     (while scores
1324       (setq alist (car scores)
1325             scores (cdr scores)
1326             entries (assoc header alist))
1327       (while (cdr entries)              ;First entry is the header index.
1328         (let* ((rest (cdr entries))             
1329                (kill (car rest))
1330                (match (timezone-make-date-sortable (nth 0 kill)))
1331                (type (or (nth 3 kill) 'before))
1332                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1333                (date (nth 2 kill))
1334                (found nil)
1335                (match-func 
1336                 (cond ((eq type 'after) 'string<)
1337                       ((eq type 'before) 'gnus-string>)
1338                       ((eq type 'at) 'string=)
1339                       (t (error "Illegal match type: %s" type))))
1340                (articles gnus-scores-articles)
1341                l)
1342           ;; Instead of doing all the clever stuff that
1343           ;; `gnus-score-string' does to minimize searches and stuff,
1344           ;; I will assume that people generally will put so few
1345           ;; matches on numbers that any cleverness will take more
1346           ;; time than one would gain.
1347           (while articles
1348             (and
1349              (setq l (aref (caar articles) gnus-score-index))
1350              (funcall match-func match (timezone-make-date-sortable l))
1351              (progn
1352                (and trace (setq gnus-score-trace 
1353                                 (cons
1354                                  (cons
1355                                   (car-safe (rassq alist gnus-score-cache))
1356                                   kill)
1357                                  gnus-score-trace)))
1358                (setq found t)
1359                (setcdr (car articles) (+ score (cdar articles)))))
1360             (setq articles (cdr articles)))
1361           ;; Update expire date
1362           (cond ((null date))           ;Permanent entry.
1363                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1364                  (gnus-score-set 'touched '(t) alist)
1365                  (setcar (nthcdr 2 kill) now))
1366                 ((and expire (< date expire))   ;Old entry, remove.
1367                  (gnus-score-set 'touched '(t) alist)
1368                  (setcdr entries (cdr rest))
1369                  (setq rest entries)))
1370           (setq entries rest)))))
1371   nil)
1372
1373 (defun gnus-score-body (scores header now expire &optional trace)
1374   (save-excursion
1375     (set-buffer nntp-server-buffer)
1376     (setq gnus-scores-articles
1377           (sort gnus-scores-articles
1378                 (lambda (a1 a2)
1379                   (< (mail-header-number (car a1))
1380                      (mail-header-number (car a2))))))
1381     (save-restriction
1382       (let* ((buffer-read-only nil)
1383              (articles gnus-scores-articles)
1384              (all-scores scores)
1385              (request-func (cond ((string= "head" header)
1386                                   'gnus-request-head)
1387                                  ((string= "body" header)
1388                                   'gnus-request-body)
1389                                  (t 'gnus-request-article)))
1390              entries alist ofunc article last)
1391         (when articles
1392           (while (cdr articles)
1393             (setq articles (cdr articles)))
1394           (setq last (mail-header-number (caar articles)))
1395           (setq articles gnus-scores-articles)
1396           ;; Not all backends support partial fetching.  In that case,
1397           ;; we just fetch the entire article.
1398           (or (gnus-check-backend-function 
1399                (and (string-match "^gnus-" (symbol-name request-func))
1400                     (intern (substring (symbol-name request-func)
1401                                        (match-end 0))))
1402                gnus-newsgroup-name)
1403               (progn
1404                 (setq ofunc request-func)
1405                 (setq request-func 'gnus-request-article)))
1406           (while articles
1407             (setq article (mail-header-number (caar articles)))
1408             (gnus-message 7 "Scoring on article %s of %s..." article last)
1409             (when (funcall request-func article gnus-newsgroup-name)
1410               (widen)
1411               (goto-char (point-min))
1412               ;; If just parts of the article is to be searched, but the
1413               ;; backend didn't support partial fetching, we just narrow
1414               ;; to the relevant parts.
1415               (if ofunc
1416                   (if (eq ofunc 'gnus-request-head)
1417                       (narrow-to-region
1418                        (point)
1419                        (or (search-forward "\n\n" nil t) (point-max)))
1420                     (narrow-to-region
1421                      (or (search-forward "\n\n" nil t) (point))
1422                      (point-max))))
1423               (setq scores all-scores)
1424               ;; Find matches.
1425               (while scores
1426                 (setq alist (car scores)
1427                       scores (cdr scores)
1428                       entries (assoc header alist))
1429                 (while (cdr entries)    ;First entry is the header index.
1430                   (let* ((rest (cdr entries))           
1431                          (kill (car rest))
1432                          (match (nth 0 kill))
1433                          (type (or (nth 3 kill) 's))
1434                          (score (or (nth 1 kill) 
1435                                     gnus-score-interactive-default-score))
1436                          (date (nth 2 kill))
1437                          (found nil)
1438                          (case-fold-search 
1439                           (not (or (eq type 'R) (eq type 'S)
1440                                    (eq type 'Regexp) (eq type 'String))))
1441                          (search-func 
1442                           (cond ((or (eq type 'r) (eq type 'R)
1443                                      (eq type 'regexp) (eq type 'Regexp))
1444                                  're-search-forward)
1445                                 ((or (eq type 's) (eq type 'S)
1446                                      (eq type 'string) (eq type 'String))
1447                                  'search-forward)
1448                                 (t
1449                                  (error "Illegal match type: %s" type)))))
1450                     (goto-char (point-min))
1451                     (if (funcall search-func match nil t)
1452                         ;; Found a match, update scores.
1453                         (progn
1454                           (setcdr (car articles) (+ score (cdar articles)))
1455                           (setq found t)
1456                           (and trace (setq gnus-score-trace 
1457                                            (cons
1458                                             (cons
1459                                              (car-safe
1460                                               (rassq alist gnus-score-cache))
1461                                              kill)
1462                                             gnus-score-trace)))))
1463                     ;; Update expire date
1464                     (cond
1465                      ((null date))      ;Permanent entry.
1466                      ((and found gnus-update-score-entry-dates) ;Match, update date.
1467                       (gnus-score-set 'touched '(t) alist)
1468                       (setcar (nthcdr 2 kill) now))
1469                      ((and expire (< date expire)) ;Old entry, remove.
1470                       (gnus-score-set 'touched '(t) alist)
1471                       (setcdr entries (cdr rest))
1472                       (setq rest entries)))
1473                     (setq entries rest)))))
1474             (setq articles (cdr articles)))))))
1475   nil)
1476
1477 (defun gnus-score-followup (scores header now expire &optional trace thread)
1478   ;; Insert the unique article headers in the buffer.
1479   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1480         (current-score-file gnus-current-score-file)
1481         (all-scores scores)
1482         ;; gnus-score-index is used as a free variable.
1483         alike last this art entries alist articles
1484         new news)
1485
1486     ;; Change score file to the adaptive score file.  All entries that
1487     ;; this function makes will be put into this file.
1488     (save-excursion
1489       (set-buffer gnus-summary-buffer)
1490       (gnus-score-load-file
1491        (or gnus-newsgroup-adaptive-score-file
1492            (gnus-score-file-name 
1493             gnus-newsgroup-name gnus-adaptive-file-suffix))))
1494
1495     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1496           articles gnus-scores-articles)
1497
1498     (erase-buffer)
1499     (while articles
1500       (setq art (car articles)
1501             this (aref (car art) gnus-score-index)
1502             articles (cdr articles))
1503       (if (equal last this)
1504           (setq alike (cons art alike))
1505         (if last
1506             (progn
1507               (insert last ?\n)
1508               (put-text-property (1- (point)) (point) 'articles alike)))
1509         (setq alike (list art)
1510               last this)))
1511     (and last                           ; Bwadr, duplicate code.
1512          (progn
1513            (insert last ?\n)                    
1514            (put-text-property (1- (point)) (point) 'articles alike)))
1515   
1516     ;; Find matches.
1517     (while scores
1518       (setq alist (car scores)
1519             scores (cdr scores)
1520             entries (assoc header alist))
1521       (while (cdr entries)              ;First entry is the header index.
1522         (let* ((rest (cdr entries))             
1523                (kill (car rest))
1524                (match (nth 0 kill))
1525                (type (or (nth 3 kill) 's))
1526                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1527                (date (nth 2 kill))
1528                (found nil)
1529                (mt (aref (symbol-name type) 0))
1530                (case-fold-search 
1531                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1532                (dmt (downcase mt))
1533                (search-func 
1534                 (cond ((= dmt ?r) 're-search-forward)
1535                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1536                       (t (error "Illegal match type: %s" type))))
1537                arts art)
1538           (goto-char (point-min))
1539           (if (= dmt ?e)
1540               (while (funcall search-func match nil t)
1541                 (and (= (progn (beginning-of-line) (point))
1542                         (match-beginning 0))
1543                      (= (progn (end-of-line) (point))
1544                         (match-end 0))
1545                      (progn
1546                        (setq found (setq arts (get-text-property 
1547                                                (point) 'articles)))
1548                        ;; Found a match, update scores.
1549                        (while arts
1550                          (setq art (car arts)
1551                                arts (cdr arts))
1552                          (gnus-score-add-followups 
1553                           (car art) score all-scores thread))))
1554                 (end-of-line))
1555             (while (funcall search-func match nil t)
1556               (end-of-line)
1557               (setq found (setq arts (get-text-property (point) 'articles)))
1558               ;; Found a match, update scores.
1559               (while (setq art (pop arts))
1560                 (when (setq new (gnus-score-add-followups
1561                                  (car art) score all-scores thread))
1562                   (push new news)))))
1563           ;; Update expire date
1564           (cond ((null date))           ;Permanent entry.
1565                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1566                  (gnus-score-set 'touched '(t) alist)
1567                  (setcar (nthcdr 2 kill) now))
1568                 ((and expire (< date expire))   ;Old entry, remove.
1569                  (gnus-score-set 'touched '(t) alist)
1570                  (setcdr entries (cdr rest))
1571                  (setq rest entries)))
1572           (setq entries rest))))
1573     ;; We change the score file back to the previous one.
1574     (save-excursion
1575       (set-buffer gnus-summary-buffer)
1576       (gnus-score-load-file current-score-file))
1577     (list (cons "references" news))))
1578
1579 (defun gnus-score-add-followups (header score scores &optional thread)
1580   "Add a score entry to the adapt file."
1581   (save-excursion
1582     (set-buffer gnus-summary-buffer)
1583     (let* ((id (mail-header-id header))
1584            (scores (car scores))
1585            entry dont)
1586       ;; Don't enter a score if there already is one.
1587       (while (setq entry (pop scores))
1588         (and (equal "references" (car entry))
1589              (or (null (nth 3 (cadr entry)))
1590                  (eq 's (nth 3 (cadr entry))))
1591              (assoc id entry)
1592              (setq dont t)))
1593       (unless dont
1594         (gnus-summary-score-entry 
1595          (if thread "thread" "references")
1596          id 's score (current-time-string) nil t)))))
1597
1598 (defun gnus-score-string (score-list header now expire &optional trace)
1599   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1600   ;; Update matching entries to NOW and remove unmatched entries older
1601   ;; than EXPIRE.
1602   
1603   ;; Insert the unique article headers in the buffer.
1604   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1605         ;; gnus-score-index is used as a free variable.
1606         alike last this art entries alist articles scores fuzzy)
1607
1608     ;; Sorting the articles costs os O(N*log N) but will allow us to
1609     ;; only match with each unique header.  Thus the actual matching
1610     ;; will be O(M*U) where M is the number of strings to match with,
1611     ;; and U is the number of unique headers.  It is assumed (but
1612     ;; untested) this will be a net win because of the large constant
1613     ;; factor involved with string matching.
1614     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1615           articles gnus-scores-articles)
1616
1617     (erase-buffer)
1618     (while articles
1619       (setq art (car articles)
1620             this (aref (car art) gnus-score-index)
1621             articles (cdr articles))
1622       (if (equal last this)
1623           ;; O(N*H) cons-cells used here, where H is the number of
1624           ;; headers.
1625           (setq alike (cons art alike))
1626         (if last
1627             (progn
1628               ;; Insert the line, with a text property on the
1629               ;; terminating newline referring to the articles with
1630               ;; this line.
1631               (insert last ?\n)
1632               (put-text-property (1- (point)) (point) 'articles alike)))
1633         (setq alike (list art)
1634               last this)))
1635     (and last                           ; Bwadr, duplicate code.
1636          (progn
1637            (insert last ?\n)                    
1638            (put-text-property (1- (point)) (point) 'articles alike)))
1639
1640     ;; Find ordinary matches.
1641     (setq scores score-list) 
1642     (while scores
1643       (setq alist (car scores)
1644             scores (cdr scores)
1645             entries (assoc header alist))
1646       (while (cdr entries)              ;First entry is the header index.
1647         (let* ((rest (cdr entries))             
1648                (kill (car rest))
1649                (match (nth 0 kill))
1650                (type (or (nth 3 kill) 's))
1651                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1652                (date (nth 2 kill))
1653                (found nil)
1654                (mt (aref (symbol-name type) 0))
1655                (case-fold-search 
1656                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1657                (dmt (downcase mt))
1658                (search-func 
1659                 (cond ((= dmt ?r) 're-search-forward)
1660                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1661                       (t (error "Illegal match type: %s" type))))
1662                arts art)
1663           (if (= dmt ?f)
1664               (setq fuzzy t)
1665             ;; Do non-fuzzy matching.
1666             (goto-char (point-min))
1667             (if (= dmt ?e)
1668                 ;; Do exact matching.
1669                 (while (and (not (eobp)) 
1670                             (funcall search-func match nil t))
1671                   (and (= (progn (beginning-of-line) (point))
1672                           (match-beginning 0))
1673                        (= (progn (end-of-line) (point))
1674                           (match-end 0))
1675                        (progn
1676                          (setq found (setq arts (get-text-property 
1677                                                  (point) 'articles)))
1678                          ;; Found a match, update scores.
1679                          (if trace
1680                              (while arts
1681                                (setq art (car arts)
1682                                      arts (cdr arts))
1683                                (setcdr art (+ score (cdr art)))
1684                                (setq gnus-score-trace
1685                                      (cons
1686                                       (cons
1687                                        (car-safe
1688                                         (rassq alist gnus-score-cache))
1689                                        kill)
1690                                       gnus-score-trace)))
1691                            (while arts
1692                              (setq art (car arts)
1693                                    arts (cdr arts))
1694                              (setcdr art (+ score (cdr art)))))))
1695                   (forward-line 1))
1696               ;; Do regexp and substring matching.
1697               (and (string= match "") (setq match "\n"))
1698               (while (and (not (eobp))
1699                           (funcall search-func match nil t))
1700                 (goto-char (match-beginning 0))
1701                 (end-of-line)
1702                 (setq found (setq arts (get-text-property (point) 'articles)))
1703                 ;; Found a match, update scores.
1704                 (if trace
1705                     (while arts
1706                       (setq art (pop arts))
1707                       (setcdr art (+ score (cdr art)))
1708                       (push (cons
1709                               (car-safe (rassq alist gnus-score-cache))
1710                               kill)
1711                             gnus-score-trace))
1712                   (while arts
1713                     (setq art (pop arts))
1714                     (setcdr art (+ score (cdr art)))))
1715                 (forward-line 1)))
1716             ;; Update expire date
1717             (cond 
1718              ((null date))              ;Permanent entry.
1719              ((and found gnus-update-score-entry-dates) ;Match, update date.
1720               (gnus-score-set 'touched '(t) alist)
1721               (setcar (nthcdr 2 kill) now))
1722              ((and expire (< date expire)) ;Old entry, remove.
1723               (gnus-score-set 'touched '(t) alist)
1724               (setcdr entries (cdr rest))
1725               (setq rest entries))))
1726           (setq entries rest))))
1727
1728     ;; Find fuzzy matches.
1729     (when fuzzy
1730       (setq scores score-list)
1731       (gnus-simplify-buffer-fuzzy)
1732       (while scores
1733         (setq alist (car scores)
1734               scores (cdr scores)
1735               entries (assoc header alist))
1736         (while (cdr entries)            ;First entry is the header index.
1737           (let* ((rest (cdr entries))           
1738                  (kill (car rest))
1739                  (match (nth 0 kill))
1740                  (type (or (nth 3 kill) 's))
1741                  (score (or (nth 1 kill) gnus-score-interactive-default-score))
1742                  (date (nth 2 kill))
1743                  (found nil)
1744                  (mt (aref (symbol-name type) 0))
1745                  (case-fold-search (not (= mt ?F)))
1746                  (dmt (downcase mt))
1747                  arts art)
1748             (when (= dmt ?f)
1749               (goto-char (point-min))
1750               (while (and (not (eobp)) 
1751                           (search-forward match nil t))
1752                 (when (and (= (progn (beginning-of-line) (point))
1753                               (match-beginning 0))
1754                            (= (progn (end-of-line) (point))
1755                               (match-end 0)))
1756                   (setq found (setq arts (get-text-property 
1757                                           (point) 'articles)))
1758                   ;; Found a match, update scores.
1759                   (if trace
1760                       (while arts
1761                         (setq art (pop arts))
1762                         (setcdr art (+ score (cdr art)))
1763                         (push (cons
1764                                (car-safe (rassq alist gnus-score-cache))
1765                                kill)
1766                               gnus-score-trace))
1767                     (while arts
1768                       (setq art (pop arts))
1769                       (setcdr art (+ score (cdr art))))))
1770                 (forward-line 1))
1771               ;; Update expire date
1772               (unless trace
1773                 (cond 
1774                  ((null date))          ;Permanent entry.
1775                  ((and found gnus-update-score-entry-dates) ;Match, update date.
1776                   (gnus-score-set 'touched '(t) alist)
1777                   (setcar (nthcdr 2 kill) now))
1778                  ((and expire (< date expire)) ;Old entry, remove.
1779                   (gnus-score-set 'touched '(t) alist)
1780                   (setcdr entries (cdr rest))
1781                   (setq rest entries)))))
1782             (setq entries rest))))))
1783   nil)
1784
1785 (defun gnus-score-string< (a1 a2)
1786   ;; Compare headers in articles A2 and A2.
1787   ;; The header index used is the free variable `gnus-score-index'.
1788   (string-lessp (aref (car a1) gnus-score-index)
1789                 (aref (car a2) gnus-score-index)))
1790
1791 (defun gnus-score-build-cons (article)
1792   ;; Build a `gnus-newsgroup-scored' type cons from ARTICLE.
1793   (cons (mail-header-number (car article)) (cdr article)))
1794
1795 (defun gnus-current-score-file-nondirectory (&optional score-file)
1796   (let ((score-file (or score-file gnus-current-score-file)))
1797     (if score-file 
1798         (gnus-short-group-name (file-name-nondirectory score-file))
1799       "none")))
1800
1801 (defun gnus-score-adaptive ()
1802   (save-excursion
1803     (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
1804            (alist malist)
1805            (date (current-time-string)) 
1806            (data gnus-newsgroup-data)
1807            elem headers match)
1808       ;; First we transform the adaptive rule alist into something
1809       ;; that's faster to process.
1810       (while malist
1811         (setq elem (car malist))
1812         (if (symbolp (car elem))
1813             (setcar elem (symbol-value (car elem))))
1814         (setq elem (cdr elem))
1815         (while elem
1816           (setcdr (car elem) 
1817                   (cons (if (eq (caar elem) 'followup)
1818                             "references"
1819                           (symbol-name (caar elem)))
1820                         (cdar elem)))
1821           (setcar (car elem) 
1822                   `(lambda (h)
1823                      (,(intern 
1824                         (concat "mail-header-" 
1825                                 (if (eq (caar elem) 'followup)
1826                                     "message-id"
1827                                   (downcase (symbol-name (caar elem))))))
1828                       h)))
1829           (setq elem (cdr elem)))
1830         (setq malist (cdr malist)))
1831       ;; We change the score file to the adaptive score file.
1832       (save-excursion
1833         (set-buffer gnus-summary-buffer)
1834         (gnus-score-load-file 
1835          (or gnus-newsgroup-adaptive-score-file
1836              (gnus-score-file-name 
1837               gnus-newsgroup-name gnus-adaptive-file-suffix))))
1838       ;; The we score away.
1839       (while data
1840         (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
1841         (if (or (not elem)
1842                 (gnus-data-pseudo-p (car data)))
1843             ()
1844           (when (setq headers (gnus-data-header (car data)))
1845             (while elem 
1846               (setq match (funcall (caar elem) headers))
1847               (gnus-summary-score-entry 
1848                (nth 1 (car elem)) match
1849                (cond
1850                 ((numberp match)
1851                  '=)
1852                 ((equal (nth 1 (car elem)) "date")
1853                  'a)
1854                 (t
1855                  ;; Whether we use substring or exact matches are controlled
1856                  ;; here.  
1857                  (if (or (not gnus-score-exact-adapt-limit)
1858                          (< (length match) gnus-score-exact-adapt-limit))
1859                      'e 
1860                    (if (equal (nth 1 (car elem)) "subject")
1861                        'f 's))))
1862                (nth 2 (car elem)) date nil t)
1863               (setq elem (cdr elem)))))
1864         (setq data (cdr data))))))
1865
1866 (defun gnus-score-edit-done ()
1867   (let ((bufnam (buffer-file-name (current-buffer)))
1868         (winconf gnus-prev-winconf))
1869     (and winconf (set-window-configuration winconf))
1870     (gnus-score-remove-from-cache bufnam)
1871     (gnus-score-load-file bufnam)))
1872
1873 (defun gnus-score-find-trace ()
1874   "Find all score rules that applies to the current article."
1875   (interactive)
1876   (let ((gnus-newsgroup-headers
1877          (list (gnus-summary-article-header)))
1878         (gnus-newsgroup-scored nil)
1879         (buf (current-buffer))
1880         trace)
1881     (when (get-buffer "*Gnus Scores*")
1882       (save-excursion
1883         (set-buffer "*Gnus Scores*")
1884         (erase-buffer)))
1885     (setq gnus-score-trace nil)
1886     (gnus-possibly-score-headers 'trace)
1887     (if (not (setq trace gnus-score-trace))
1888         (gnus-error 1 "No score rules apply to the current article.")
1889       (pop-to-buffer "*Gnus Scores*")
1890       (gnus-add-current-to-buffer-list)
1891       (erase-buffer)
1892       (while trace
1893         (insert (format "%S  ->  %s\n" (cdar trace)
1894                         (file-name-nondirectory (caar trace))))
1895         (setq trace (cdr trace)))
1896       (goto-char (point-min))
1897       (pop-to-buffer buf))))
1898
1899 (defun gnus-summary-rescore ()
1900   "Redo the entire scoring process in the current summary."
1901   (interactive)
1902   (gnus-score-save)
1903   (setq gnus-score-cache nil)
1904   (setq gnus-newsgroup-scored nil)
1905   (gnus-possibly-score-headers)
1906   (gnus-score-update-all-lines))
1907   
1908 (defun gnus-score-flush-cache ()
1909   "Flush the cache of score files."
1910   (interactive)
1911   (gnus-score-save)
1912   (setq gnus-score-cache nil
1913         gnus-score-alist nil
1914         gnus-short-name-score-file-cache nil)
1915   (gnus-message 6 "The score cache is now flushed"))
1916
1917 (gnus-add-shutdown 'gnus-score-close 'gnus)
1918
1919 (defvar gnus-score-file-alist-cache nil)
1920
1921 (defun gnus-score-close ()
1922   "Clear all internal score variables."
1923   (setq gnus-score-cache nil
1924         gnus-internal-global-score-files nil
1925         gnus-score-file-list nil
1926         gnus-score-file-alist-cache nil))
1927
1928 ;; Summary score marking commands.
1929
1930 (defun gnus-summary-raise-same-subject-and-select (score)
1931   "Raise articles which has the same subject with SCORE and select the next."
1932   (interactive "p")
1933   (let ((subject (gnus-summary-article-subject)))
1934     (gnus-summary-raise-score score)
1935     (while (gnus-summary-find-subject subject)
1936       (gnus-summary-raise-score score))
1937     (gnus-summary-next-article t)))
1938
1939 (defun gnus-summary-raise-same-subject (score)
1940   "Raise articles which has the same subject with SCORE."
1941   (interactive "p")
1942   (let ((subject (gnus-summary-article-subject)))
1943     (gnus-summary-raise-score score)
1944     (while (gnus-summary-find-subject subject)
1945       (gnus-summary-raise-score score))
1946     (gnus-summary-next-subject 1 t)))
1947
1948 (defun gnus-score-default (level)
1949   (if level (prefix-numeric-value level) 
1950     gnus-score-interactive-default-score))
1951
1952 (defun gnus-summary-raise-thread (&optional score)
1953   "Raise the score of the articles in the current thread with SCORE."
1954   (interactive "P")
1955   (setq score (gnus-score-default score))
1956   (let (e)
1957     (save-excursion
1958       (let ((articles (gnus-summary-articles-in-thread)))
1959         (while articles
1960           (gnus-summary-goto-subject (car articles))
1961           (gnus-summary-raise-score score)
1962           (setq articles (cdr articles))))
1963       (setq e (point)))
1964     (let ((gnus-summary-check-current t))
1965       (or (zerop (gnus-summary-next-subject 1 t))
1966           (goto-char e))))
1967   (gnus-summary-recenter)
1968   (gnus-summary-position-point)
1969   (gnus-set-mode-line 'summary))
1970
1971 (defun gnus-summary-lower-same-subject-and-select (score)
1972   "Raise articles which has the same subject with SCORE and select the next."
1973   (interactive "p")
1974   (gnus-summary-raise-same-subject-and-select (- score)))
1975
1976 (defun gnus-summary-lower-same-subject (score)
1977   "Raise articles which has the same subject with SCORE."
1978   (interactive "p")
1979   (gnus-summary-raise-same-subject (- score)))
1980
1981 (defun gnus-summary-lower-thread (&optional score)
1982   "Lower score of articles in the current thread with SCORE."
1983   (interactive "P")
1984   (gnus-summary-raise-thread (- (1- (gnus-score-default score)))))
1985
1986 ;;; Finding score files. 
1987
1988 (defun gnus-score-score-files (group)
1989   "Return a list of all possible score files."
1990   ;; Search and set any global score files.
1991   (and gnus-global-score-files 
1992        (or gnus-internal-global-score-files
1993            (gnus-score-search-global-directories gnus-global-score-files)))
1994   ;; Fix the kill-file dir variable.
1995   (setq gnus-kill-files-directory 
1996         (file-name-as-directory gnus-kill-files-directory))
1997   ;; If we can't read it, there are no score files.
1998   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
1999       (setq gnus-score-file-list nil)
2000     (if (not (gnus-use-long-file-name 'not-score))
2001         ;; We do not use long file names, so we have to do some
2002         ;; directory traversing.  
2003         (setq gnus-score-file-list 
2004               (cons nil 
2005                     (or gnus-short-name-score-file-cache
2006                         (prog2
2007                             (gnus-message 6 "Finding all score files...")
2008                             (setq gnus-short-name-score-file-cache
2009                                   (gnus-score-score-files-1
2010                                    gnus-kill-files-directory))
2011                           (gnus-message 6 "Finding all score files...done")))))
2012       ;; We want long file names.
2013       (when (or (not gnus-score-file-list)
2014                 (not (car gnus-score-file-list))
2015                 (gnus-file-newer-than gnus-kill-files-directory
2016                                       (car gnus-score-file-list)))
2017         (setq gnus-score-file-list 
2018               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2019                     (nreverse 
2020                      (directory-files 
2021                       gnus-kill-files-directory t 
2022                       (gnus-score-file-regexp)))))))
2023     (cdr gnus-score-file-list)))
2024
2025 (defun gnus-score-score-files-1 (dir)
2026   "Return all possible score files under DIR."
2027   (let ((files (directory-files (expand-file-name dir) t nil t))
2028         (regexp (gnus-score-file-regexp))
2029         out file)
2030     (while (setq file (pop files))
2031       (cond 
2032        ;; Ignore "." and "..".
2033        ((member (file-name-nondirectory file) '("." ".."))
2034         nil)
2035        ;; Recurse down directories.
2036        ((file-directory-p file)
2037         (setq out (nconc (gnus-score-score-files-1 file) out)))
2038        ;; Add files to the list of score files.
2039        ((string-match regexp file)
2040         (push file out))))
2041     (or out
2042         ;; Return a dummy value.
2043         (list "~/News/this.file.does.not.exist.SCORE"))))
2044        
2045 (defun gnus-score-file-regexp ()
2046   "Return a regexp that match all score files."
2047   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2048           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2049         
2050 (defun gnus-score-find-bnews (group)
2051   "Return a list of score files for GROUP.
2052 The score files are those files in the ~/News/ directory which matches
2053 GROUP using BNews sys file syntax."
2054   (let* ((sfiles (append (gnus-score-score-files group)
2055                          gnus-internal-global-score-files))
2056          (kill-dir (file-name-as-directory 
2057                     (expand-file-name gnus-kill-files-directory)))
2058          (klen (length kill-dir))
2059          (score-regexp (gnus-score-file-regexp))
2060          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2061          ofiles not-match regexp)
2062     (save-excursion
2063       (set-buffer (get-buffer-create "*gnus score files*"))
2064       (buffer-disable-undo (current-buffer))
2065       ;; Go through all score file names and create regexp with them
2066       ;; as the source.  
2067       (while sfiles
2068         (erase-buffer)
2069         (insert (car sfiles))
2070         (goto-char (point-min))
2071         ;; First remove the suffix itself.
2072         (when (re-search-forward (concat "." score-regexp) nil t)
2073           (replace-match "" t t) 
2074           (goto-char (point-min))
2075           (if (looking-at (regexp-quote kill-dir))
2076               ;; If the file name was just "SCORE", `klen' is one character
2077               ;; too much.
2078               (delete-char (min (1- (point-max)) klen))
2079             (goto-char (point-max))
2080             (search-backward "/")
2081             (delete-region (1+ (point)) (point-min)))
2082           ;; If short file names were used, we have to translate slashes.
2083           (goto-char (point-min))
2084           (let ((regexp (concat
2085                          "[/:" (if trans (char-to-string trans) "") "]")))
2086             (while (re-search-forward regexp nil t)
2087               (replace-match "." t t)))
2088           ;; Cludge to get rid of "nntp+" problems.
2089           (goto-char (point-min))
2090           (and (looking-at "nn[a-z]+\\+")
2091                (progn
2092                  (search-forward "+")
2093                  (forward-char -1)
2094                  (insert "\\")))
2095           ;; Kludge to deal with "++".
2096           (goto-char (point-min))
2097           (while (search-forward "++" nil t)
2098             (replace-match "\\+\\+" t t))
2099           ;; Translate "all" to ".*".
2100           (goto-char (point-min))
2101           (while (search-forward "all" nil t)
2102             (replace-match ".*" t t))
2103           (goto-char (point-min))
2104           ;; Deal with "not."s.
2105           (if (looking-at "not.")
2106               (progn
2107                 (setq not-match t)
2108                 (setq regexp (buffer-substring 5 (point-max))))
2109             (setq regexp (buffer-substring 1 (point-max)))
2110             (setq not-match nil))
2111           ;; Finally - if this resulting regexp matches the group name,
2112           ;; we add this score file to the list of score files
2113           ;; applicable to this group.
2114           (if (or (and not-match
2115                        (not (string-match regexp group)))
2116                   (and (not not-match)
2117                        (string-match regexp group)))
2118               (setq ofiles (cons (car sfiles) ofiles))))
2119         (setq sfiles (cdr sfiles)))
2120       (kill-buffer (current-buffer))
2121       ;; Slight kludge here - the last score file returned should be
2122       ;; the local score file, whether it exists or not. This is so
2123       ;; that any score commands the user enters will go to the right
2124       ;; file, and not end up in some global score file.
2125       (let ((localscore (gnus-score-file-name group)))
2126         (setq ofiles (cons localscore (delete localscore ofiles))))
2127       (nreverse ofiles))))
2128
2129 (defun gnus-score-find-single (group)
2130   "Return list containing the score file for GROUP."
2131   (list (or gnus-newsgroup-adaptive-score-file
2132             (gnus-score-file-name group gnus-adaptive-file-suffix))
2133         (gnus-score-file-name group)))
2134
2135 (defun gnus-score-find-hierarchical (group)
2136   "Return list of score files for GROUP.
2137 This includes the score file for the group and all its parents."
2138   (let ((all (copy-sequence '(nil)))
2139         (start 0))
2140     (while (string-match "\\." group (1+ start))
2141       (setq start (match-beginning 0))
2142       (setq all (cons (substring group 0 start) all)))
2143     (setq all (cons group all))
2144     (nconc
2145      (mapcar (lambda (newsgroup)
2146                (gnus-score-file-name newsgroup gnus-adaptive-file-suffix))
2147              (setq all (nreverse all)))
2148      (mapcar 'gnus-score-file-name all))))
2149
2150 (defun gnus-score-find-alist (group)
2151   "Return list of score files for GROUP.
2152 The list is determined from the variable gnus-score-file-alist."
2153   (let ((alist gnus-score-file-multiple-match-alist)
2154         score-files)
2155     ;; if this group has been seen before, return the cached entry
2156     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2157         (cdr score-files)               ;ensures caching groups with no matches
2158       ;; handle the multiple match alist
2159       (while alist
2160         (and (string-match (caar alist) group)
2161              (setq score-files
2162                    (nconc score-files (copy-sequence (cdar alist)))))
2163         (setq alist (cdr alist)))
2164       (setq alist gnus-score-file-single-match-alist)
2165       ;; handle the single match alist
2166       (while alist
2167         (and (string-match (caar alist) group)
2168              ;; progn used just in case ("regexp") has no files
2169              ;; and score-files is still nil. -sj
2170              ;; this can be construed as a "stop searching here" feature :>
2171              ;; and used to simplify regexps in the single-alist 
2172              (progn
2173                (setq score-files
2174                      (nconc score-files (copy-sequence (cdar alist))))
2175                (setq alist nil)))
2176         (setq alist (cdr alist)))
2177       ;; cache the score files
2178       (setq gnus-score-file-alist-cache
2179             (cons (cons group score-files) gnus-score-file-alist-cache))
2180       score-files)))
2181
2182 (defun gnus-possibly-score-headers (&optional trace)
2183   (let ((funcs gnus-score-find-score-files-function)
2184         score-files)
2185     ;; Make sure funcs is a list.
2186     (and funcs
2187          (not (listp funcs))
2188          (setq funcs (list funcs)))
2189     ;; Get the initial score files for this group.
2190     (when funcs 
2191       (setq score-files (gnus-score-find-alist gnus-newsgroup-name)))
2192     ;; Go through all the functions for finding score files (or actual
2193     ;; scores) and add them to a list.
2194     (while funcs
2195       (when (gnus-functionp (car funcs))
2196         (setq score-files 
2197               (nconc score-files (funcall (car funcs) gnus-newsgroup-name))))
2198       (setq funcs (cdr funcs)))
2199     ;; Check whether there is a `score-file' group parameter.
2200     (let ((param-file (gnus-group-get-parameter 
2201                        gnus-newsgroup-name 'score-file)))
2202       (when param-file
2203         (push param-file score-files)))
2204     ;; Do the scoring if there are any score files for this group.
2205     (when score-files
2206       (gnus-score-headers score-files trace))))
2207
2208 (defun gnus-score-file-name (newsgroup &optional suffix)
2209   "Return the name of a score file for NEWSGROUP."
2210   (let ((suffix (or suffix gnus-score-file-suffix)))
2211     (nnheader-translate-file-chars
2212      (cond
2213       ((or (null newsgroup)
2214            (string-equal newsgroup ""))
2215        ;; The global score file is placed at top of the directory.
2216        (expand-file-name 
2217         suffix gnus-kill-files-directory))
2218       ((gnus-use-long-file-name 'not-score)
2219        ;; Append ".SCORE" to newsgroup name.
2220        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2221                                  "." suffix)
2222                          gnus-kill-files-directory))
2223       (t
2224        ;; Place "SCORE" under the hierarchical directory.
2225        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2226                                  "/" suffix)
2227                          gnus-kill-files-directory))))))
2228
2229 (defun gnus-score-search-global-directories (files)
2230   "Scan all global score directories for score files."
2231   ;; Set the variable `gnus-internal-global-score-files' to all
2232   ;; available global score files.
2233   (interactive (list gnus-global-score-files))
2234   (let (out)
2235     (while files
2236       (if (string-match "/$" (car files))
2237           (setq out (nconc (directory-files 
2238                             (car files) t
2239                             (concat (gnus-score-file-regexp) "$"))))
2240         (setq out (cons (car files) out)))
2241       (setq files (cdr files)))
2242     (setq gnus-internal-global-score-files out)))
2243
2244 (defun gnus-score-default-fold-toggle ()
2245   "Toggle folding for new score file entries."
2246   (interactive)
2247   (setq gnus-score-default-fold (not gnus-score-default-fold))
2248   (if gnus-score-default-fold
2249       (gnus-message 1 "New score file entries will be case insensitive.")
2250     (gnus-message 1 "New score file entries will be case sensitive.")))
2251
2252 (provide 'gnus-score)
2253
2254 ;;; gnus-score.el ends here