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