*** 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)))
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 (concat gnus-adaptive-file-suffix "$") file)
1061                   ;; This is an adaptive score file, so we do not run
1062                   ;; it through `pp'.  These files can get huge, and
1063                   ;; are not meant to be edited by human hands.
1064                   (prin1 score (current-buffer))
1065                 ;; This is a normal score file, so we print it very
1066                 ;; prettily. 
1067                 (pp score (current-buffer))))
1068             (if (not (gnus-make-directory (file-name-directory file)))
1069                 ()
1070               ;; If the score file is empty, we delete it.
1071               (if (zerop (buffer-size))
1072                   (delete-file file)
1073                 ;; There are scores, so we write the file. 
1074                 (when (file-writable-p file)
1075                   (write-region (point-min) (point-max) file nil 'silent)
1076                   (and gnus-score-after-write-file-function
1077                        (funcall gnus-score-after-write-file-function file)))))
1078             (and gnus-score-uncacheable-files
1079                  (string-match gnus-score-uncacheable-files file)
1080                  (gnus-score-remove-from-cache file)))))
1081       (kill-buffer (current-buffer)))))
1082   
1083 (defun gnus-score-headers (score-files &optional trace)
1084   ;; Score `gnus-newsgroup-headers'.
1085   (let (scores news)
1086     ;; PLM: probably this is not the best place to clear orphan-score
1087     (setq gnus-orphan-score nil)
1088     (setq gnus-scores-articles nil)
1089     (setq gnus-scores-exclude-files nil)
1090     ;; Load the score files.
1091     (while score-files
1092       (if (stringp (car score-files))
1093           ;; It is a string, which means that it's a score file name,
1094           ;; so we load the score file and add the score alist to
1095           ;; the list of alists.
1096           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1097         ;; It is an alist, so we just add it to the list directly.
1098         (setq scores (nconc (car score-files) scores)))
1099       (setq score-files (cdr score-files)))
1100     ;; Prune the score files that are to be excluded, if any.
1101     (when gnus-scores-exclude-files
1102       (let ((s scores)
1103             c)
1104         (while s
1105           (and (setq c (rassq (car s) gnus-score-cache))
1106                (member (car c) gnus-scores-exclude-files)
1107                (setq scores (delq (car s) scores)))
1108           (setq s (cdr s)))))
1109     (setq news scores)
1110     ;; Do the scoring.
1111     (while news
1112       (setq scores news
1113             news nil)
1114       (when (and gnus-summary-default-score
1115                  scores)
1116         (let* ((entries gnus-header-index)
1117                (now (gnus-day-number (current-time-string)))
1118                (expire (and gnus-score-expiry-days
1119                             (- now gnus-score-expiry-days)))
1120                (headers gnus-newsgroup-headers)
1121                (current-score-file gnus-current-score-file)
1122                entry header new)
1123           (gnus-message 5 "Scoring...")
1124           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1125           (while (setq header (pop headers))
1126             ;; WARNING: The assq makes the function O(N*S) while it could
1127             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1128             ;; and S is (length gnus-newsgroup-scored).
1129             (or (assq (mail-header-number header) gnus-newsgroup-scored)
1130                 (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1131                       (cons (cons header (or gnus-summary-default-score 0))
1132                             gnus-scores-articles))))
1133
1134           (save-excursion
1135             (set-buffer (get-buffer-create "*Headers*"))
1136             (buffer-disable-undo (current-buffer))
1137
1138             ;; Set the global variant of this variable.
1139             (setq gnus-current-score-file current-score-file)
1140             ;; score orphans
1141             (when gnus-orphan-score 
1142               (setq gnus-score-index 
1143                     (nth 1 (assoc "references" gnus-header-index)))
1144               (gnus-score-orphans gnus-orphan-score))
1145             ;; Run each header through the score process.
1146             (while entries
1147               (setq entry (pop entries)
1148                     header (nth 0 entry)
1149                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1150               (when (< 0 (apply 'max (mapcar
1151                                       (lambda (score)
1152                                         (length (gnus-score-get header score)))
1153                                       scores)))
1154                 ;; Call the scoring function for this type of "header".
1155                 (when (setq new (funcall (nth 2 entry) scores header
1156                                          now expire trace))
1157                   (push new news))))
1158             ;; Remove the buffer.
1159             (kill-buffer (current-buffer)))
1160
1161           ;; Add articles to `gnus-newsgroup-scored'.
1162           (while gnus-scores-articles
1163             (or (= gnus-summary-default-score (cdar gnus-scores-articles))
1164                 (setq gnus-newsgroup-scored
1165                       (cons (cons (mail-header-number 
1166                                    (caar gnus-scores-articles))
1167                                   (cdar gnus-scores-articles))
1168                             gnus-newsgroup-scored)))
1169             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1170
1171           (gnus-message 5 "Scoring...done"))))))
1172
1173
1174 (defun gnus-get-new-thread-ids (articles)
1175   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
1176         (refind gnus-score-index)
1177         id-list art this tref)
1178     (while articles
1179       (setq art (car articles)
1180             this (aref (car art) index)
1181             tref (aref (car art) refind)
1182             articles (cdr articles))
1183       (if (string-equal tref "")        ;no references line
1184           (setq id-list (cons this id-list))))
1185     id-list))
1186
1187 ;; Orphan functions written by plm@atcmp.nl (Peter Mutsaers).
1188 (defun gnus-score-orphans (score)
1189   (let ((new-thread-ids (gnus-get-new-thread-ids gnus-scores-articles))
1190         alike articles art arts this last this-id)
1191     
1192     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1193           articles gnus-scores-articles)
1194
1195     ;;more or less the same as in gnus-score-string
1196     (erase-buffer)
1197     (while articles
1198       (setq art (car articles)
1199             this (aref (car art) gnus-score-index)
1200             articles (cdr articles))
1201       ;;completely skip if this is empty (not a child, so not an orphan)
1202       (if (not (string= this ""))
1203           (if (equal last this)
1204               ;; O(N*H) cons-cells used here, where H is the number of
1205               ;; headers.
1206               (setq alike (cons art alike))
1207             (if last
1208                 (progn
1209                   ;; Insert the line, with a text property on the
1210                   ;; terminating newline referring to the articles with
1211                   ;; this line.
1212                   (insert last ?\n)
1213                   (put-text-property (1- (point)) (point) 'articles alike)))
1214             (setq alike (list art)
1215                   last this))))
1216     (and last                           ; Bwadr, duplicate code.
1217          (progn
1218            (insert last ?\n)                    
1219            (put-text-property (1- (point)) (point) 'articles alike)))
1220
1221     ;; PLM: now delete those lines that contain an entry from new-thread-ids
1222     (while new-thread-ids
1223       (setq this-id (car new-thread-ids)
1224             new-thread-ids (cdr new-thread-ids))
1225       (goto-char (point-min))
1226       (while (search-forward this-id nil t)
1227         ;; found a match. remove this line
1228         (beginning-of-line)
1229         (kill-line 1)))
1230
1231     ;; now for each line: update its articles with score by moving to
1232     ;; every end-of-line in the buffer and read the articles property
1233     (goto-char (point-min))
1234     (while (eq 0 (progn
1235                    (end-of-line)
1236                    (setq arts (get-text-property (point) 'articles))
1237                    (while arts
1238                      (setq art (car arts)
1239                            arts (cdr arts))
1240                      (setcdr art (+ score (cdr art))))
1241                    (forward-line))))))
1242              
1243
1244 (defun gnus-score-integer (scores header now expire &optional trace)
1245   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1246         entries alist)
1247
1248     ;; Find matches.
1249     (while scores
1250       (setq alist (car scores)
1251             scores (cdr scores)
1252             entries (assoc header alist))
1253       (while (cdr entries)              ;First entry is the header index.
1254         (let* ((rest (cdr entries))             
1255                (kill (car rest))
1256                (match (nth 0 kill))
1257                (type (or (nth 3 kill) '>))
1258                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1259                (date (nth 2 kill))
1260                (found nil)
1261                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1262                                    (eq type '>=) (eq type '=))
1263                                type
1264                              (error "Illegal match type: %s" type)))
1265                (articles gnus-scores-articles))
1266           ;; Instead of doing all the clever stuff that
1267           ;; `gnus-score-string' does to minimize searches and stuff,
1268           ;; I will assume that people generally will put so few
1269           ;; matches on numbers that any cleverness will take more
1270           ;; time than one would gain.
1271           (while articles
1272             (and (funcall match-func 
1273                           (or (aref (caar articles) gnus-score-index) 0)
1274                           match)
1275                  (progn
1276                    (and trace (setq gnus-score-trace 
1277                                     (cons
1278                                      (cons
1279                                       (car-safe (rassq alist gnus-score-cache))
1280                                       kill)
1281                                      gnus-score-trace)))
1282                    (setq found t)
1283                    (setcdr (car articles) (+ score (cdar articles)))))
1284             (setq articles (cdr articles)))
1285           ;; Update expire date
1286           (cond ((null date))           ;Permanent entry.
1287                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1288                  (gnus-score-set 'touched '(t) alist)
1289                  (setcar (nthcdr 2 kill) now))
1290                 ((and expire (< date expire)) ;Old entry, remove.
1291                  (gnus-score-set 'touched '(t) alist)
1292                  (setcdr entries (cdr rest))
1293                  (setq rest entries)))
1294           (setq entries rest)))))
1295   nil)
1296
1297 (defun gnus-score-date (scores header now expire &optional trace)
1298   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1299         entries alist)
1300
1301     ;; Find matches.
1302     (while scores
1303       (setq alist (car scores)
1304             scores (cdr scores)
1305             entries (assoc header alist))
1306       (while (cdr entries)              ;First entry is the header index.
1307         (let* ((rest (cdr entries))             
1308                (kill (car rest))
1309                (match (timezone-make-date-sortable (nth 0 kill)))
1310                (type (or (nth 3 kill) 'before))
1311                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1312                (date (nth 2 kill))
1313                (found nil)
1314                (match-func 
1315                 (cond ((eq type 'after) 'string<)
1316                       ((eq type 'before) 'gnus-string>)
1317                       ((eq type 'at) 'string=)
1318                       (t (error "Illegal match type: %s" type))))
1319                (articles gnus-scores-articles)
1320                l)
1321           ;; Instead of doing all the clever stuff that
1322           ;; `gnus-score-string' does to minimize searches and stuff,
1323           ;; I will assume that people generally will put so few
1324           ;; matches on numbers that any cleverness will take more
1325           ;; time than one would gain.
1326           (while articles
1327             (and
1328              (setq l (aref (caar articles) gnus-score-index))
1329              (funcall match-func match (timezone-make-date-sortable l))
1330              (progn
1331                (and trace (setq gnus-score-trace 
1332                                 (cons
1333                                  (cons
1334                                   (car-safe (rassq alist gnus-score-cache))
1335                                   kill)
1336                                  gnus-score-trace)))
1337                (setq found t)
1338                (setcdr (car articles) (+ score (cdar articles)))))
1339             (setq articles (cdr articles)))
1340           ;; Update expire date
1341           (cond ((null date))           ;Permanent entry.
1342                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1343                  (gnus-score-set 'touched '(t) alist)
1344                  (setcar (nthcdr 2 kill) now))
1345                 ((and expire (< date expire))   ;Old entry, remove.
1346                  (gnus-score-set 'touched '(t) alist)
1347                  (setcdr entries (cdr rest))
1348                  (setq rest entries)))
1349           (setq entries rest)))))
1350   nil)
1351
1352 (defun gnus-score-body (scores header now expire &optional trace)
1353   (save-excursion
1354     (set-buffer nntp-server-buffer)
1355     (setq gnus-scores-articles
1356           (sort gnus-scores-articles
1357                 (lambda (a1 a2)
1358                   (< (mail-header-number (car a1))
1359                      (mail-header-number (car a2))))))
1360     (save-restriction
1361       (let* ((buffer-read-only nil)
1362              (articles gnus-scores-articles)
1363              (all-scores scores)
1364              (request-func (cond ((string= "head" header)
1365                                   'gnus-request-head)
1366                                  ((string= "body" header)
1367                                   'gnus-request-body)
1368                                  (t 'gnus-request-article)))
1369              entries alist ofunc article last)
1370         (when articles
1371           (while (cdr articles)
1372             (setq articles (cdr articles)))
1373           (setq last (mail-header-number (caar articles)))
1374           (setq articles gnus-scores-articles)
1375           ;; Not all backends support partial fetching.  In that case,
1376           ;; we just fetch the entire article.
1377           (or (gnus-check-backend-function 
1378                (and (string-match "^gnus-" (symbol-name request-func))
1379                     (intern (substring (symbol-name request-func)
1380                                        (match-end 0))))
1381                gnus-newsgroup-name)
1382               (progn
1383                 (setq ofunc request-func)
1384                 (setq request-func 'gnus-request-article)))
1385           (while articles
1386             (setq article (mail-header-number (caar articles)))
1387             (gnus-message 7 "Scoring on article %s of %s..." article last)
1388             (when (funcall request-func article gnus-newsgroup-name)
1389               (widen)
1390               (goto-char (point-min))
1391               ;; If just parts of the article is to be searched, but the
1392               ;; backend didn't support partial fetching, we just narrow
1393               ;; to the relevant parts.
1394               (if ofunc
1395                   (if (eq ofunc 'gnus-request-head)
1396                       (narrow-to-region
1397                        (point)
1398                        (or (search-forward "\n\n" nil t) (point-max)))
1399                     (narrow-to-region
1400                      (or (search-forward "\n\n" nil t) (point))
1401                      (point-max))))
1402               (setq scores all-scores)
1403               ;; Find matches.
1404               (while scores
1405                 (setq alist (car scores)
1406                       scores (cdr scores)
1407                       entries (assoc header alist))
1408                 (while (cdr entries)    ;First entry is the header index.
1409                   (let* ((rest (cdr entries))           
1410                          (kill (car rest))
1411                          (match (nth 0 kill))
1412                          (type (or (nth 3 kill) 's))
1413                          (score (or (nth 1 kill) 
1414                                     gnus-score-interactive-default-score))
1415                          (date (nth 2 kill))
1416                          (found nil)
1417                          (case-fold-search 
1418                           (not (or (eq type 'R) (eq type 'S)
1419                                    (eq type 'Regexp) (eq type 'String))))
1420                          (search-func 
1421                           (cond ((or (eq type 'r) (eq type 'R)
1422                                      (eq type 'regexp) (eq type 'Regexp))
1423                                  're-search-forward)
1424                                 ((or (eq type 's) (eq type 'S)
1425                                      (eq type 'string) (eq type 'String))
1426                                  'search-forward)
1427                                 (t
1428                                  (error "Illegal match type: %s" type)))))
1429                     (goto-char (point-min))
1430                     (if (funcall search-func match nil t)
1431                         ;; Found a match, update scores.
1432                         (progn
1433                           (setcdr (car articles) (+ score (cdar articles)))
1434                           (setq found t)
1435                           (and trace (setq gnus-score-trace 
1436                                            (cons
1437                                             (cons
1438                                              (car-safe
1439                                               (rassq alist gnus-score-cache))
1440                                              kill)
1441                                             gnus-score-trace)))))
1442                     ;; Update expire date
1443                     (cond
1444                      ((null date))      ;Permanent entry.
1445                      ((and found gnus-update-score-entry-dates) ;Match, update date.
1446                       (gnus-score-set 'touched '(t) alist)
1447                       (setcar (nthcdr 2 kill) now))
1448                      ((and expire (< date expire)) ;Old entry, remove.
1449                       (gnus-score-set 'touched '(t) alist)
1450                       (setcdr entries (cdr rest))
1451                       (setq rest entries)))
1452                     (setq entries rest)))))
1453             (setq articles (cdr articles)))))))
1454   nil)
1455
1456 (defun gnus-score-followup (scores header now expire &optional trace thread)
1457   ;; Insert the unique article headers in the buffer.
1458   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1459         (current-score-file gnus-current-score-file)
1460         (all-scores scores)
1461         ;; gnus-score-index is used as a free variable.
1462         alike last this art entries alist articles
1463         new news)
1464
1465     ;; Change score file to the adaptive score file.  All entries that
1466     ;; this function makes will be put into this file.
1467     (save-excursion
1468       (set-buffer gnus-summary-buffer)
1469       (gnus-score-load-file
1470        (or gnus-newsgroup-adaptive-score-file
1471            (gnus-score-file-name 
1472             gnus-newsgroup-name gnus-adaptive-file-suffix))))
1473
1474     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1475           articles gnus-scores-articles)
1476
1477     (erase-buffer)
1478     (while articles
1479       (setq art (car articles)
1480             this (aref (car art) gnus-score-index)
1481             articles (cdr articles))
1482       (if (equal last this)
1483           (setq alike (cons art alike))
1484         (if last
1485             (progn
1486               (insert last ?\n)
1487               (put-text-property (1- (point)) (point) 'articles alike)))
1488         (setq alike (list art)
1489               last this)))
1490     (and last                           ; Bwadr, duplicate code.
1491          (progn
1492            (insert last ?\n)                    
1493            (put-text-property (1- (point)) (point) 'articles alike)))
1494   
1495     ;; Find matches.
1496     (while scores
1497       (setq alist (car scores)
1498             scores (cdr scores)
1499             entries (assoc header alist))
1500       (while (cdr entries)              ;First entry is the header index.
1501         (let* ((rest (cdr entries))             
1502                (kill (car rest))
1503                (match (nth 0 kill))
1504                (type (or (nth 3 kill) 's))
1505                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1506                (date (nth 2 kill))
1507                (found nil)
1508                (mt (aref (symbol-name type) 0))
1509                (case-fold-search 
1510                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1511                (dmt (downcase mt))
1512                (search-func 
1513                 (cond ((= dmt ?r) 're-search-forward)
1514                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1515                       (t (error "Illegal match type: %s" type))))
1516                arts art)
1517           (goto-char (point-min))
1518           (if (= dmt ?e)
1519               (while (funcall search-func match nil t)
1520                 (and (= (progn (beginning-of-line) (point))
1521                         (match-beginning 0))
1522                      (= (progn (end-of-line) (point))
1523                         (match-end 0))
1524                      (progn
1525                        (setq found (setq arts (get-text-property 
1526                                                (point) 'articles)))
1527                        ;; Found a match, update scores.
1528                        (while arts
1529                          (setq art (car arts)
1530                                arts (cdr arts))
1531                          (gnus-score-add-followups 
1532                           (car art) score all-scores thread))))
1533                 (end-of-line))
1534             (while (funcall search-func match nil t)
1535               (end-of-line)
1536               (setq found (setq arts (get-text-property (point) 'articles)))
1537               ;; Found a match, update scores.
1538               (while (setq art (pop arts))
1539                 (when (setq new (gnus-score-add-followups
1540                                  (car art) score all-scores thread))
1541                   (push new news)))))
1542           ;; Update expire date
1543           (cond ((null date))           ;Permanent entry.
1544                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1545                  (gnus-score-set 'touched '(t) alist)
1546                  (setcar (nthcdr 2 kill) now))
1547                 ((and expire (< date expire))   ;Old entry, remove.
1548                  (gnus-score-set 'touched '(t) alist)
1549                  (setcdr entries (cdr rest))
1550                  (setq rest entries)))
1551           (setq entries rest))))
1552     ;; We change the score file back to the previous one.
1553     (save-excursion
1554       (set-buffer gnus-summary-buffer)
1555       (gnus-score-load-file current-score-file))
1556     (list (cons "references" news))))
1557
1558 (defun gnus-score-add-followups (header score scores &optional thread)
1559   "Add a score entry to the adapt file."
1560   (save-excursion
1561     (set-buffer gnus-summary-buffer)
1562     (let* ((id (mail-header-id header))
1563            (scores (car scores))
1564            entry dont)
1565       ;; Don't enter a score if there already is one.
1566       (while (setq entry (pop scores))
1567         (and (equal "references" (car entry))
1568              (or (null (nth 3 (cadr entry)))
1569                  (eq 's (nth 3 (cadr entry))))
1570              (assoc id entry)
1571              (setq dont t)))
1572       (unless dont
1573         (gnus-summary-score-entry 
1574          (if thread "thread" "references")
1575          id 's score (current-time-string) nil t)))))
1576
1577 (defun gnus-score-string (score-list header now expire &optional trace)
1578   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1579   ;; Update matching entries to NOW and remove unmatched entries older
1580   ;; than EXPIRE.
1581   
1582   ;; Insert the unique article headers in the buffer.
1583   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1584         ;; gnus-score-index is used as a free variable.
1585         alike last this art entries alist articles scores fuzzy)
1586
1587     ;; Sorting the articles costs os O(N*log N) but will allow us to
1588     ;; only match with each unique header.  Thus the actual matching
1589     ;; will be O(M*U) where M is the number of strings to match with,
1590     ;; and U is the number of unique headers.  It is assumed (but
1591     ;; untested) this will be a net win because of the large constant
1592     ;; factor involved with string matching.
1593     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1594           articles gnus-scores-articles)
1595
1596     (erase-buffer)
1597     (while articles
1598       (setq art (car articles)
1599             this (aref (car art) gnus-score-index)
1600             articles (cdr articles))
1601       (if (equal last this)
1602           ;; O(N*H) cons-cells used here, where H is the number of
1603           ;; headers.
1604           (setq alike (cons art alike))
1605         (if last
1606             (progn
1607               ;; Insert the line, with a text property on the
1608               ;; terminating newline referring to the articles with
1609               ;; this line.
1610               (insert last ?\n)
1611               (put-text-property (1- (point)) (point) 'articles alike)))
1612         (setq alike (list art)
1613               last this)))
1614     (and last                           ; Bwadr, duplicate code.
1615          (progn
1616            (insert last ?\n)                    
1617            (put-text-property (1- (point)) (point) 'articles alike)))
1618
1619     ;; Find ordinary matches.
1620     (setq scores score-list) 
1621     (while scores
1622       (setq alist (car scores)
1623             scores (cdr scores)
1624             entries (assoc header alist))
1625       (while (cdr entries)              ;First entry is the header index.
1626         (let* ((rest (cdr entries))             
1627                (kill (car rest))
1628                (match (nth 0 kill))
1629                (type (or (nth 3 kill) 's))
1630                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1631                (date (nth 2 kill))
1632                (found nil)
1633                (mt (aref (symbol-name type) 0))
1634                (case-fold-search 
1635                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1636                (dmt (downcase mt))
1637                (search-func 
1638                 (cond ((= dmt ?r) 're-search-forward)
1639                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1640                       (t (error "Illegal match type: %s" type))))
1641                arts art)
1642           (if (= dmt ?f)
1643               (setq fuzzy t)
1644             ;; Do non-fuzzy matching.
1645             (goto-char (point-min))
1646             (if (= dmt ?e)
1647                 ;; Do exact matching.
1648                 (while (and (not (eobp)) 
1649                             (funcall search-func match nil t))
1650                   (and (= (progn (beginning-of-line) (point))
1651                           (match-beginning 0))
1652                        (= (progn (end-of-line) (point))
1653                           (match-end 0))
1654                        (progn
1655                          (setq found (setq arts (get-text-property 
1656                                                  (point) 'articles)))
1657                          ;; Found a match, update scores.
1658                          (if trace
1659                              (while arts
1660                                (setq art (car arts)
1661                                      arts (cdr arts))
1662                                (setcdr art (+ score (cdr art)))
1663                                (setq gnus-score-trace
1664                                      (cons
1665                                       (cons
1666                                        (car-safe
1667                                         (rassq alist gnus-score-cache))
1668                                        kill)
1669                                       gnus-score-trace)))
1670                            (while arts
1671                              (setq art (car arts)
1672                                    arts (cdr arts))
1673                              (setcdr art (+ score (cdr art)))))))
1674                   (forward-line 1))
1675               ;; Do regexp and substring matching.
1676               (and (string= match "") (setq match "\n"))
1677               (while (and (not (eobp))
1678                           (funcall search-func match nil t))
1679                 (goto-char (match-beginning 0))
1680                 (end-of-line)
1681                 (setq found (setq arts (get-text-property (point) 'articles)))
1682                 ;; Found a match, update scores.
1683                 (if trace
1684                     (while arts
1685                       (setq art (pop arts))
1686                       (setcdr art (+ score (cdr art)))
1687                       (push (cons
1688                               (car-safe (rassq alist gnus-score-cache))
1689                               kill)
1690                             gnus-score-trace))
1691                   (while arts
1692                     (setq art (pop arts))
1693                     (setcdr art (+ score (cdr art)))))
1694                 (forward-line 1)))
1695             ;; Update expire date
1696             (cond 
1697              ((null date))              ;Permanent entry.
1698              ((and found gnus-update-score-entry-dates) ;Match, update date.
1699               (gnus-score-set 'touched '(t) alist)
1700               (setcar (nthcdr 2 kill) now))
1701              ((and expire (< date expire)) ;Old entry, remove.
1702               (gnus-score-set 'touched '(t) alist)
1703               (setcdr entries (cdr rest))
1704               (setq rest entries))))
1705           (setq entries rest))))
1706
1707     ;; Find fuzzy matches.
1708     (when fuzzy
1709       (setq scores score-list)
1710       (gnus-simplify-buffer-fuzzy)
1711       (while scores
1712         (setq alist (car scores)
1713               scores (cdr scores)
1714               entries (assoc header alist))
1715         (while (cdr entries)            ;First entry is the header index.
1716           (let* ((rest (cdr entries))           
1717                  (kill (car rest))
1718                  (match (nth 0 kill))
1719                  (type (or (nth 3 kill) 's))
1720                  (score (or (nth 1 kill) gnus-score-interactive-default-score))
1721                  (date (nth 2 kill))
1722                  (found nil)
1723                  (mt (aref (symbol-name type) 0))
1724                  (case-fold-search (not (= mt ?F)))
1725                  (dmt (downcase mt))
1726                  arts art)
1727             (when (= dmt ?f)
1728               (goto-char (point-min))
1729               (while (and (not (eobp)) 
1730                           (search-forward match nil t))
1731                 (when (and (= (progn (beginning-of-line) (point))
1732                               (match-beginning 0))
1733                            (= (progn (end-of-line) (point))
1734                               (match-end 0)))
1735                   (setq found (setq arts (get-text-property 
1736                                           (point) 'articles)))
1737                   ;; Found a match, update scores.
1738                   (if trace
1739                       (while arts
1740                         (setq art (pop arts))
1741                         (setcdr art (+ score (cdr art)))
1742                         (push (cons
1743                                (car-safe (rassq alist gnus-score-cache))
1744                                kill)
1745                               gnus-score-trace))
1746                     (while arts
1747                       (setq art (pop arts))
1748                       (setcdr art (+ score (cdr art))))))
1749                 (forward-line 1))
1750               ;; Update expire date
1751               (unless trace
1752                 (cond 
1753                  ((null date))          ;Permanent entry.
1754                  ((and found gnus-update-score-entry-dates) ;Match, update date.
1755                   (gnus-score-set 'touched '(t) alist)
1756                   (setcar (nthcdr 2 kill) now))
1757                  ((and expire (< date expire)) ;Old entry, remove.
1758                   (gnus-score-set 'touched '(t) alist)
1759                   (setcdr entries (cdr rest))
1760                   (setq rest entries)))))
1761             (setq entries rest))))))
1762   nil)
1763
1764 (defun gnus-score-string< (a1 a2)
1765   ;; Compare headers in articles A2 and A2.
1766   ;; The header index used is the free variable `gnus-score-index'.
1767   (string-lessp (aref (car a1) gnus-score-index)
1768                 (aref (car a2) gnus-score-index)))
1769
1770 (defun gnus-score-build-cons (article)
1771   ;; Build a `gnus-newsgroup-scored' type cons from ARTICLE.
1772   (cons (mail-header-number (car article)) (cdr article)))
1773
1774 (defun gnus-current-score-file-nondirectory (&optional score-file)
1775   (let ((score-file (or score-file gnus-current-score-file)))
1776     (if score-file 
1777         (gnus-short-group-name (file-name-nondirectory score-file))
1778       "none")))
1779
1780 (defun gnus-score-adaptive ()
1781   (save-excursion
1782     (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
1783            (alist malist)
1784            (date (current-time-string)) 
1785            (data gnus-newsgroup-data)
1786            elem headers match)
1787       ;; First we transform the adaptive rule alist into something
1788       ;; that's faster to process.
1789       (while malist
1790         (setq elem (car malist))
1791         (if (symbolp (car elem))
1792             (setcar elem (symbol-value (car elem))))
1793         (setq elem (cdr elem))
1794         (while elem
1795           (setcdr (car elem) 
1796                   (cons (if (eq (caar elem) 'followup)
1797                             "references"
1798                           (symbol-name (caar elem)))
1799                         (cdar elem)))
1800           (setcar (car elem) 
1801                   `(lambda (h)
1802                      (,(intern 
1803                         (concat "mail-header-" 
1804                                 (if (eq (caar elem) 'followup)
1805                                     "message-id"
1806                                   (downcase (symbol-name (caar elem))))))
1807                       h)))
1808           (setq elem (cdr elem)))
1809         (setq malist (cdr malist)))
1810       ;; We change the score file to the adaptive score file.
1811       (save-excursion
1812         (set-buffer gnus-summary-buffer)
1813         (gnus-score-load-file 
1814          (or gnus-newsgroup-adaptive-score-file
1815              (gnus-score-file-name 
1816               gnus-newsgroup-name gnus-adaptive-file-suffix))))
1817       ;; The we score away.
1818       (while data
1819         (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
1820         (if (or (not elem)
1821                 (gnus-data-pseudo-p (car data)))
1822             ()
1823           (when (setq headers (gnus-data-header (car data)))
1824             (while elem 
1825               (setq match (funcall (caar elem) headers))
1826               (gnus-summary-score-entry 
1827                (nth 1 (car elem)) match
1828                (cond
1829                 ((numberp match)
1830                  '=)
1831                 ((equal (nth 1 (car elem)) "date")
1832                  'a)
1833                 (t
1834                  ;; Whether we use substring or exact matches are controlled
1835                  ;; here.  
1836                  (if (or (not gnus-score-exact-adapt-limit)
1837                          (< (length match) gnus-score-exact-adapt-limit))
1838                      'e 
1839                    (if (equal (nth 1 (car elem)) "subject")
1840                        'f 's))))
1841                (nth 2 (car elem)) date nil t)
1842               (setq elem (cdr elem)))))
1843         (setq data (cdr data))))))
1844
1845 (defun gnus-score-edit-done ()
1846   (let ((bufnam (buffer-file-name (current-buffer)))
1847         (winconf gnus-prev-winconf))
1848     (and winconf (set-window-configuration winconf))
1849     (gnus-score-remove-from-cache bufnam)
1850     (gnus-score-load-file bufnam)))
1851
1852 (defun gnus-score-find-trace ()
1853   "Find all score rules that applies to the current article."
1854   (interactive)
1855   (let ((gnus-newsgroup-headers
1856          (list (gnus-summary-article-header)))
1857         (gnus-newsgroup-scored nil)
1858         (buf (current-buffer))
1859         trace)
1860     (setq gnus-score-trace nil)
1861     (gnus-possibly-score-headers 'trace)
1862     (or (setq trace gnus-score-trace)
1863         (error "No score rules apply to the current article."))
1864     (pop-to-buffer "*Gnus Scores*")
1865     (gnus-add-current-to-buffer-list)
1866     (erase-buffer)
1867     (while trace
1868       (insert (format "%S  ->  %s\n" (cdar trace)
1869                       (file-name-nondirectory (caar trace))))
1870       (setq trace (cdr trace)))
1871     (goto-char (point-min))
1872     (pop-to-buffer buf)))
1873
1874 (defun gnus-summary-rescore ()
1875   "Redo the entire scoring process in the current summary."
1876   (interactive)
1877   (gnus-score-save)
1878   (setq gnus-score-cache nil)
1879   (setq gnus-newsgroup-scored nil)
1880   (gnus-possibly-score-headers)
1881   (gnus-score-update-all-lines))
1882   
1883 (defun gnus-score-flush-cache ()
1884   "Flush the cache of score files."
1885   (interactive)
1886   (gnus-score-save)
1887   (setq gnus-score-cache nil
1888         gnus-score-alist nil
1889         gnus-short-name-score-file-cache nil)
1890   (gnus-message 6 "The score cache is now flushed"))
1891
1892 (gnus-add-shutdown 'gnus-score-close 'gnus)
1893
1894 (defvar gnus-score-file-alist-cache nil)
1895
1896 (defun gnus-score-close ()
1897   "Clear all internal score variables."
1898   (setq gnus-score-cache nil
1899         gnus-internal-global-score-files nil
1900         gnus-score-file-list nil
1901         gnus-score-file-alist-cache nil))
1902
1903 ;; Summary score marking commands.
1904
1905 (defun gnus-summary-raise-same-subject-and-select (score)
1906   "Raise articles which has the same subject with SCORE and select the next."
1907   (interactive "p")
1908   (let ((subject (gnus-summary-article-subject)))
1909     (gnus-summary-raise-score score)
1910     (while (gnus-summary-find-subject subject)
1911       (gnus-summary-raise-score score))
1912     (gnus-summary-next-article t)))
1913
1914 (defun gnus-summary-raise-same-subject (score)
1915   "Raise articles which has the same subject with SCORE."
1916   (interactive "p")
1917   (let ((subject (gnus-summary-article-subject)))
1918     (gnus-summary-raise-score score)
1919     (while (gnus-summary-find-subject subject)
1920       (gnus-summary-raise-score score))
1921     (gnus-summary-next-subject 1 t)))
1922
1923 (defun gnus-score-default (level)
1924   (if level (prefix-numeric-value level) 
1925     gnus-score-interactive-default-score))
1926
1927 (defun gnus-summary-raise-thread (&optional score)
1928   "Raise the score of the articles in the current thread with SCORE."
1929   (interactive "P")
1930   (setq score (gnus-score-default score))
1931   (let (e)
1932     (save-excursion
1933       (let ((articles (gnus-summary-articles-in-thread)))
1934         (while articles
1935           (gnus-summary-goto-subject (car articles))
1936           (gnus-summary-raise-score score)
1937           (setq articles (cdr articles))))
1938       (setq e (point)))
1939     (let ((gnus-summary-check-current t))
1940       (or (zerop (gnus-summary-next-subject 1 t))
1941           (goto-char e))))
1942   (gnus-summary-recenter)
1943   (gnus-summary-position-point)
1944   (gnus-set-mode-line 'summary))
1945
1946 (defun gnus-summary-lower-same-subject-and-select (score)
1947   "Raise articles which has the same subject with SCORE and select the next."
1948   (interactive "p")
1949   (gnus-summary-raise-same-subject-and-select (- score)))
1950
1951 (defun gnus-summary-lower-same-subject (score)
1952   "Raise articles which has the same subject with SCORE."
1953   (interactive "p")
1954   (gnus-summary-raise-same-subject (- score)))
1955
1956 (defun gnus-summary-lower-thread (&optional score)
1957   "Lower score of articles in the current thread with SCORE."
1958   (interactive "P")
1959   (gnus-summary-raise-thread (- (1- (gnus-score-default score)))))
1960
1961 ;;; Finding score files. 
1962
1963 (defun gnus-score-score-files (group)
1964   "Return a list of all possible score files."
1965   ;; Search and set any global score files.
1966   (and gnus-global-score-files 
1967        (or gnus-internal-global-score-files
1968            (gnus-score-search-global-directories gnus-global-score-files)))
1969   ;; Fix the kill-file dir variable.
1970   (setq gnus-kill-files-directory 
1971         (file-name-as-directory gnus-kill-files-directory))
1972   ;; If we can't read it, there are no score files.
1973   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
1974       (setq gnus-score-file-list nil)
1975     (if (not (gnus-use-long-file-name 'not-score))
1976         ;; We do not use long file names, so we have to do some
1977         ;; directory traversing.  
1978         (setq gnus-score-file-list 
1979               (cons nil 
1980                     (or gnus-short-name-score-file-cache
1981                         (prog2
1982                             (gnus-message 6 "Finding all score files...")
1983                             (setq gnus-short-name-score-file-cache
1984                                   (gnus-score-score-files-1
1985                                    gnus-kill-files-directory))
1986                           (gnus-message 6 "Finding all score files...done")))))
1987       ;; We want long file names.
1988       (when (or (not gnus-score-file-list)
1989                 (not (car gnus-score-file-list))
1990                 (gnus-file-newer-than gnus-kill-files-directory
1991                                       (car gnus-score-file-list)))
1992         (setq gnus-score-file-list 
1993               (cons (nth 5 (file-attributes gnus-kill-files-directory))
1994                     (nreverse 
1995                      (directory-files 
1996                       gnus-kill-files-directory t 
1997                       (gnus-score-file-regexp)))))))
1998     (cdr gnus-score-file-list)))
1999
2000 (defun gnus-score-score-files-1 (dir)
2001   "Return all possible score files under DIR."
2002   (let ((files (directory-files (expand-file-name dir) t nil t))
2003         (regexp (gnus-score-file-regexp))
2004         out file)
2005     (while (setq file (pop files))
2006       (cond 
2007        ;; Ignore "." and "..".
2008        ((string-match "/\\.\\.?\\'" file)
2009         nil)
2010        ;; Recurse down directories.
2011        ((file-directory-p file)
2012         (setq out (nconc (gnus-score-score-files-1 file) out)))
2013        ;; Add files to the list of score files.
2014        ((string-match regexp file)
2015         (push file out))))
2016     (or out
2017         ;; Return a dummy value.
2018         (list "~/News/this.file.does.not.exist.SCORE"))))
2019        
2020 (defun gnus-score-file-regexp ()
2021   "Return a regexp that match all score files."
2022   (concat "\\(" gnus-score-file-suffix 
2023           "\\|" gnus-adaptive-file-suffix "\\)\\'"))
2024         
2025 (defun gnus-score-find-bnews (group)
2026   "Return a list of score files for GROUP.
2027 The score files are those files in the ~/News/ directory which matches
2028 GROUP using BNews sys file syntax."
2029   (let* ((sfiles (append (gnus-score-score-files group)
2030                          gnus-internal-global-score-files))
2031          (kill-dir (file-name-as-directory 
2032                     (expand-file-name gnus-kill-files-directory)))
2033          (klen (length kill-dir))
2034          (score-regexp (gnus-score-file-regexp))
2035          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2036          ofiles not-match regexp)
2037     (save-excursion
2038       (set-buffer (get-buffer-create "*gnus score files*"))
2039       (buffer-disable-undo (current-buffer))
2040       ;; Go through all score file names and create regexp with them
2041       ;; as the source.  
2042       (while sfiles
2043         (erase-buffer)
2044         (insert (car sfiles))
2045         (goto-char (point-min))
2046         ;; First remove the suffix itself.
2047         (when (re-search-forward (concat "." score-regexp) nil t)
2048           (replace-match "" t t) 
2049           (goto-char (point-min))
2050           (if (looking-at (regexp-quote kill-dir))
2051               ;; If the file name was just "SCORE", `klen' is one character
2052               ;; too much.
2053               (delete-char (min (1- (point-max)) klen))
2054             (goto-char (point-max))
2055             (search-backward "/")
2056             (delete-region (1+ (point)) (point-min)))
2057           ;; If short file names were used, we have to translate slashes.
2058           (goto-char (point-min))
2059           (let ((regexp (concat
2060                          "[/:" (if trans (char-to-string trans) "") "]")))
2061             (while (re-search-forward regexp nil t)
2062               (replace-match "." t t)))
2063           ;; Cludge to get rid of "nntp+" problems.
2064           (goto-char (point-min))
2065           (and (looking-at "nn[a-z]+\\+")
2066                (progn
2067                  (search-forward "+")
2068                  (forward-char -1)
2069                  (insert "\\")))
2070           ;; Translate "all" to ".*".
2071           (while (search-forward "all" nil t)
2072             (replace-match ".*" t t))
2073           (goto-char (point-min))
2074           ;; Deal with "not."s.
2075           (if (looking-at "not.")
2076               (progn
2077                 (setq not-match t)
2078                 (setq regexp (buffer-substring 5 (point-max))))
2079             (setq regexp (buffer-substring 1 (point-max)))
2080             (setq not-match nil))
2081           ;; Finally - if this resulting regexp matches the group name,
2082           ;; we add this score file to the list of score files
2083           ;; applicable to this group.
2084           (if (or (and not-match
2085                        (not (string-match regexp group)))
2086                   (and (not not-match)
2087                        (string-match regexp group)))
2088               (setq ofiles (cons (car sfiles) ofiles))))
2089         (setq sfiles (cdr sfiles)))
2090       (kill-buffer (current-buffer))
2091       ;; Slight kludge here - the last score file returned should be
2092       ;; the local score file, whether it exists or not. This is so
2093       ;; that any score commands the user enters will go to the right
2094       ;; file, and not end up in some global score file.
2095       (let ((localscore (gnus-score-file-name group)))
2096         (setq ofiles (cons localscore (delete localscore ofiles))))
2097       (nreverse ofiles))))
2098
2099 (defun gnus-score-find-single (group)
2100   "Return list containing the score file for GROUP."
2101   (list (or gnus-newsgroup-adaptive-score-file
2102             (gnus-score-file-name group gnus-adaptive-file-suffix))
2103         (gnus-score-file-name group)))
2104
2105 (defun gnus-score-find-hierarchical (group)
2106   "Return list of score files for GROUP.
2107 This includes the score file for the group and all its parents."
2108   (let ((all (copy-sequence '(nil)))
2109         (start 0))
2110     (while (string-match "\\." group (1+ start))
2111       (setq start (match-beginning 0))
2112       (setq all (cons (substring group 0 start) all)))
2113     (setq all (cons group all))
2114     (nconc
2115      (mapcar (lambda (newsgroup)
2116                (gnus-score-file-name newsgroup gnus-adaptive-file-suffix))
2117              (setq all (nreverse all)))
2118      (mapcar 'gnus-score-file-name all))))
2119
2120 (defun gnus-score-find-alist (group)
2121   "Return list of score files for GROUP.
2122 The list is determined from the variable gnus-score-file-alist."
2123   (let ((alist gnus-score-file-multiple-match-alist)
2124         score-files)
2125     ;; if this group has been seen before, return the cached entry
2126     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2127         (cdr score-files)               ;ensures caching groups with no matches
2128       ;; handle the multiple match alist
2129       (while alist
2130         (and (string-match (caar alist) group)
2131              (setq score-files
2132                    (nconc score-files (copy-sequence (cdar alist)))))
2133         (setq alist (cdr alist)))
2134       (setq alist gnus-score-file-single-match-alist)
2135       ;; handle the single match alist
2136       (while alist
2137         (and (string-match (caar alist) group)
2138              ;; progn used just in case ("regexp") has no files
2139              ;; and score-files is still nil. -sj
2140              ;; this can be construed as a "stop searching here" feature :>
2141              ;; and used to simplify regexps in the single-alist 
2142              (progn
2143                (setq score-files
2144                      (nconc score-files (copy-sequence (cdar alist))))
2145                (setq alist nil)))
2146         (setq alist (cdr alist)))
2147       ;; cache the score files
2148       (setq gnus-score-file-alist-cache
2149             (cons (cons group score-files) gnus-score-file-alist-cache))
2150       score-files)))
2151
2152 (defun gnus-possibly-score-headers (&optional trace)
2153   (let ((funcs gnus-score-find-score-files-function)
2154         score-files)
2155     ;; Make sure funcs is a list.
2156     (and funcs
2157          (not (listp funcs))
2158          (setq funcs (list funcs)))
2159     ;; Get the initial score files for this group.
2160     (when funcs 
2161       (setq score-files (gnus-score-find-alist gnus-newsgroup-name)))
2162     ;; Go through all the functions for finding score files (or actual
2163     ;; scores) and add them to a list.
2164     (while funcs
2165       (when (gnus-functionp (car funcs))
2166         (setq score-files 
2167               (nconc score-files (funcall (car funcs) gnus-newsgroup-name))))
2168       (setq funcs (cdr funcs)))
2169     ;; Check whether there is a `score-file' group parameter.
2170     (let ((param-file (gnus-group-get-parameter 
2171                        gnus-newsgroup-name 'score-file)))
2172       (when param-file
2173         (push param-file score-files)))
2174     ;; Do the scoring if there are any score files for this group.
2175     (when score-files
2176       (gnus-score-headers score-files trace))))
2177
2178 (defun gnus-score-file-name (newsgroup &optional suffix)
2179   "Return the name of a score file for NEWSGROUP."
2180   (let ((suffix (or suffix gnus-score-file-suffix)))
2181     (nnheader-translate-file-chars
2182      (cond
2183       ((or (null newsgroup)
2184            (string-equal newsgroup ""))
2185        ;; The global score file is placed at top of the directory.
2186        (expand-file-name 
2187         suffix gnus-kill-files-directory))
2188       ((gnus-use-long-file-name 'not-score)
2189        ;; Append ".SCORE" to newsgroup name.
2190        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2191                                  "." suffix)
2192                          gnus-kill-files-directory))
2193       (t
2194        ;; Place "SCORE" under the hierarchical directory.
2195        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2196                                  "/" suffix)
2197                          gnus-kill-files-directory))))))
2198
2199 (defun gnus-score-search-global-directories (files)
2200   "Scan all global score directories for score files."
2201   ;; Set the variable `gnus-internal-global-score-files' to all
2202   ;; available global score files.
2203   (interactive (list gnus-global-score-files))
2204   (let (out)
2205     (while files
2206       (if (string-match "/$" (car files))
2207           (setq out (nconc (directory-files 
2208                             (car files) t
2209                             (concat (gnus-score-file-regexp) "$"))))
2210         (setq out (cons (car files) out)))
2211       (setq files (cdr files)))
2212     (setq gnus-internal-global-score-files out)))
2213
2214 (defun gnus-score-default-fold-toggle ()
2215   "Toggle folding for new score file entries."
2216   (interactive)
2217   (setq gnus-score-default-fold (not gnus-score-default-fold))
2218   (if gnus-score-default-fold
2219       (gnus-message 1 "New score file entries will be case insensitive.")
2220     (gnus-message 1 "New score file entries will be case sensitive.")))
2221
2222 (provide 'gnus-score)
2223
2224 ;;; gnus-score.el ends here