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