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