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