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