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