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