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