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