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