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