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