*** empty log message ***
[gnus] / lisp / gnus-score.el
1 1;;; gnus-score.el --- scoring code for Gnus
2 ;; Copyright (C) 1995,96,97 Free Software Foundation, Inc.
3
4 ;; Author: Per Abrahamsen <amanda@iesd.auc.dk>
5 ;;      Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;;; Code:
28
29 (eval-when-compile (require 'cl))
30
31 (require 'gnus)
32 (require 'gnus-sum)
33 (require 'gnus-range)
34 (require 'message)
35
36 (defcustom gnus-global-score-files nil
37   "List of global score files and directories.
38 Set this variable if you want to use people's score files.  One entry
39 for each score file or each score file directory.  Gnus will decide
40 by itself what score files are applicable to which group.
41
42 Say you want to use the single score file
43 \"/ftp.gnus.org@ftp:/pub/larsi/ding/score/soc.motss.SCORE\" and all
44 score files in the \"/ftp.some-where:/pub/score\" directory.
45
46  (setq gnus-global-score-files
47        '(\"/ftp.gnus.org:/pub/larsi/ding/score/soc.motss.SCORE\"
48          \"/ftp.some-where:/pub/score\"))"
49   :group 'gnus-score-files
50   :type '(repeat file))
51
52 (defcustom gnus-score-file-single-match-alist nil
53   "Alist mapping regexps to lists of score files.
54 Each element of this alist should be of the form
55         (\"REGEXP\" [ \"SCORE-FILE-1\" ] [ \"SCORE-FILE-2\" ] ... )
56
57 If the name of a group is matched by REGEXP, the corresponding scorefiles
58 will be used for that group.
59 The first match found is used, subsequent matching entries are ignored (to
60 use multiple matches, see gnus-score-file-multiple-match-alist).
61
62 These score files are loaded in addition to any files returned by
63 gnus-score-find-score-files-function (which see)."
64   :group 'gnus-score-files
65   :type '(repeat (cons regexp (repeat file))))
66
67 (defcustom gnus-score-file-multiple-match-alist nil
68   "Alist mapping regexps to lists of score files.
69 Each element of this alist should be of the form
70         (\"REGEXP\" [ \"SCORE-FILE-1\" ] [ \"SCORE-FILE-2\" ] ... )
71
72 If the name of a group is matched by REGEXP, the corresponding scorefiles
73 will be used for that group.
74 If multiple REGEXPs match a group, the score files corresponding to each
75 match will be used (for only one match to be used, see
76 gnus-score-file-single-match-alist).
77
78 These score files are loaded in addition to any files returned by
79 gnus-score-find-score-files-function (which see)."
80   :group 'gnus-score-files
81   :type '(repeat (cons regexp (repeat file))))
82
83 (defcustom gnus-score-file-suffix "SCORE"
84   "Suffix of the score files."
85   :group 'gnus-score-files
86   :type 'string)
87
88 (defcustom gnus-adaptive-file-suffix "ADAPT"
89   "Suffix of the adaptive score files."
90   :group 'gnus-score-files
91   :group 'gnus-score-adapt
92   :type 'string)
93
94 (defcustom gnus-score-find-score-files-function 'gnus-score-find-bnews
95   "Function used to find score files.
96 The function will be called with the group name as the argument, and
97 should return a list of score files to apply to that group.  The score
98 files do not actually have to exist.
99
100 Predefined values are:
101
102 gnus-score-find-single: Only apply the group's own score file.
103 gnus-score-find-hierarchical: Also apply score files from parent groups.
104 gnus-score-find-bnews: Apply score files whose names matches.
105
106 See the documentation to these functions for more information.
107
108 This variable can also be a list of functions to be called.  Each
109 function should either return a list of score files, or a list of
110 score alists."
111   :group 'gnus-score-files
112   :type '(radio (function-item gnus-score-find-single)
113                 (function-item gnus-score-find-hierarchical)
114                 (function-item gnus-score-find-bnews)
115                 (function :tag "Other")))
116
117 (defcustom gnus-score-interactive-default-score 1000
118   "*Scoring commands will raise/lower the score with this number as the default."
119   :group 'gnus-score-default
120   :type 'integer)
121
122 (defcustom gnus-score-expiry-days 7
123   "*Number of days before unused score file entries are expired.
124 If this variable is nil, no score file entries will be expired."
125   :group 'gnus-score-expire
126   :type '(choice (const :tag "never" nil)
127                  number))
128
129 (defcustom gnus-update-score-entry-dates t
130   "*In non-nil, update matching score entry dates.
131 If this variable is nil, then score entries that provide matches
132 will be expired along with non-matching score entries."
133   :group 'gnus-score-expire
134   :type 'boolean)
135
136 (defcustom gnus-orphan-score nil
137   "*All orphans get this score added.  Set in the score file."
138   :group 'gnus-score-default
139   :type '(choice (const nil)
140                  integer))
141
142 (defcustom gnus-decay-scores nil
143   "*If non-nil, decay non-permanent scores."
144   :group 'gnus-score-decay
145   :type 'boolean)
146
147 (defcustom gnus-decay-score-function 'gnus-decay-score
148   "*Function called to decay a score.
149 It is called with one parameter -- the score to be decayed."
150   :group 'gnus-score-decay
151   :type '(radio (function-item gnus-decay-score)
152                 (function :tag "Other")))
153
154 (defcustom gnus-score-decay-constant 3
155   "*Decay all \"small\" scores with this amount."
156   :group 'gnus-score-decay
157   :type 'integer)
158
159 (defcustom gnus-score-decay-scale .05
160   "*Decay all \"big\" scores with this factor."
161   :group 'gnus-score-decay
162   :type 'number)
163
164 (defcustom gnus-home-score-file nil
165   "Variable to control where interactive score entries are to go.
166 It can be:
167
168  * A string
169    This file file will be used as the home score file.
170
171  * A function
172    The result of this function will be used as the home score file.
173    The function will be passed the name of the group as its
174    parameter.
175
176  * A list
177    The elements in this list can be:
178
179    * `(regexp file-name ...)'
180      If the `regexp' matches the group name, the first `file-name' will
181      will be used as the home score file.  (Multiple filenames are
182      allowed so that one may use gnus-score-file-single-match-alist to
183      set this variable.)
184
185    * A function.
186      If the function returns non-nil, the result will be used
187      as the home score file.  The function will be passed the
188      name of the group as its parameter.
189
190    * A string.  Use the string as the home score file.
191
192    The list will be traversed from the beginning towards the end looking
193    for matches."
194   :group 'gnus-score-files
195   :type '(choice string
196                  (repeat (choice string
197                                  (cons regexp (repeat file))
198                                  function))
199                  function))
200
201 (defcustom gnus-home-adapt-file nil
202   "Variable to control where new adaptive score entries are to go.
203 This variable allows the same syntax as `gnus-home-score-file'."
204   :group 'gnus-score-adapt
205   :group 'gnus-score-files
206   :type '(choice string
207                  (repeat (choice string
208                                  (cons regexp (repeat file))
209                                  function))
210                  function))
211
212 (defcustom gnus-default-adaptive-score-alist
213   '((gnus-kill-file-mark)
214     (gnus-unread-mark)
215     (gnus-read-mark (from 3) (subject 30))
216     (gnus-catchup-mark (subject -10))
217     (gnus-killed-mark (from -1) (subject -20))
218     (gnus-del-mark (from -2) (subject -15)))
219 "Alist of marks and scores."
220 :group 'gnus-score-adapt
221 :type '(repeat (cons (symbol :tag "Mark")
222                      (repeat (list (choice :tag "Header"
223                                            (const from)
224                                            (const subject)
225                                            (symbol :tag "other"))
226                                    (integer :tag "Score"))))))
227
228 (defcustom gnus-ignored-adaptive-words nil
229   "List of words to be ignored when doing adaptive word scoring."
230   :group 'gnus-score-adapt
231   :type '(repeat string))
232
233 (defcustom gnus-default-ignored-adaptive-words
234   '("a" "i" "the" "to" "of" "and" "in" "is" "it" "for" "that" "if" "you"
235     "this" "be" "on" "with" "not" "have" "are" "or" "as" "from" "can"
236     "but" "by" "at" "an" "will" "no" "all" "was" "do" "there" "my" "one"
237     "so" "we" "they" "what" "would" "any" "which" "about" "get" "your"
238     "use" "some" "me" "then" "name" "like" "out" "when" "up" "time"
239     "other" "more" "only" "just" "end" "also" "know" "how" "new" "should"
240     "been" "than" "them" "he" "who" "make" "may" "people" "these" "now"
241     "their" "here" "into" "first" "could" "way" "had" "see" "work" "well"
242     "were" "two" "very" "where" "while" "us" "because" "good" "same"
243     "even" "much" "most" "many" "such" "long" "his" "over" "last" "since"
244     "right" "before" "our" "without" "too" "those" "why" "must" "part"
245     "being" "current" "back" "still" "go" "point" "value" "each" "did"
246     "both" "true" "off" "say" "another" "state" "might" "under" "start"
247     "try" "re")
248   "Default list of words to be ignored when doing adaptive word scoring."
249   :group 'gnus-score-adapt
250   :type '(repeat string))
251
252 (defcustom gnus-default-adaptive-word-score-alist
253   `((,gnus-read-mark . 30)
254     (,gnus-catchup-mark . -10)
255     (,gnus-killed-mark . -20)
256     (,gnus-del-mark . -15))
257 "Alist of marks and scores."
258 :group 'gnus-score-adapt
259 :type '(repeat (cons (character :tag "Mark")
260                      (integer :tag "Score"))))
261
262 (defcustom gnus-adaptive-word-minimum nil
263   "If a number, this is the minimum score value that can be assigned to a word."
264   :group 'gnus-score-adapt
265   :type '(choice (const nil) integer))
266
267 (defcustom gnus-score-mimic-keymap nil
268   "*Have the score entry functions pretend that they are a keymap."
269   :group 'gnus-score-default
270   :type 'boolean)
271
272 (defcustom gnus-score-exact-adapt-limit 10
273   "*Number that says how long a match has to be before using substring matching.
274 When doing adaptive scoring, one normally uses fuzzy or substring
275 matching.  However, if the header one matches is short, the possibility
276 for false positives is great, so if the length of the match is less
277 than this variable, exact matching will be used.
278
279 If this variable is nil, exact matching will always be used."
280   :group 'gnus-score-adapt
281   :type '(choice (const nil) integer))
282
283 (defcustom gnus-score-uncacheable-files "ADAPT$"
284   "All score files that match this regexp will not be cached."
285   :group 'gnus-score-adapt
286   :group 'gnus-score-files
287   :type 'regexp)
288
289 (defcustom gnus-score-default-header nil
290   "Default header when entering new scores.
291
292 Should be one of the following symbols.
293
294  a: from
295  s: subject
296  b: body
297  h: head
298  i: message-id
299  t: references
300  x: xref
301  l: lines
302  d: date
303  f: followup
304
305 If nil, the user will be asked for a header."
306   :group 'gnus-score-default
307   :type '(choice (const :tag "from" a)
308                  (const :tag "subject" s)
309                  (const :tag "body" b)
310                  (const :tag "head" h)
311                  (const :tag "message-id" i)
312                  (const :tag "references" t)
313                  (const :tag "xref" x)
314                  (const :tag "lines" l)
315                  (const :tag "date" d)
316                  (const :tag "followup" f)
317                  (const :tag "ask" nil)))
318
319 (defcustom gnus-score-default-type nil
320   "Default match type when entering new scores.
321
322 Should be one of the following symbols.
323
324  s: substring
325  e: exact string
326  f: fuzzy string
327  r: regexp string
328  b: before date
329  a: at date
330  n: this date
331  <: less than number
332  >: greater than number
333  =: equal to number
334
335 If nil, the user will be asked for a match type."
336   :group 'gnus-score-default
337   :type '(choice (const :tag "substring" s)
338                  (const :tag "exact string" e)
339                  (const :tag "fuzzy string" f)
340                  (const :tag "regexp string" r)
341                  (const :tag "before date" b)
342                  (const :tag "at date" a)
343                  (const :tag "this date" n)
344                  (const :tag "less than number" <)
345                  (const :tag "greater than number" >)
346                  (const :tag "equal than number" =)
347                  (const :tag "ask" nil)))
348
349 (defcustom gnus-score-default-fold nil
350   "Use case folding for new score file entries iff not nil."
351   :group 'gnus-score-default
352   :type 'boolean)
353
354 (defcustom gnus-score-default-duration nil
355   "Default duration of effect when entering new scores.
356
357 Should be one of the following symbols.
358
359  t: temporary
360  p: permanent
361  i: immediate
362
363 If nil, the user will be asked for a duration."
364   :group 'gnus-score-default
365   :type '(choice (const :tag "temporary" t)
366                  (const :tag "permanent" p)
367                  (const :tag "immediate" i)
368                  (const :tag "ask" nil)))
369
370 (defcustom gnus-score-after-write-file-function nil
371   "Function called with the name of the score file just written to disk."
372   :group 'gnus-score-files
373   :type 'function)
374
375 \f
376
377 ;; Internal variables.
378
379 (defvar gnus-adaptive-word-syntax-table
380   (let ((table (copy-syntax-table (standard-syntax-table)))
381         (numbers '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9)))
382     (while numbers
383       (modify-syntax-entry (pop numbers) " " table))
384     (modify-syntax-entry ?' "w" table)
385     table)
386   "Syntax table used when doing adaptive word scoring.")
387
388 (defvar gnus-scores-exclude-files nil)
389 (defvar gnus-internal-global-score-files nil)
390 (defvar gnus-score-file-list nil)
391
392 (defvar gnus-short-name-score-file-cache nil)
393
394 (defvar gnus-score-help-winconf nil)
395 (defvar gnus-adaptive-score-alist gnus-default-adaptive-score-alist)
396 (defvar gnus-adaptive-word-score-alist gnus-default-adaptive-word-score-alist)
397 (defvar gnus-score-trace nil)
398 (defvar gnus-score-edit-buffer nil)
399
400 (defvar gnus-score-alist nil
401   "Alist containing score information.
402 The keys can be symbols or strings.  The following symbols are defined.
403
404 touched: If this alist has been modified.
405 mark:    Automatically mark articles below this.
406 expunge: Automatically expunge articles below this.
407 files:   List of other score files to load when loading this one.
408 eval:    Sexp to be evaluated when the score file is loaded.
409
410 String entries have the form (HEADER (MATCH TYPE SCORE DATE) ...)
411 where HEADER is the header being scored, MATCH is the string we are
412 looking for, TYPE is a flag indicating whether it should use regexp or
413 substring matching, SCORE is the score to add and DATE is the date
414 of the last successful match.")
415
416 (defvar gnus-score-cache nil)
417 (defvar gnus-scores-articles nil)
418 (defvar gnus-score-index nil)
419
420
421 (defconst gnus-header-index
422   ;; Name to index alist.
423   '(("number" 0 gnus-score-integer)
424     ("subject" 1 gnus-score-string)
425     ("from" 2 gnus-score-string)
426     ("date" 3 gnus-score-date)
427     ("message-id" 4 gnus-score-string)
428     ("references" 5 gnus-score-string)
429     ("chars" 6 gnus-score-integer)
430     ("lines" 7 gnus-score-integer)
431     ("xref" 8 gnus-score-string)
432     ("head" -1 gnus-score-body)
433     ("body" -1 gnus-score-body)
434     ("all" -1 gnus-score-body)
435     ("followup" 2 gnus-score-followup)
436     ("thread" 5 gnus-score-thread)))
437
438 ;;; Summary mode score maps.
439
440 (gnus-define-keys (gnus-summary-score-map "V" gnus-summary-mode-map)
441   "s" gnus-summary-set-score
442   "a" gnus-summary-score-entry
443   "S" gnus-summary-current-score
444   "c" gnus-score-change-score-file
445   "C" gnus-score-customize
446   "m" gnus-score-set-mark-below
447   "x" gnus-score-set-expunge-below
448   "R" gnus-summary-rescore
449   "e" gnus-score-edit-current-scores
450   "f" gnus-score-edit-file
451   "F" gnus-score-flush-cache
452   "t" gnus-score-find-trace
453   "w" gnus-score-find-favourite-words)
454
455 ;; Summary score file commands
456
457 ;; Much modification of the kill (ahem, score) code and lots of the
458 ;; functions are written by Per Abrahamsen <amanda@iesd.auc.dk>.
459
460 (defun gnus-summary-lower-score (&optional score symp)
461   "Make a score entry based on the current article.
462 The user will be prompted for header to score on, match type,
463 permanence, and the string to be used.  The numerical prefix will be
464 used as score."
465   (interactive (gnus-interactive "P\ny"))
466   (gnus-summary-increase-score (- (gnus-score-default score)) symp))
467
468 (defun gnus-score-kill-help-buffer ()
469   (when (get-buffer "*Score Help*")
470     (kill-buffer "*Score Help*")
471     (when gnus-score-help-winconf
472       (set-window-configuration gnus-score-help-winconf))))
473
474 (defun gnus-summary-increase-score (&optional score symp)
475   "Make a score entry based on the current article.
476 The user will be prompted for header to score on, match type,
477 permanence, and the string to be used.  The numerical prefix will be
478 used as score."
479   (interactive (gnus-interactive "P\ny"))
480   (let* ((nscore (gnus-score-default score))
481          (prefix (if (< nscore 0) ?L ?I))
482          (increase (> nscore 0))
483          (char-to-header
484           '((?a "from" nil nil string)
485             (?s "subject" nil nil string)
486             (?b "body" "" nil body-string)
487             (?h "head" "" nil body-string)
488             (?i "message-id" nil t string)
489             (?t "references" "message-id" nil string)
490             (?x "xref" nil nil string)
491             (?l "lines" nil nil number)
492             (?d "date" nil nil date)
493             (?f "followup" nil nil string)
494             (?T "thread" nil nil string)))
495          (char-to-type
496           '((?s s "substring" string)
497             (?e e "exact string" string)
498             (?f f "fuzzy string" string)
499             (?r r "regexp string" string)
500             (?z s "substring" body-string)
501             (?p r "regexp string" body-string)
502             (?b before "before date" date)
503             (?a at "at date" date)
504             (?n now "this date" date)
505             (?< < "less than number" number)
506             (?> > "greater than number" number)
507             (?= = "equal to number" number)))
508          (current-score-file gnus-current-score-file)
509          (char-to-perm
510           (list (list ?t (current-time-string) "temporary")
511                 '(?p perm "permanent") '(?i now "immediate")))
512          (mimic gnus-score-mimic-keymap)
513          (hchar (and gnus-score-default-header
514                      (aref (symbol-name gnus-score-default-header) 0)))
515          (tchar (and gnus-score-default-type
516                      (aref (symbol-name gnus-score-default-type) 0)))
517          (pchar (and gnus-score-default-duration
518                      (aref (symbol-name gnus-score-default-duration) 0)))
519          entry temporary type match)
520
521     (unwind-protect
522         (progn
523
524           ;; First we read the header to score.
525           (while (not hchar)
526             (if mimic
527                 (progn
528                   (sit-for 1)
529                   (message "%c-" prefix))
530               (message "%s header (%s?): " (if increase "Increase" "Lower")
531                        (mapconcat (lambda (s) (char-to-string (car s)))
532                                   char-to-header "")))
533             (setq hchar (read-char))
534             (when (or (= hchar ??) (= hchar ?\C-h))
535               (setq hchar nil)
536               (gnus-score-insert-help "Match on header" char-to-header 1)))
537
538           (gnus-score-kill-help-buffer)
539           (unless (setq entry (assq (downcase hchar) char-to-header))
540             (if mimic (error "%c %c" prefix hchar)
541               (error "Illegal header type")))
542
543           (when (/= (downcase hchar) hchar)
544             ;; This was a majuscule, so we end reading and set the defaults.
545             (if mimic (message "%c %c" prefix hchar) (message ""))
546             (setq tchar (or tchar ?s)
547                   pchar (or pchar ?t)))
548
549           (let ((legal-types
550                  (delq nil
551                        (mapcar (lambda (s)
552                                  (if (eq (nth 4 entry)
553                                          (nth 3 s))
554                                      s nil))
555                                char-to-type))))
556             ;; We continue reading - the type.
557             (while (not tchar)
558               (if mimic
559                   (progn
560                     (sit-for 1) (message "%c %c-" prefix hchar))
561                 (message "%s header '%s' with match type (%s?): "
562                          (if increase "Increase" "Lower")
563                          (nth 1 entry)
564                          (mapconcat (lambda (s) (char-to-string (car s)))
565                                     legal-types "")))
566               (setq tchar (read-char))
567               (when (or (= tchar ??) (= tchar ?\C-h))
568                 (setq tchar nil)
569                 (gnus-score-insert-help "Match type" legal-types 2)))
570
571             (gnus-score-kill-help-buffer)
572             (unless (setq type (nth 1 (assq (downcase tchar) legal-types)))
573               (if mimic (error "%c %c" prefix hchar)
574                 (error "Illegal match type"))))
575
576           (when (/= (downcase tchar) tchar)
577             ;; It was a majuscule, so we end reading and use the default.
578             (if mimic (message "%c %c %c" prefix hchar tchar)
579               (message ""))
580             (setq pchar (or pchar ?p)))
581
582           ;; We continue reading.
583           (while (not pchar)
584             (if mimic
585                 (progn
586                   (sit-for 1) (message "%c %c %c-" prefix hchar tchar))
587               (message "%s permanence (%s?): " (if increase "Increase" "Lower")
588                        (mapconcat (lambda (s) (char-to-string (car s)))
589                                   char-to-perm "")))
590             (setq pchar (read-char))
591             (when (or (= pchar ??) (= pchar ?\C-h))
592               (setq pchar nil)
593               (gnus-score-insert-help "Match permanence" char-to-perm 2)))
594
595           (gnus-score-kill-help-buffer)
596           (if mimic (message "%c %c %c" prefix hchar tchar pchar)
597             (message ""))
598           (unless (setq temporary (cadr (assq pchar char-to-perm)))
599             ;; Deal with der(r)ided superannuated paradigms.
600             (when (and (eq (1+ prefix) 77)
601                        (eq (+ hchar 12) 109)
602                        (eq tchar 114)
603                        (eq (- pchar 4) 111))
604               (error "You rang?"))
605             (if mimic
606                 (error "%c %c %c %c" prefix hchar tchar pchar)
607               (error "Illegal match duration"))))
608       ;; Always kill the score help buffer.
609       (gnus-score-kill-help-buffer))
610
611     ;; We have all the data, so we enter this score.
612     (setq match (if (string= (nth 2 entry) "") ""
613                   (gnus-summary-header (or (nth 2 entry) (nth 1 entry)))))
614
615     ;; Modify the match, perhaps.
616     (cond
617      ((equal (nth 1 entry) "xref")
618       (when (string-match "^Xref: *" match)
619         (setq match (substring match (match-end 0))))
620       (when (string-match "^[^:]* +" match)
621         (setq match (substring match (match-end 0))))))
622
623     (when (memq type '(r R regexp Regexp))
624       (setq match (regexp-quote match)))
625
626     ;; Change score file to the "all.SCORE" file.
627     (when (eq symp 'a)
628       (save-excursion
629         (set-buffer gnus-summary-buffer)
630         (gnus-score-load-file
631          (gnus-score-file-name "all"))))
632     
633     (gnus-summary-score-entry
634      (nth 1 entry)                      ; Header
635      match                              ; Match
636      type                               ; Type
637      (if (eq score 's) nil score)       ; Score
638      (if (eq temporary 'perm)           ; Temp
639          nil
640        temporary)
641      (not (nth 3 entry)))               ; Prompt
642
643     (when (eq symp 'a)
644       ;; We change the score file back to the previous one.
645       (save-excursion
646         (set-buffer gnus-summary-buffer)
647         (gnus-score-load-file current-score-file)))))
648
649 (defun gnus-score-insert-help (string alist idx)
650   (setq gnus-score-help-winconf (current-window-configuration))
651   (save-excursion
652     (set-buffer (get-buffer-create "*Score Help*"))
653     (buffer-disable-undo (current-buffer))
654     (delete-windows-on (current-buffer))
655     (erase-buffer)
656     (insert string ":\n\n")
657     (let ((max -1)
658           (list alist)
659           (i 0)
660           n width pad format)
661       ;; find the longest string to display
662       (while list
663         (setq n (length (nth idx (car list))))
664         (unless (> max n)
665           (setq max n))
666         (setq list (cdr list)))
667       (setq max (+ max 4))              ; %c, `:', SPACE, a SPACE at end
668       (setq n (/ (1- (window-width)) max)) ; items per line
669       (setq width (/ (1- (window-width)) n)) ; width of each item
670       ;; insert `n' items, each in a field of width `width'
671       (while alist
672         (if (< i n)
673             ()
674           (setq i 0)
675           (delete-char -1)              ; the `\n' takes a char
676           (insert "\n"))
677         (setq pad (- width 3))
678         (setq format (concat "%c: %-" (int-to-string pad) "s"))
679         (insert (format format (caar alist) (nth idx (car alist))))
680         (setq alist (cdr alist))
681         (setq i (1+ i))))
682     ;; display ourselves in a small window at the bottom
683     (gnus-appt-select-lowest-window)
684     (split-window)
685     (pop-to-buffer "*Score Help*")
686     (let ((window-min-height 1))
687       (shrink-window-if-larger-than-buffer))
688     (select-window (get-buffer-window gnus-summary-buffer))))
689
690 (defun gnus-summary-header (header &optional no-err)
691   ;; Return HEADER for current articles, or error.
692   (let ((article (gnus-summary-article-number))
693         headers)
694     (if article
695         (if (and (setq headers (gnus-summary-article-header article))
696                  (vectorp headers))
697             (aref headers (nth 1 (assoc header gnus-header-index)))
698           (if no-err
699               nil
700             (error "Pseudo-articles can't be scored")))
701       (if no-err
702           (error "No article on current line")
703         nil))))
704
705 (defun gnus-newsgroup-score-alist ()
706   (or
707    (let ((param-file (gnus-group-find-parameter
708                       gnus-newsgroup-name 'score-file)))
709      (when param-file
710        (gnus-score-load param-file)))
711    (gnus-score-load
712     (gnus-score-file-name gnus-newsgroup-name)))
713   gnus-score-alist)
714
715 (defsubst gnus-score-get (symbol &optional alist)
716   ;; Get SYMBOL's definition in ALIST.
717   (cdr (assoc symbol
718               (or alist
719                   gnus-score-alist
720                   (gnus-newsgroup-score-alist)))))
721
722 (defun gnus-summary-score-entry (header match type score date
723                                         &optional prompt silent)
724   "Enter score file entry.
725 HEADER is the header being scored.
726 MATCH is the string we are looking for.
727 TYPE is the match type: substring, regexp, exact, fuzzy.
728 SCORE is the score to add.
729 DATE is the expire date, or nil for no expire, or 'now for immediate expire.
730 If optional argument `PROMPT' is non-nil, allow user to edit match.
731 If optional argument `SILENT' is nil, show effect of score entry."
732   (interactive
733    (list (completing-read "Header: "
734                           gnus-header-index
735                           (lambda (x) (fboundp (nth 2 x)))
736                           t)
737          (read-string "Match: ")
738          (if (y-or-n-p "Use regexp match? ") 'r 's)
739          (and current-prefix-arg
740               (prefix-numeric-value current-prefix-arg))
741          (cond ((not (y-or-n-p "Add to score file? "))
742                 'now)
743                ((y-or-n-p "Expire kill? ")
744                 (current-time-string))
745                (t nil))))
746   ;; Regexp is the default type.
747   (when (eq type t)
748     (setq type 'r))
749   ;; Simplify matches...
750   (cond ((or (eq type 'r) (eq type 's) (eq type nil))
751          (setq match (if match (gnus-simplify-subject-re match) "")))
752         ((eq type 'f)
753          (setq match (gnus-simplify-subject-fuzzy match))))
754   (let ((score (gnus-score-default score))
755         (header (format "%s" (downcase header)))
756         new)
757     (when prompt
758       (setq match (read-string
759                    (format "Match %s on %s, %s: "
760                            (cond ((eq date 'now)
761                                   "now")
762                                  ((stringp date)
763                                   "temp")
764                                  (t "permanent"))
765                            header
766                            (if (< score 0) "lower" "raise"))
767                    (if (numberp match)
768                        (int-to-string match)
769                      match))))
770
771     ;; Get rid of string props.
772     (setq match (format "%s" match))
773
774     ;; If this is an integer comparison, we transform from string to int.
775     (when (eq (nth 2 (assoc header gnus-header-index)) 'gnus-score-integer)
776       (setq match (string-to-int match)))
777
778     (unless (eq date 'now)
779       ;; Add the score entry to the score file.
780       (when (= score gnus-score-interactive-default-score)
781         (setq score nil))
782       (let ((old (gnus-score-get header))
783             elem)
784         (setq new
785               (cond
786                (type
787                 (list match score
788                       (and date (if (numberp date) date
789                                   (gnus-day-number date)))
790                       type))
791                (date (list match score (gnus-day-number date)))
792                (score (list match score))
793                (t (list match))))
794         ;; We see whether we can collapse some score entries.
795         ;; This isn't quite correct, because there may be more elements
796         ;; later on with the same key that have matching elems...  Hm.
797         (if (and old
798                  (setq elem (assoc match old))
799                  (eq (nth 3 elem) (nth 3 new))
800                  (or (and (numberp (nth 2 elem)) (numberp (nth 2 new)))
801                      (and (not (nth 2 elem)) (not (nth 2 new)))))
802             ;; Yup, we just add this new score to the old elem.
803             (setcar (cdr elem) (+ (or (nth 1 elem)
804                                       gnus-score-interactive-default-score)
805                                   (or (nth 1 new)
806                                       gnus-score-interactive-default-score)))
807           ;; Nope, we have to add a new elem.
808           (gnus-score-set header (if old (cons new old) (list new))))
809         (gnus-score-set 'touched '(t))))
810
811     ;; Score the current buffer.
812     (unless silent
813       (if (and (>= (nth 1 (assoc header gnus-header-index)) 0)
814                (eq (nth 2 (assoc header gnus-header-index))
815                    'gnus-score-string))
816           (gnus-summary-score-effect header match type score)
817         (gnus-summary-rescore)))
818
819     ;; Return the new scoring rule.
820     new))
821
822 (defun gnus-summary-score-effect (header match type score)
823   "Simulate the effect of a score file entry.
824 HEADER is the header being scored.
825 MATCH is the string we are looking for.
826 TYPE is the score type.
827 SCORE is the score to add."
828   (interactive (list (completing-read "Header: "
829                                       gnus-header-index
830                                       (lambda (x) (fboundp (nth 2 x)))
831                                       t)
832                      (read-string "Match: ")
833                      (y-or-n-p "Use regexp match? ")
834                      (prefix-numeric-value current-prefix-arg)))
835   (save-excursion
836     (unless (and (stringp match) (> (length match) 0))
837       (error "No match"))
838     (goto-char (point-min))
839     (let ((regexp (cond ((eq type 'f)
840                          (gnus-simplify-subject-fuzzy match))
841                         ((eq type 'r)
842                          match)
843                         ((eq type 'e)
844                          (concat "\\`" (regexp-quote match) "\\'"))
845                         (t
846                          (regexp-quote match)))))
847       (while (not (eobp))
848         (let ((content (gnus-summary-header header 'noerr))
849               (case-fold-search t))
850           (and content
851                (when (if (eq type 'f)
852                          (string-equal (gnus-simplify-subject-fuzzy content)
853                                        regexp)
854                        (string-match regexp content))
855                  (gnus-summary-raise-score score))))
856         (beginning-of-line 2))))
857   (gnus-set-mode-line 'summary))
858
859 (defun gnus-summary-score-crossposting (score date)
860   ;; Enter score file entry for current crossposting.
861   ;; SCORE is the score to add.
862   ;; DATE is the expire date.
863   (let ((xref (gnus-summary-header "xref"))
864         (start 0)
865         group)
866     (unless xref
867       (error "This article is not crossposted"))
868     (while (string-match " \\([^ \t]+\\):" xref start)
869       (setq start (match-end 0))
870       (when (not (string=
871                   (setq group
872                         (substring xref (match-beginning 1) (match-end 1)))
873                   gnus-newsgroup-name))
874         (gnus-summary-score-entry
875          "xref" (concat " " group ":") nil score date t)))))
876
877 \f
878 ;;;
879 ;;; Gnus Score Files
880 ;;;
881
882 ;; All score code written by Per Abrahamsen <abraham@iesd.auc.dk>.
883
884 ;; Added by Per Abrahamsen <amanda@iesd.auc.dk>.
885 (defun gnus-score-set-mark-below (score)
886   "Automatically mark articles with score below SCORE as read."
887   (interactive
888    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
889              (string-to-int (read-string "Mark below: ")))))
890   (setq score (or score gnus-summary-default-score 0))
891   (gnus-score-set 'mark (list score))
892   (gnus-score-set 'touched '(t))
893   (setq gnus-summary-mark-below score)
894   (gnus-score-update-lines))
895
896 (defun gnus-score-update-lines ()
897   "Update all lines in the summary buffer."
898   (save-excursion
899     (goto-char (point-min))
900     (while (not (eobp))
901       (gnus-summary-update-line)
902       (forward-line 1))))
903
904 (defun gnus-score-update-all-lines ()
905   "Update all lines in the summary buffer, even the hidden ones."
906   (save-excursion
907     (goto-char (point-min))
908     (let (hidden)
909       (while (not (eobp))
910         (when (gnus-summary-show-thread)
911           (push (point) hidden))
912         (gnus-summary-update-line)
913         (forward-line 1))
914       ;; Re-hide the hidden threads.
915       (while hidden
916         (goto-char (pop hidden))
917         (gnus-summary-hide-thread)))))
918
919 (defun gnus-score-set-expunge-below (score)
920   "Automatically expunge articles with score below SCORE."
921   (interactive
922    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
923              (string-to-int (read-string "Set expunge below: ")))))
924   (setq score (or score gnus-summary-default-score 0))
925   (gnus-score-set 'expunge (list score))
926   (gnus-score-set 'touched '(t)))
927
928 (defun gnus-score-followup-article (&optional score)
929   "Add SCORE to all followups to the article in the current buffer."
930   (interactive "P")
931   (setq score (gnus-score-default score))
932   (when (gnus-buffer-live-p gnus-summary-buffer)
933     (save-excursion
934       (save-restriction
935         (message-narrow-to-headers)
936         (let ((id (mail-fetch-field "message-id")))
937           (when id
938             (set-buffer gnus-summary-buffer)
939             (gnus-summary-score-entry
940              "references" (concat id "[ \t]*$") 'r
941              score (current-time-string) nil t)))))))
942
943 (defun gnus-score-followup-thread (&optional score)
944   "Add SCORE to all later articles in the thread the current buffer is part of."
945   (interactive "P")
946   (setq score (gnus-score-default score))
947   (when (gnus-buffer-live-p gnus-summary-buffer)
948     (save-excursion
949       (save-restriction
950         (goto-char (point-min))
951         (let ((id (mail-fetch-field "message-id")))
952           (when id
953             (set-buffer gnus-summary-buffer)
954             (gnus-summary-score-entry
955              "references" id 's
956              score (current-time-string))))))))
957
958 (defun gnus-score-set (symbol value &optional alist)
959   ;; Set SYMBOL to VALUE in ALIST.
960   (let* ((alist
961           (or alist
962               gnus-score-alist
963               (gnus-newsgroup-score-alist)))
964          (entry (assoc symbol alist)))
965     (cond ((gnus-score-get 'read-only alist)
966            ;; This is a read-only score file, so we do nothing.
967            )
968           (entry
969            (setcdr entry value))
970           ((null alist)
971            (error "Empty alist"))
972           (t
973            (setcdr alist
974                    (cons (cons symbol value) (cdr alist)))))))
975
976 (defun gnus-summary-raise-score (n)
977   "Raise the score of the current article by N."
978   (interactive "p")
979   (gnus-summary-set-score (+ (gnus-summary-article-score)
980                              (or n gnus-score-interactive-default-score ))))
981
982 (defun gnus-summary-set-score (n)
983   "Set the score of the current article to N."
984   (interactive "p")
985   (save-excursion
986     (gnus-summary-show-thread)
987     (let ((buffer-read-only nil))
988       ;; Set score.
989       (gnus-summary-update-mark
990        (if (= n (or gnus-summary-default-score 0)) ? 
991          (if (< n (or gnus-summary-default-score 0))
992              gnus-score-below-mark gnus-score-over-mark))
993        'score))
994     (let* ((article (gnus-summary-article-number))
995            (score (assq article gnus-newsgroup-scored)))
996       (if score (setcdr score n)
997         (push (cons article n) gnus-newsgroup-scored)))
998     (gnus-summary-update-line)))
999
1000 (defun gnus-summary-current-score ()
1001   "Return the score of the current article."
1002   (interactive)
1003   (gnus-message 1 "%s" (gnus-summary-article-score)))
1004
1005 (defun gnus-score-change-score-file (file)
1006   "Change current score alist."
1007   (interactive
1008    (list (read-file-name "Change to score file: " gnus-kill-files-directory)))
1009   (gnus-score-load-file file)
1010   (gnus-set-mode-line 'summary))
1011
1012 (defvar gnus-score-edit-exit-function)
1013 (defun gnus-score-edit-current-scores (file)
1014   "Edit the current score alist."
1015   (interactive (list gnus-current-score-file))
1016   (if (not gnus-current-score-file)
1017       (error "No current score file")
1018     (let ((winconf (current-window-configuration)))
1019       (when (buffer-name gnus-summary-buffer)
1020         (gnus-score-save))
1021       (gnus-make-directory (file-name-directory file))
1022       (setq gnus-score-edit-buffer (find-file-noselect file))
1023       (gnus-configure-windows 'edit-score)
1024       (gnus-score-mode)
1025       (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1026       (make-local-variable 'gnus-prev-winconf)
1027       (setq gnus-prev-winconf winconf))
1028     (gnus-message
1029      4 (substitute-command-keys
1030         "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits"))))
1031
1032 (defun gnus-score-edit-file (file)
1033   "Edit a score file."
1034   (interactive
1035    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
1036   (gnus-make-directory (file-name-directory file))
1037   (when (buffer-name gnus-summary-buffer)
1038     (gnus-score-save))
1039   (let ((winconf (current-window-configuration)))
1040     (setq gnus-score-edit-buffer (find-file-noselect file))
1041     (gnus-configure-windows 'edit-score)
1042     (gnus-score-mode)
1043     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1044     (make-local-variable 'gnus-prev-winconf)
1045     (setq gnus-prev-winconf winconf))
1046   (gnus-message
1047    4 (substitute-command-keys
1048       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
1049
1050 (defun gnus-score-load-file (file)
1051   ;; Load score file FILE.  Returns a list a retrieved score-alists.
1052   (let* ((file (expand-file-name
1053                 (or (and (string-match
1054                           (concat "^" (expand-file-name
1055                                        gnus-kill-files-directory))
1056                           (expand-file-name file))
1057                          file)
1058                     (concat (file-name-as-directory gnus-kill-files-directory)
1059                             file))))
1060          (cached (assoc file gnus-score-cache))
1061          (global (member file gnus-internal-global-score-files))
1062          lists alist)
1063     (if cached
1064         ;; The score file was already loaded.
1065         (setq alist (cdr cached))
1066       ;; We load the score file.
1067       (setq gnus-score-alist nil)
1068       (setq alist (gnus-score-load-score-alist file))
1069       ;; We add '(touched) to the alist to signify that it hasn't been
1070       ;; touched (yet).
1071       (unless (assq 'touched alist)
1072         (push (list 'touched nil) alist))
1073       ;; If it is a global score file, we make it read-only.
1074       (and global
1075            (not (assq 'read-only alist))
1076            (push (list 'read-only t) alist))
1077       (push (cons file alist) gnus-score-cache))
1078     (let ((a alist)
1079           found)
1080       (while a
1081         ;; Downcase all header names.
1082         (when (stringp (caar a))
1083           (setcar (car a) (downcase (caar a)))
1084           (setq found t))
1085         (pop a))
1086       ;; If there are actual scores in the alist, we add it to the
1087       ;; return value of this function.
1088       (when found
1089         (setq lists (list alist))))
1090     ;; Treat the other possible atoms in the score alist.
1091     (let ((mark (car (gnus-score-get 'mark alist)))
1092           (expunge (car (gnus-score-get 'expunge alist)))
1093           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
1094           (files (gnus-score-get 'files alist))
1095           (exclude-files (gnus-score-get 'exclude-files alist))
1096           (orphan (car (gnus-score-get 'orphan alist)))
1097           (adapt (gnus-score-get 'adapt alist))
1098           (thread-mark-and-expunge
1099            (car (gnus-score-get 'thread-mark-and-expunge alist)))
1100           (adapt-file (car (gnus-score-get 'adapt-file alist)))
1101           (local (gnus-score-get 'local alist))
1102           (decay (car (gnus-score-get 'decay alist)))
1103           (eval (car (gnus-score-get 'eval alist))))
1104       ;; Perform possible decays.
1105       (when (and gnus-decay-scores
1106                  (or cached (file-exists-p file))
1107                  (or (not decay)
1108                      (gnus-decay-scores alist decay)))
1109         (gnus-score-set 'touched '(t) alist)
1110         (gnus-score-set 'decay (list (gnus-time-to-day (current-time)))))
1111       ;; We do not respect eval and files atoms from global score
1112       ;; files.
1113       (when (and files (not global))
1114         (setq lists (apply 'append lists
1115                            (mapcar (lambda (file)
1116                                      (gnus-score-load-file file))
1117                                    (if adapt-file (cons adapt-file files)
1118                                      files)))))
1119       (when (and eval (not global))
1120         (eval eval))
1121       ;; We then expand any exclude-file directives.
1122       (setq gnus-scores-exclude-files
1123             (nconc
1124              (mapcar
1125               (lambda (sfile)
1126                 (expand-file-name sfile (file-name-directory file)))
1127               exclude-files)
1128              gnus-scores-exclude-files))
1129       (unless local
1130         (save-excursion
1131           (set-buffer gnus-summary-buffer)
1132           (while local
1133             (and (consp (car local))
1134                  (symbolp (caar local))
1135                  (progn
1136                    (make-local-variable (caar local))
1137                    (set (caar local) (nth 1 (car local)))))
1138             (setq local (cdr local)))))
1139       (when orphan
1140         (setq gnus-orphan-score orphan))
1141       (setq gnus-adaptive-score-alist
1142             (cond ((equal adapt '(t))
1143                    (setq gnus-newsgroup-adaptive t)
1144                    gnus-default-adaptive-score-alist)
1145                   ((equal adapt '(ignore))
1146                    (setq gnus-newsgroup-adaptive nil))
1147                   ((consp adapt)
1148                    (setq gnus-newsgroup-adaptive t)
1149                    adapt)
1150                   (t
1151                    ;;(setq gnus-newsgroup-adaptive gnus-use-adaptive-scoring)
1152                    gnus-default-adaptive-score-alist)))
1153       (setq gnus-thread-expunge-below
1154             (or thread-mark-and-expunge gnus-thread-expunge-below))
1155       (setq gnus-summary-mark-below
1156             (or mark mark-and-expunge gnus-summary-mark-below))
1157       (setq gnus-summary-expunge-below
1158             (or expunge mark-and-expunge gnus-summary-expunge-below))
1159       (setq gnus-newsgroup-adaptive-score-file
1160             (or adapt-file gnus-newsgroup-adaptive-score-file)))
1161     (setq gnus-current-score-file file)
1162     (setq gnus-score-alist alist)
1163     lists))
1164
1165 (defun gnus-score-load (file)
1166   ;; Load score FILE.
1167   (let ((cache (assoc file gnus-score-cache)))
1168     (if cache
1169         (setq gnus-score-alist (cdr cache))
1170       (setq gnus-score-alist nil)
1171       (gnus-score-load-score-alist file)
1172       (unless gnus-score-alist
1173         (setq gnus-score-alist (copy-alist '((touched nil)))))
1174       (push (cons file gnus-score-alist) gnus-score-cache))))
1175
1176 (defun gnus-score-remove-from-cache (file)
1177   (setq gnus-score-cache
1178         (delq (assoc file gnus-score-cache) gnus-score-cache)))
1179
1180 (defun gnus-score-load-score-alist (file)
1181   "Read score FILE."
1182   (let (alist)
1183     (if (not (file-readable-p file))
1184         ;; Couldn't read file.
1185         (setq gnus-score-alist nil)
1186       ;; Read file.
1187       (save-excursion
1188         (gnus-set-work-buffer)
1189         (insert-file-contents file)
1190         (goto-char (point-min))
1191         ;; Only do the loading if the score file isn't empty.
1192         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
1193           (setq alist
1194                 (condition-case ()
1195                     (read (current-buffer))
1196                   (error
1197                    (gnus-error 3.2 "Problem with score file %s" file))))))
1198       (if (eq (car alist) 'setq)
1199           ;; This is an old-style score file.
1200           (setq gnus-score-alist (gnus-score-transform-old-to-new alist))
1201         (setq gnus-score-alist alist))
1202       ;; Check the syntax of the score file.
1203       (setq gnus-score-alist
1204             (gnus-score-check-syntax gnus-score-alist file)))))
1205
1206 (defun gnus-score-check-syntax (alist file)
1207   "Check the syntax of the score ALIST."
1208   (cond
1209    ((null alist)
1210     nil)
1211    ((not (consp alist))
1212     (gnus-message 1 "Score file is not a list: %s" file)
1213     (ding)
1214     nil)
1215    (t
1216     (let ((a alist)
1217           sr err s type)
1218       (while (and a (not err))
1219         (setq
1220          err
1221          (cond
1222           ((not (listp (car a)))
1223            (format "Illegal score element %s in %s" (car a) file))
1224           ((stringp (caar a))
1225            (cond
1226             ((not (listp (setq sr (cdar a))))
1227              (format "Illegal header match %s in %s" (nth 1 (car a)) file))
1228             (t
1229              (setq type (caar a))
1230              (while (and sr (not err))
1231                (setq s (pop sr))
1232                (setq
1233                 err
1234                 (cond
1235                  ((if (member (downcase type) '("lines" "chars"))
1236                       (not (numberp (car s)))
1237                     (not (stringp (car s))))
1238                   (format "Illegal match %s in %s" (car s) file))
1239                  ((and (cadr s) (not (integerp (cadr s))))
1240                   (format "Non-integer score %s in %s" (cadr s) file))
1241                  ((and (caddr s) (not (integerp (caddr s))))
1242                   (format "Non-integer date %s in %s" (caddr s) file))
1243                  ((and (cadddr s) (not (symbolp (cadddr s))))
1244                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1245              err)))))
1246         (setq a (cdr a)))
1247       (if err
1248           (progn
1249             (ding)
1250             (gnus-message 3 err)
1251             (sit-for 2)
1252             nil)
1253         alist)))))
1254
1255 (defun gnus-score-transform-old-to-new (alist)
1256   (let* ((alist (nth 2 alist))
1257          out entry)
1258     (when (eq (car alist) 'quote)
1259       (setq alist (nth 1 alist)))
1260     (while alist
1261       (setq entry (car alist))
1262       (if (stringp (car entry))
1263           (let ((scor (cdr entry)))
1264             (push entry out)
1265             (while scor
1266               (setcar scor
1267                       (list (caar scor) (nth 2 (car scor))
1268                             (and (nth 3 (car scor))
1269                                  (gnus-day-number (nth 3 (car scor))))
1270                             (if (nth 1 (car scor)) 'r 's)))
1271               (setq scor (cdr scor))))
1272         (push (if (not (listp (cdr entry)))
1273                   (list (car entry) (cdr entry))
1274                 entry)
1275               out))
1276       (setq alist (cdr alist)))
1277     (cons (list 'touched t) (nreverse out))))
1278
1279 (defun gnus-score-save ()
1280   ;; Save all score information.
1281   (let ((cache gnus-score-cache)
1282         entry score file)
1283     (save-excursion
1284       (setq gnus-score-alist nil)
1285       (nnheader-set-temp-buffer " *Gnus Scores*")
1286       (while cache
1287         (current-buffer)
1288         (setq entry (pop cache)
1289               file (car entry)
1290               score (cdr entry))
1291         (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1292                 (gnus-score-get 'read-only score)
1293                 (and (file-exists-p file)
1294                      (not (file-writable-p file))))
1295             ()
1296           (setq score (setcdr entry (delq (assq 'touched score) score)))
1297           (erase-buffer)
1298           (let (emacs-lisp-mode-hook)
1299             (if (string-match
1300                  (concat (regexp-quote gnus-adaptive-file-suffix) "$")
1301                  file)
1302                 ;; This is an adaptive score file, so we do not run
1303                 ;; it through `pp'.  These files can get huge, and
1304                 ;; are not meant to be edited by human hands.
1305                 (gnus-prin1 score)
1306               ;; This is a normal score file, so we print it very
1307               ;; prettily.
1308               (pp score (current-buffer))))
1309           (gnus-make-directory (file-name-directory file))
1310           ;; If the score file is empty, we delete it.
1311           (if (zerop (buffer-size))
1312               (delete-file file)
1313             ;; There are scores, so we write the file.
1314             (when (file-writable-p file)
1315               (gnus-write-buffer file)
1316               (when gnus-score-after-write-file-function
1317                 (funcall gnus-score-after-write-file-function file)))))
1318         (and gnus-score-uncacheable-files
1319              (string-match gnus-score-uncacheable-files file)
1320              (gnus-score-remove-from-cache file)))
1321       (kill-buffer (current-buffer)))))
1322
1323 (defun gnus-score-load-files (score-files)
1324   "Load all score files in SCORE-FILES."
1325   ;; Load the score files.
1326   (let (scores)
1327     (while score-files
1328       (if (stringp (car score-files))
1329           ;; It is a string, which means that it's a score file name,
1330           ;; so we load the score file and add the score alist to
1331           ;; the list of alists.
1332           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1333         ;; It is an alist, so we just add it to the list directly.
1334         (setq scores (nconc (car score-files) scores)))
1335       (setq score-files (cdr score-files)))
1336     ;; Prune the score files that are to be excluded, if any.
1337     (when gnus-scores-exclude-files
1338       (let ((s scores)
1339             c)
1340         (while s
1341           (and (setq c (rassq (car s) gnus-score-cache))
1342                (member (car c) gnus-scores-exclude-files)
1343                (setq scores (delq (car s) scores)))
1344           (setq s (cdr s)))))
1345     scores))
1346
1347 (defun gnus-score-headers (score-files &optional trace)
1348   ;; Score `gnus-newsgroup-headers'.
1349   (let (scores news)
1350     ;; PLM: probably this is not the best place to clear orphan-score
1351     (setq gnus-orphan-score nil
1352           gnus-scores-articles nil
1353           gnus-scores-exclude-files nil
1354           scores (gnus-score-load-files score-files))
1355     (setq news scores)
1356     ;; Do the scoring.
1357     (while news
1358       (setq scores news
1359             news nil)
1360       (when (and gnus-summary-default-score
1361                  scores)
1362         (let* ((entries gnus-header-index)
1363                (now (gnus-day-number (current-time-string)))
1364                (expire (and gnus-score-expiry-days
1365                             (- now gnus-score-expiry-days)))
1366                (headers gnus-newsgroup-headers)
1367                (current-score-file gnus-current-score-file)
1368                entry header new)
1369           (gnus-message 5 "Scoring...")
1370           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1371           (while (setq header (pop headers))
1372             ;; WARNING: The assq makes the function O(N*S) while it could
1373             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1374             ;; and S is (length gnus-newsgroup-scored).
1375             (unless (assq (mail-header-number header) gnus-newsgroup-scored)
1376               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1377                     (cons (cons header (or gnus-summary-default-score 0))
1378                           gnus-scores-articles))))
1379
1380           (save-excursion
1381             (set-buffer (get-buffer-create "*Headers*"))
1382             (buffer-disable-undo (current-buffer))
1383             (when (gnus-buffer-live-p gnus-summary-buffer)
1384               (message-clone-locals gnus-summary-buffer))
1385
1386             ;; Set the global variant of this variable.
1387             (setq gnus-current-score-file current-score-file)
1388             ;; score orphans
1389             (when gnus-orphan-score
1390               (setq gnus-score-index
1391                     (nth 1 (assoc "references" gnus-header-index)))
1392               (gnus-score-orphans gnus-orphan-score))
1393             ;; Run each header through the score process.
1394             (while entries
1395               (setq entry (pop entries)
1396                     header (nth 0 entry)
1397                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1398               (when (< 0 (apply 'max (mapcar
1399                                       (lambda (score)
1400                                         (length (gnus-score-get header score)))
1401                                       scores)))
1402                 ;; Call the scoring function for this type of "header".
1403                 (when (setq new (funcall (nth 2 entry) scores header
1404                                          now expire trace))
1405                   (push new news))))
1406             ;; Remove the buffer.
1407             (kill-buffer (current-buffer)))
1408
1409           ;; Add articles to `gnus-newsgroup-scored'.
1410           (while gnus-scores-articles
1411             (when (or (/= gnus-summary-default-score
1412                           (cdar gnus-scores-articles))
1413                       gnus-save-score)
1414               (push (cons (mail-header-number (caar gnus-scores-articles))
1415                           (cdar gnus-scores-articles))
1416                     gnus-newsgroup-scored))
1417             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1418
1419           (let (score)
1420             (while (setq score (pop scores))
1421               (while score
1422                 (when (listp (caar score))
1423                   (gnus-score-advanced (car score) trace))
1424                 (pop score))))
1425
1426           (gnus-message 5 "Scoring...done"))))))
1427
1428
1429 (defun gnus-get-new-thread-ids (articles)
1430   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
1431         (refind gnus-score-index)
1432         id-list art this tref)
1433     (while articles
1434       (setq art (car articles)
1435             this (aref (car art) index)
1436             tref (aref (car art) refind)
1437             articles (cdr articles))
1438       (when (string-equal tref "")      ;no references line
1439         (push this id-list)))
1440     id-list))
1441
1442 ;; Orphan functions written by plm@atcmp.nl (Peter Mutsaers).
1443 (defun gnus-score-orphans (score)
1444   (let ((new-thread-ids (gnus-get-new-thread-ids gnus-scores-articles))
1445         alike articles art arts this last this-id)
1446
1447     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1448           articles gnus-scores-articles)
1449
1450     ;;more or less the same as in gnus-score-string
1451     (erase-buffer)
1452     (while articles
1453       (setq art (car articles)
1454             this (aref (car art) gnus-score-index)
1455             articles (cdr articles))
1456       ;;completely skip if this is empty (not a child, so not an orphan)
1457       (when (not (string= this ""))
1458         (if (equal last this)
1459             ;; O(N*H) cons-cells used here, where H is the number of
1460             ;; headers.
1461             (push art alike)
1462           (when last
1463             ;; Insert the line, with a text property on the
1464             ;; terminating newline referring to the articles with
1465             ;; this line.
1466             (insert last ?\n)
1467             (put-text-property (1- (point)) (point) 'articles alike))
1468           (setq alike (list art)
1469                 last this))))
1470     (when last                          ; Bwadr, duplicate code.
1471       (insert last ?\n)
1472       (put-text-property (1- (point)) (point) 'articles alike))
1473
1474     ;; PLM: now delete those lines that contain an entry from new-thread-ids
1475     (while new-thread-ids
1476       (setq this-id (car new-thread-ids)
1477             new-thread-ids (cdr new-thread-ids))
1478       (goto-char (point-min))
1479       (while (search-forward this-id nil t)
1480         ;; found a match.  remove this line
1481         (beginning-of-line)
1482         (kill-line 1)))
1483
1484     ;; now for each line: update its articles with score by moving to
1485     ;; every end-of-line in the buffer and read the articles property
1486     (goto-char (point-min))
1487     (while (eq 0 (progn
1488                    (end-of-line)
1489                    (setq arts (get-text-property (point) 'articles))
1490                    (while arts
1491                      (setq art (car arts)
1492                            arts (cdr arts))
1493                      (setcdr art (+ score (cdr art))))
1494                    (forward-line))))))
1495
1496
1497 (defun gnus-score-integer (scores header now expire &optional trace)
1498   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1499         entries alist)
1500
1501     ;; Find matches.
1502     (while scores
1503       (setq alist (car scores)
1504             scores (cdr scores)
1505             entries (assoc header alist))
1506       (while (cdr entries)              ;First entry is the header index.
1507         (let* ((rest (cdr entries))
1508                (kill (car rest))
1509                (match (nth 0 kill))
1510                (type (or (nth 3 kill) '>))
1511                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1512                (date (nth 2 kill))
1513                (found nil)
1514                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1515                                    (eq type '>=) (eq type '=))
1516                                type
1517                              (error "Illegal match type: %s" type)))
1518                (articles gnus-scores-articles))
1519           ;; Instead of doing all the clever stuff that
1520           ;; `gnus-score-string' does to minimize searches and stuff,
1521           ;; I will assume that people generally will put so few
1522           ;; matches on numbers that any cleverness will take more
1523           ;; time than one would gain.
1524           (while articles
1525             (when (funcall match-func
1526                            (or (aref (caar articles) gnus-score-index) 0)
1527                            match)
1528               (when trace
1529                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1530                       gnus-score-trace))
1531               (setq found t)
1532               (setcdr (car articles) (+ score (cdar articles))))
1533             (setq articles (cdr articles)))
1534           ;; Update expire date
1535           (cond ((null date))           ;Permanent entry.
1536                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1537                  (gnus-score-set 'touched '(t) alist)
1538                  (setcar (nthcdr 2 kill) now))
1539                 ((and expire (< date expire)) ;Old entry, remove.
1540                  (gnus-score-set 'touched '(t) alist)
1541                  (setcdr entries (cdr rest))
1542                  (setq rest entries)))
1543           (setq entries rest)))))
1544   nil)
1545
1546 (defun gnus-score-date (scores header now expire &optional trace)
1547   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1548         entries alist match match-func article)
1549
1550     ;; Find matches.
1551     (while scores
1552       (setq alist (car scores)
1553             scores (cdr scores)
1554             entries (assoc header alist))
1555       (while (cdr entries)              ;First entry is the header index.
1556         (let* ((rest (cdr entries))
1557                (kill (car rest))
1558                (type (or (nth 3 kill) 'before))
1559                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1560                (date (nth 2 kill))
1561                (found nil)
1562                (articles gnus-scores-articles)
1563                l)
1564           (cond
1565            ((eq type 'after)
1566             (setq match-func 'string<
1567                   match (gnus-date-iso8601 (nth 0 kill))))
1568            ((eq type 'before)
1569             (setq match-func 'gnus-string>
1570                   match (gnus-date-iso8601 (nth 0 kill))))
1571            ((eq type 'at)
1572             (setq match-func 'string=
1573                   match (gnus-date-iso8601 (nth 0 kill))))
1574            ((eq type 'regexp)
1575             (setq match-func 'string-match
1576                   match (nth 0 kill)))
1577            (t (error "Illegal match type: %s" type)))
1578           ;; Instead of doing all the clever stuff that
1579           ;; `gnus-score-string' does to minimize searches and stuff,
1580           ;; I will assume that people generally will put so few
1581           ;; matches on numbers that any cleverness will take more
1582           ;; time than one would gain.
1583           (while (setq article (pop articles))
1584             (when (and
1585                    (setq l (aref (car article) gnus-score-index))
1586                    (funcall match-func match (gnus-date-iso8601 l)))
1587               (when trace
1588                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1589                       gnus-score-trace))
1590               (setq found t)
1591               (setcdr article (+ score (cdr article)))))
1592           ;; Update expire date
1593           (cond ((null date))           ;Permanent entry.
1594                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1595                  (gnus-score-set 'touched '(t) alist)
1596                  (setcar (nthcdr 2 kill) now))
1597                 ((and expire (< date expire)) ;Old entry, remove.
1598                  (gnus-score-set 'touched '(t) alist)
1599                  (setcdr entries (cdr rest))
1600                  (setq rest entries)))
1601           (setq entries rest)))))
1602   nil)
1603
1604 (defun gnus-score-body (scores header now expire &optional trace)
1605   (save-excursion
1606     (setq gnus-scores-articles
1607           (sort gnus-scores-articles
1608                 (lambda (a1 a2)
1609                   (< (mail-header-number (car a1))
1610                      (mail-header-number (car a2))))))
1611     (set-buffer nntp-server-buffer)
1612     (save-restriction
1613       (let* ((buffer-read-only nil)
1614              (articles gnus-scores-articles)
1615              (all-scores scores)
1616              (request-func (cond ((string= "head" header)
1617                                   'gnus-request-head)
1618                                  ((string= "body" header)
1619                                   'gnus-request-body)
1620                                  (t 'gnus-request-article)))
1621              entries alist ofunc article last)
1622         (when articles
1623           (setq last (mail-header-number (caar (last articles))))
1624           ;; Not all backends support partial fetching.  In that case,
1625           ;; we just fetch the entire article.
1626           (unless (gnus-check-backend-function
1627                    (and (string-match "^gnus-" (symbol-name request-func))
1628                         (intern (substring (symbol-name request-func)
1629                                            (match-end 0))))
1630                    gnus-newsgroup-name)
1631             (setq ofunc request-func)
1632             (setq request-func 'gnus-request-article))
1633           (while articles
1634             (setq article (mail-header-number (caar articles)))
1635             (gnus-message 7 "Scoring on article %s of %s..." article last)
1636             (when (funcall request-func article gnus-newsgroup-name)
1637               (widen)
1638               (goto-char (point-min))
1639               ;; If just parts of the article is to be searched, but the
1640               ;; backend didn't support partial fetching, we just narrow
1641               ;; to the relevant parts.
1642               (when ofunc
1643                 (if (eq ofunc 'gnus-request-head)
1644                     (narrow-to-region
1645                      (point)
1646                      (or (search-forward "\n\n" nil t) (point-max)))
1647                   (narrow-to-region
1648                    (or (search-forward "\n\n" nil t) (point))
1649                    (point-max))))
1650               (setq scores all-scores)
1651               ;; Find matches.
1652               (while scores
1653                 (setq alist (pop scores)
1654                       entries (assoc header alist))
1655                 (while (cdr entries)    ;First entry is the header index.
1656                   (let* ((rest (cdr entries))
1657                          (kill (car rest))
1658                          (match (nth 0 kill))
1659                          (type (or (nth 3 kill) 's))
1660                          (score (or (nth 1 kill)
1661                                     gnus-score-interactive-default-score))
1662                          (date (nth 2 kill))
1663                          (found nil)
1664                          (case-fold-search
1665                           (not (or (eq type 'R) (eq type 'S)
1666                                    (eq type 'Regexp) (eq type 'String))))
1667                          (search-func
1668                           (cond ((or (eq type 'r) (eq type 'R)
1669                                      (eq type 'regexp) (eq type 'Regexp))
1670                                  're-search-forward)
1671                                 ((or (eq type 's) (eq type 'S)
1672                                      (eq type 'string) (eq type 'String))
1673                                  'search-forward)
1674                                 (t
1675                                  (error "Illegal match type: %s" type)))))
1676                     (goto-char (point-min))
1677                     (when (funcall search-func match nil t)
1678                       ;; Found a match, update scores.
1679                       (setcdr (car articles) (+ score (cdar articles)))
1680                       (setq found t)
1681                       (when trace
1682                         (push
1683                          (cons (car-safe (rassq alist gnus-score-cache)) kill)
1684                          gnus-score-trace)))
1685                     ;; Update expire date
1686                     (unless trace
1687                       (cond
1688                        ((null date))    ;Permanent entry.
1689                        ((and found gnus-update-score-entry-dates)
1690                         ;; Match, update date.
1691                         (gnus-score-set 'touched '(t) alist)
1692                         (setcar (nthcdr 2 kill) now))
1693                        ((and expire (< date expire)) ;Old entry, remove.
1694                         (gnus-score-set 'touched '(t) alist)
1695                         (setcdr entries (cdr rest))
1696                         (setq rest entries))))
1697                     (setq entries rest)))))
1698             (setq articles (cdr articles)))))))
1699   nil)
1700
1701 (defun gnus-score-thread (scores header now expire &optional trace)
1702   (gnus-score-followup scores header now expire trace t))
1703
1704 (defun gnus-score-followup (scores header now expire &optional trace thread)
1705   ;; Insert the unique article headers in the buffer.
1706   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1707         (current-score-file gnus-current-score-file)
1708         (all-scores scores)
1709         ;; gnus-score-index is used as a free variable.
1710         alike last this art entries alist articles
1711         new news)
1712
1713     ;; Change score file to the adaptive score file.  All entries that
1714     ;; this function makes will be put into this file.
1715     (save-excursion
1716       (set-buffer gnus-summary-buffer)
1717       (gnus-score-load-file
1718        (or gnus-newsgroup-adaptive-score-file
1719            (gnus-score-file-name
1720             gnus-newsgroup-name gnus-adaptive-file-suffix))))
1721
1722     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1723           articles gnus-scores-articles)
1724
1725     (erase-buffer)
1726     (while articles
1727       (setq art (car articles)
1728             this (aref (car art) gnus-score-index)
1729             articles (cdr articles))
1730       (if (equal last this)
1731           (push art alike)
1732         (when last
1733           (insert last ?\n)
1734           (put-text-property (1- (point)) (point) 'articles alike))
1735         (setq alike (list art)
1736               last this)))
1737     (when last                          ; Bwadr, duplicate code.
1738       (insert last ?\n)
1739       (put-text-property (1- (point)) (point) 'articles alike))
1740
1741     ;; Find matches.
1742     (while scores
1743       (setq alist (car scores)
1744             scores (cdr scores)
1745             entries (assoc header alist))
1746       (while (cdr entries)              ;First entry is the header index.
1747         (let* ((rest (cdr entries))
1748                (kill (car rest))
1749                (match (nth 0 kill))
1750                (type (or (nth 3 kill) 's))
1751                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1752                (date (nth 2 kill))
1753                (found nil)
1754                (mt (aref (symbol-name type) 0))
1755                (case-fold-search
1756                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1757                (dmt (downcase mt))
1758                (search-func
1759                 (cond ((= dmt ?r) 're-search-forward)
1760                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1761                       (t (error "Illegal match type: %s" type))))
1762                arts art)
1763           (goto-char (point-min))
1764           (if (= dmt ?e)
1765               (while (funcall search-func match nil t)
1766                 (and (= (progn (beginning-of-line) (point))
1767                         (match-beginning 0))
1768                      (= (progn (end-of-line) (point))
1769                         (match-end 0))
1770                      (progn
1771                        (setq found (setq arts (get-text-property
1772                                                (point) 'articles)))
1773                        ;; Found a match, update scores.
1774                        (while arts
1775                          (setq art (car arts)
1776                                arts (cdr arts))
1777                          (gnus-score-add-followups
1778                           (car art) score all-scores thread))))
1779                 (end-of-line))
1780             (while (funcall search-func match nil t)
1781               (end-of-line)
1782               (setq found (setq arts (get-text-property (point) 'articles)))
1783               ;; Found a match, update scores.
1784               (while (setq art (pop arts))
1785                 (when (setq new (gnus-score-add-followups
1786                                  (car art) score all-scores thread))
1787                   (push new news)))))
1788           ;; Update expire date
1789           (cond ((null date))           ;Permanent entry.
1790                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1791                  (gnus-score-set 'touched '(t) alist)
1792                  (setcar (nthcdr 2 kill) now))
1793                 ((and expire (< date expire)) ;Old entry, remove.
1794                  (gnus-score-set 'touched '(t) alist)
1795                  (setcdr entries (cdr rest))
1796                  (setq rest entries)))
1797           (setq entries rest))))
1798     ;; We change the score file back to the previous one.
1799     (save-excursion
1800       (set-buffer gnus-summary-buffer)
1801       (gnus-score-load-file current-score-file))
1802     (list (cons "references" news))))
1803
1804 (defun gnus-score-add-followups (header score scores &optional thread)
1805   "Add a score entry to the adapt file."
1806   (save-excursion
1807     (set-buffer gnus-summary-buffer)
1808     (let* ((id (mail-header-id header))
1809            (scores (car scores))
1810            entry dont)
1811       ;; Don't enter a score if there already is one.
1812       (while (setq entry (pop scores))
1813         (and (equal "references" (car entry))
1814              (or (null (nth 3 (cadr entry)))
1815                  (eq 's (nth 3 (cadr entry))))
1816              (assoc id entry)
1817              (setq dont t)))
1818       (unless dont
1819         (gnus-summary-score-entry
1820          (if thread "thread" "references")
1821          id 's score (current-time-string) nil t)))))
1822
1823 (defun gnus-score-string (score-list header now expire &optional trace)
1824   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1825   ;; Update matching entries to NOW and remove unmatched entries older
1826   ;; than EXPIRE.
1827
1828   ;; Insert the unique article headers in the buffer.
1829   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1830         ;; gnus-score-index is used as a free variable.
1831         alike last this art entries alist articles
1832         fuzzies arts words kill)
1833
1834     ;; Sorting the articles costs os O(N*log N) but will allow us to
1835     ;; only match with each unique header.  Thus the actual matching
1836     ;; will be O(M*U) where M is the number of strings to match with,
1837     ;; and U is the number of unique headers.  It is assumed (but
1838     ;; untested) this will be a net win because of the large constant
1839     ;; factor involved with string matching.
1840     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1841           articles gnus-scores-articles)
1842
1843     (erase-buffer)
1844     (while (setq art (pop articles))
1845       (setq this (aref (car art) gnus-score-index))
1846       (if (equal last this)
1847           ;; O(N*H) cons-cells used here, where H is the number of
1848           ;; headers.
1849           (push art alike)
1850         (when last
1851           ;; Insert the line, with a text property on the
1852           ;; terminating newline referring to the articles with
1853           ;; this line.
1854           (insert last ?\n)
1855           (put-text-property (1- (point)) (point) 'articles alike))
1856         (setq alike (list art)
1857               last this)))
1858     (when last                          ; Bwadr, duplicate code.
1859       (insert last ?\n)
1860       (put-text-property (1- (point)) (point) 'articles alike))
1861
1862     ;; Go through all the score alists and pick out the entries
1863     ;; for this header.
1864     (while score-list
1865       (setq alist (pop score-list)
1866             ;; There's only one instance of this header for
1867             ;; each score alist.
1868             entries (assoc header alist))
1869       (while (cdr entries)              ;First entry is the header index.
1870         (let* ((kill (cadr entries))
1871                (match (nth 0 kill))
1872                (type (or (nth 3 kill) 's))
1873                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1874                (date (nth 2 kill))
1875                (found nil)
1876                (mt (aref (symbol-name type) 0))
1877                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
1878                (dmt (downcase mt))
1879                (search-func
1880                 (cond ((= dmt ?r) 're-search-forward)
1881                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1882                       ((= dmt ?w) nil)
1883                       (t (error "Illegal match type: %s" type)))))
1884           (cond
1885            ;; Fuzzy matches.  We save these for later.
1886            ((= dmt ?f)
1887             (push (cons entries alist) fuzzies))
1888            ;; Word matches.  Save these for even later.
1889            ((= dmt ?w)
1890             (push (cons entries alist) words))
1891            ;; Exact matches.
1892            ((= dmt ?e)
1893             ;; Do exact matching.
1894             (goto-char (point-min))
1895             (while (and (not (eobp))
1896                         (funcall search-func match nil t))
1897               ;; Is it really exact?
1898               (and (eolp)
1899                    (= (gnus-point-at-bol) (match-beginning 0))
1900                    ;; Yup.
1901                    (progn
1902                      (setq found (setq arts (get-text-property
1903                                              (point) 'articles)))
1904                      ;; Found a match, update scores.
1905                      (if trace
1906                          (while (setq art (pop arts))
1907                            (setcdr art (+ score (cdr art)))
1908                            (push
1909                             (cons
1910                              (car-safe (rassq alist gnus-score-cache))
1911                              kill)
1912                             gnus-score-trace))
1913                        (while (setq art (pop arts))
1914                          (setcdr art (+ score (cdr art)))))))
1915               (forward-line 1)))
1916            ;; Regexp and substring matching.
1917            (t
1918             (goto-char (point-min))
1919             (when (string= match "")
1920               (setq match "\n"))
1921             (while (and (not (eobp))
1922                         (funcall search-func match nil t))
1923               (goto-char (match-beginning 0))
1924               (end-of-line)
1925               (setq found (setq arts (get-text-property (point) 'articles)))
1926               ;; Found a match, update scores.
1927               (if trace
1928                   (while (setq art (pop arts))
1929                     (setcdr art (+ score (cdr art)))
1930                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1931                           gnus-score-trace))
1932                 (while (setq art (pop arts))
1933                   (setcdr art (+ score (cdr art)))))
1934               (forward-line 1))))
1935           ;; Update expiry date
1936           (if trace
1937               (setq entries (cdr entries))
1938             (cond
1939              ;; Permanent entry.
1940              ((null date)
1941               (setq entries (cdr entries)))
1942              ;; We have a match, so we update the date.
1943              ((and found gnus-update-score-entry-dates)
1944               (gnus-score-set 'touched '(t) alist)
1945               (setcar (nthcdr 2 kill) now)
1946               (setq entries (cdr entries)))
1947              ;; This entry has expired, so we remove it.
1948              ((and expire (< date expire))
1949               (gnus-score-set 'touched '(t) alist)
1950               (setcdr entries (cddr entries)))
1951              ;; No match; go to next entry.
1952              (t
1953               (setq entries (cdr entries))))))))
1954
1955     ;; Find fuzzy matches.
1956     (when fuzzies
1957       ;; Simplify the entire buffer for easy matching.
1958       (gnus-simplify-buffer-fuzzy)
1959       (while (setq kill (cadaar fuzzies))
1960         (let* ((match (nth 0 kill))
1961                (type (nth 3 kill))
1962                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1963                (date (nth 2 kill))
1964                (mt (aref (symbol-name type) 0))
1965                (case-fold-search (not (= mt ?F)))
1966                found)
1967           (goto-char (point-min))
1968           (while (and (not (eobp))
1969                       (search-forward match nil t))
1970             (when (and (= (gnus-point-at-bol) (match-beginning 0))
1971                        (eolp))
1972               (setq found (setq arts (get-text-property (point) 'articles)))
1973               (if trace
1974                   (while (setq art (pop arts))
1975                     (setcdr art (+ score (cdr art)))
1976                     (push (cons
1977                            (car-safe (rassq (cdar fuzzies) gnus-score-cache))
1978                            kill)
1979                           gnus-score-trace))
1980                 ;; Found a match, update scores.
1981                 (while (setq art (pop arts))
1982                   (setcdr art (+ score (cdr art))))))
1983             (forward-line 1))
1984           ;; Update expiry date
1985           (cond
1986            ;; Permanent.
1987            ((null date)
1988             )
1989            ;; Match, update date.
1990            ((and found gnus-update-score-entry-dates)
1991             (gnus-score-set 'touched '(t) (cdar fuzzies))
1992             (setcar (nthcdr 2 kill) now))
1993            ;; Old entry, remove.
1994            ((and expire (< date expire))
1995             (gnus-score-set 'touched '(t) (cdar fuzzies))
1996             (setcdr (caar fuzzies) (cddaar fuzzies))))
1997           (setq fuzzies (cdr fuzzies)))))
1998
1999     (when words
2000       ;; Enter all words into the hashtb.
2001       (let ((hashtb (gnus-make-hashtable
2002                      (* 10 (count-lines (point-min) (point-max))))))
2003         (gnus-enter-score-words-into-hashtb hashtb)
2004         (while (setq kill (cadaar words))
2005           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
2006                  (date (nth 2 kill))
2007                  found)
2008             (when (setq arts (intern-soft (nth 0 kill) hashtb))
2009               (setq arts (symbol-value arts))
2010               (setq found t)
2011               (if trace
2012                   (while (setq art (pop arts))
2013                     (setcdr art (+ score (cdr art)))
2014                     (push (cons
2015                            (car-safe (rassq (cdar words) gnus-score-cache))
2016                            kill)
2017                           gnus-score-trace))
2018                 ;; Found a match, update scores.
2019                 (while (setq art (pop arts))
2020                   (setcdr art (+ score (cdr art))))))
2021             ;; Update expiry date
2022             (cond
2023              ;; Permanent.
2024              ((null date)
2025               )
2026              ;; Match, update date.
2027              ((and found gnus-update-score-entry-dates)
2028               (gnus-score-set 'touched '(t) (cdar words))
2029               (setcar (nthcdr 2 kill) now))
2030              ;; Old entry, remove.
2031              ((and expire (< date expire))
2032               (gnus-score-set 'touched '(t) (cdar words))
2033               (setcdr (caar words) (cddaar words))))
2034             (setq words (cdr words))))))
2035     nil))
2036
2037 (defun gnus-enter-score-words-into-hashtb (hashtb)
2038   ;; Find all the words in the buffer and enter them into
2039   ;; the hashtable.
2040   (let ((syntab (syntax-table))
2041         word val)
2042     (goto-char (point-min))
2043     (unwind-protect
2044         (progn
2045           (set-syntax-table gnus-adaptive-word-syntax-table)
2046           (while (re-search-forward "\\b\\w+\\b" nil t)
2047             (setq val
2048                   (gnus-gethash
2049                    (setq word (downcase (buffer-substring
2050                                          (match-beginning 0) (match-end 0))))
2051                    hashtb))
2052             (gnus-sethash
2053              word
2054              (append (get-text-property (gnus-point-at-eol) 'articles) val)
2055              hashtb)))
2056       (set-syntax-table syntab))
2057     ;; Make all the ignorable words ignored.
2058     (let ((ignored (append gnus-ignored-adaptive-words
2059                            gnus-default-ignored-adaptive-words)))
2060       (while ignored
2061         (gnus-sethash (pop ignored) nil hashtb)))))
2062
2063 (defun gnus-score-string< (a1 a2)
2064   ;; Compare headers in articles A2 and A2.
2065   ;; The header index used is the free variable `gnus-score-index'.
2066   (string-lessp (aref (car a1) gnus-score-index)
2067                 (aref (car a2) gnus-score-index)))
2068
2069 (defun gnus-current-score-file-nondirectory (&optional score-file)
2070   (let ((score-file (or score-file gnus-current-score-file)))
2071     (if score-file
2072         (gnus-short-group-name (file-name-nondirectory score-file))
2073       "none")))
2074
2075 (defun gnus-score-adaptive ()
2076   "Create adaptive score rules for this newsgroup."
2077   (when gnus-newsgroup-adaptive
2078     ;; We change the score file to the adaptive score file.
2079     (save-excursion
2080       (set-buffer gnus-summary-buffer)
2081       (gnus-score-load-file
2082        (or gnus-newsgroup-adaptive-score-file
2083            (gnus-home-score-file gnus-newsgroup-name t)
2084            (gnus-score-file-name
2085             gnus-newsgroup-name gnus-adaptive-file-suffix))))
2086     ;; Perform ordinary line scoring.
2087     (when (or (not (listp gnus-newsgroup-adaptive))
2088               (memq 'line gnus-newsgroup-adaptive))
2089       (save-excursion
2090         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
2091                (alist malist)
2092                (date (current-time-string))
2093                (data gnus-newsgroup-data)
2094                elem headers match func)
2095           ;; First we transform the adaptive rule alist into something
2096           ;; that's faster to process.
2097           (while malist
2098             (setq elem (car malist))
2099             (when (symbolp (car elem))
2100               (setcar elem (symbol-value (car elem))))
2101             (setq elem (cdr elem))
2102             (while elem
2103               (when (fboundp
2104                      (setq func
2105                            (intern
2106                             (concat "mail-header-"
2107                                     (if (eq (caar elem) 'followup)
2108                                         "message-id"
2109                                       (downcase (symbol-name (caar elem))))))))
2110                 (setcdr (car elem)
2111                         (cons (if (eq (caar elem) 'followup)
2112                                   "references"
2113                                 (symbol-name (caar elem)))
2114                               (cdar elem)))
2115                 (setcar (car elem)
2116                         `(lambda (h)
2117                            (,func h))))
2118               (setq elem (cdr elem)))
2119             (setq malist (cdr malist)))
2120           ;; Then we score away.
2121           (while data
2122             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2123             (if (or (not elem)
2124                     (gnus-data-pseudo-p (car data)))
2125                 ()
2126               (when (setq headers (gnus-data-header (car data)))
2127                 (while elem
2128                   (setq match (funcall (caar elem) headers))
2129                   (gnus-summary-score-entry
2130                    (nth 1 (car elem)) match
2131                    (cond
2132                     ((numberp match)
2133                      '=)
2134                     ((equal (nth 1 (car elem)) "date")
2135                      'a)
2136                     (t
2137                      ;; Whether we use substring or exact matches is
2138                      ;; controlled here.
2139                      (if (or (not gnus-score-exact-adapt-limit)
2140                              (< (length match) gnus-score-exact-adapt-limit))
2141                          'e
2142                        (if (equal (nth 1 (car elem)) "subject")
2143                            'f 's))))
2144                    (nth 2 (car elem)) date nil t)
2145                   (setq elem (cdr elem)))))
2146             (setq data (cdr data))))))
2147
2148     ;; Perform adaptive word scoring.
2149     (when (and (listp gnus-newsgroup-adaptive)
2150                (memq 'word gnus-newsgroup-adaptive))
2151       (nnheader-temp-write nil
2152         (let* ((hashtb (gnus-make-hashtable 1000))
2153                (date (gnus-day-number (current-time-string)))
2154                (data gnus-newsgroup-data)
2155                (syntab (syntax-table))
2156                word d score val)
2157           (unwind-protect
2158               (progn
2159                 (set-syntax-table gnus-adaptive-word-syntax-table)
2160                 ;; Go through all articles.
2161                 (while (setq d (pop data))
2162                   (when (and
2163                          (not (gnus-data-pseudo-p d))
2164                          (setq score
2165                                (cdr (assq
2166                                      (gnus-data-mark d)
2167                                      gnus-adaptive-word-score-alist))))
2168                     ;; This article has a mark that should lead to
2169                     ;; adaptive word rules, so we insert the subject
2170                     ;; and find all words in that string.
2171                     (insert (mail-header-subject (gnus-data-header d)))
2172                     (downcase-region (point-min) (point-max))
2173                     (goto-char (point-min))
2174                     (while (re-search-forward "\\b\\w+\\b" nil t)
2175                       ;; Put the word and score into the hashtb.
2176                       (setq val (gnus-gethash (setq word (match-string 0))
2177                                               hashtb))
2178                       (setq val (+ score (or val 0)))
2179                       (if (and gnus-adaptive-word-minimum
2180                                (< val gnus-adaptive-word-minimum))
2181                           (setq val gnus-adaptive-word-minimum))
2182                       (gnus-sethash word val hashtb))
2183                     (erase-buffer))))
2184             (set-syntax-table syntab))
2185           ;; Make all the ignorable words ignored.
2186           (let ((ignored (append gnus-ignored-adaptive-words
2187                                  gnus-default-ignored-adaptive-words)))
2188             (while ignored
2189               (gnus-sethash (pop ignored) nil hashtb)))
2190           ;; Now we have all the words and scores, so we
2191           ;; add these rules to the ADAPT file.
2192           (set-buffer gnus-summary-buffer)
2193           (mapatoms
2194            (lambda (word)
2195              (when (symbol-value word)
2196                (gnus-summary-score-entry
2197                 "subject" (symbol-name word) 'w (symbol-value word)
2198                 date nil t)))
2199            hashtb))))))
2200
2201 (defun gnus-score-edit-done ()
2202   (let ((bufnam (buffer-file-name (current-buffer)))
2203         (winconf gnus-prev-winconf))
2204     (when winconf
2205       (set-window-configuration winconf))
2206     (gnus-score-remove-from-cache bufnam)
2207     (gnus-score-load-file bufnam)))
2208
2209 (defun gnus-score-find-trace ()
2210   "Find all score rules that applies to the current article."
2211   (interactive)
2212   (let ((old-scored gnus-newsgroup-scored))
2213     (let ((gnus-newsgroup-headers
2214            (list (gnus-summary-article-header)))
2215           (gnus-newsgroup-scored nil)
2216           trace)
2217       (save-excursion
2218         (nnheader-set-temp-buffer "*Score Trace*"))
2219       (setq gnus-score-trace nil)
2220       (gnus-possibly-score-headers 'trace)
2221       (if (not (setq trace gnus-score-trace))
2222           (gnus-error
2223            1 "No score rules apply to the current article (default score %d)."
2224            gnus-summary-default-score)
2225         (set-buffer "*Score Trace*")
2226         (gnus-add-current-to-buffer-list)
2227         (while trace
2228           (insert (format "%S  ->  %s\n" (cdar trace)
2229                           (if (caar trace)
2230                               (file-name-nondirectory (caar trace))
2231                             "(non-file rule)")))
2232           (setq trace (cdr trace)))
2233         (goto-char (point-min))
2234         (gnus-configure-windows 'score-trace)))
2235     (set-buffer gnus-summary-buffer)
2236     (setq gnus-newsgroup-scored old-scored)))
2237
2238 (defun gnus-score-find-favourite-words ()
2239   "List words used in scoring."
2240   (interactive)
2241   (let ((alists (gnus-score-load-files (gnus-all-score-files)))
2242         alist rule rules kill)
2243     ;; Go through all the score alists for this group
2244     ;; and find all `w' rules.
2245     (while (setq alist (pop alists))
2246       (while (setq rule (pop alist))
2247         (when (and (stringp (car rule))
2248                    (equal "subject" (downcase (pop rule))))
2249           (while (setq kill (pop rule))
2250             (when (memq (nth 3 kill) '(w W word Word))
2251               (push (cons (or (nth 1 kill)
2252                               gnus-score-interactive-default-score)
2253                           (car kill))
2254                     rules))))))
2255     (setq rules (sort rules (lambda (r1 r2)
2256                               (string-lessp (cdr r1) (cdr r2)))))
2257     ;; Add up words that have appeared several times.
2258     (let ((r rules))
2259       (while (cdr r)
2260         (if (equal (cdar r) (cdadr r))
2261             (progn
2262               (setcar (car r) (+ (caar r) (caadr r)))
2263               (setcdr r (cddr r)))
2264           (pop r))))
2265     ;; Insert the words.
2266     (nnheader-set-temp-buffer "*Score Words*")
2267     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2268         (gnus-error 3 "No word score rules")
2269       (while rules
2270         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2271         (pop rules))
2272       (gnus-add-current-to-buffer-list)
2273       (goto-char (point-min))
2274       (gnus-configure-windows 'score-words))))
2275
2276 (defun gnus-summary-rescore ()
2277   "Redo the entire scoring process in the current summary."
2278   (interactive)
2279   (gnus-score-save)
2280   (setq gnus-score-cache nil)
2281   (setq gnus-newsgroup-scored nil)
2282   (gnus-possibly-score-headers)
2283   (gnus-score-update-all-lines))
2284
2285 (defun gnus-score-flush-cache ()
2286   "Flush the cache of score files."
2287   (interactive)
2288   (gnus-score-save)
2289   (setq gnus-score-cache nil
2290         gnus-score-alist nil
2291         gnus-short-name-score-file-cache nil)
2292   (gnus-message 6 "The score cache is now flushed"))
2293
2294 (gnus-add-shutdown 'gnus-score-close 'gnus)
2295
2296 (defvar gnus-score-file-alist-cache nil)
2297
2298 (defun gnus-score-close ()
2299   "Clear all internal score variables."
2300   (setq gnus-score-cache nil
2301         gnus-internal-global-score-files nil
2302         gnus-score-file-list nil
2303         gnus-score-file-alist-cache nil))
2304
2305 ;; Summary score marking commands.
2306
2307 (defun gnus-summary-raise-same-subject-and-select (score)
2308   "Raise articles which has the same subject with SCORE and select the next."
2309   (interactive "p")
2310   (let ((subject (gnus-summary-article-subject)))
2311     (gnus-summary-raise-score score)
2312     (while (gnus-summary-find-subject subject)
2313       (gnus-summary-raise-score score))
2314     (gnus-summary-next-article t)))
2315
2316 (defun gnus-summary-raise-same-subject (score)
2317   "Raise articles which has the same subject with SCORE."
2318   (interactive "p")
2319   (let ((subject (gnus-summary-article-subject)))
2320     (gnus-summary-raise-score score)
2321     (while (gnus-summary-find-subject subject)
2322       (gnus-summary-raise-score score))
2323     (gnus-summary-next-subject 1 t)))
2324
2325 (defun gnus-score-default (level)
2326   (if level (prefix-numeric-value level)
2327     gnus-score-interactive-default-score))
2328
2329 (defun gnus-summary-raise-thread (&optional score)
2330   "Raise the score of the articles in the current thread with SCORE."
2331   (interactive "P")
2332   (setq score (gnus-score-default score))
2333   (let (e)
2334     (save-excursion
2335       (let ((articles (gnus-summary-articles-in-thread)))
2336         (while articles
2337           (gnus-summary-goto-subject (car articles))
2338           (gnus-summary-raise-score score)
2339           (setq articles (cdr articles))))
2340       (setq e (point)))
2341     (let ((gnus-summary-check-current t))
2342       (unless (zerop (gnus-summary-next-subject 1 t))
2343         (goto-char e))))
2344   (gnus-summary-recenter)
2345   (gnus-summary-position-point)
2346   (gnus-set-mode-line 'summary))
2347
2348 (defun gnus-summary-lower-same-subject-and-select (score)
2349   "Raise articles which has the same subject with SCORE and select the next."
2350   (interactive "p")
2351   (gnus-summary-raise-same-subject-and-select (- score)))
2352
2353 (defun gnus-summary-lower-same-subject (score)
2354   "Raise articles which has the same subject with SCORE."
2355   (interactive "p")
2356   (gnus-summary-raise-same-subject (- score)))
2357
2358 (defun gnus-summary-lower-thread (&optional score)
2359   "Lower score of articles in the current thread with SCORE."
2360   (interactive "P")
2361   (gnus-summary-raise-thread (- (1- (gnus-score-default score)))))
2362
2363 ;;; Finding score files.
2364
2365 (defun gnus-score-score-files (group)
2366   "Return a list of all possible score files."
2367   ;; Search and set any global score files.
2368   (when gnus-global-score-files
2369     (unless gnus-internal-global-score-files
2370       (gnus-score-search-global-directories gnus-global-score-files)))
2371   ;; Fix the kill-file dir variable.
2372   (setq gnus-kill-files-directory
2373         (file-name-as-directory gnus-kill-files-directory))
2374   ;; If we can't read it, there are no score files.
2375   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2376       (setq gnus-score-file-list nil)
2377     (if (not (gnus-use-long-file-name 'not-score))
2378         ;; We do not use long file names, so we have to do some
2379         ;; directory traversing.
2380         (setq gnus-score-file-list
2381               (cons nil
2382                     (or gnus-short-name-score-file-cache
2383                         (prog2
2384                             (gnus-message 6 "Finding all score files...")
2385                             (setq gnus-short-name-score-file-cache
2386                                   (gnus-score-score-files-1
2387                                    gnus-kill-files-directory))
2388                           (gnus-message 6 "Finding all score files...done")))))
2389       ;; We want long file names.
2390       (when (or (not gnus-score-file-list)
2391                 (not (car gnus-score-file-list))
2392                 (gnus-file-newer-than gnus-kill-files-directory
2393                                       (car gnus-score-file-list)))
2394         (setq gnus-score-file-list
2395               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2396                     (nreverse
2397                      (directory-files
2398                       gnus-kill-files-directory t
2399                       (gnus-score-file-regexp)))))))
2400     (cdr gnus-score-file-list)))
2401
2402 (defun gnus-score-score-files-1 (dir)
2403   "Return all possible score files under DIR."
2404   (let ((files (list (expand-file-name dir)))
2405         (regexp (gnus-score-file-regexp))
2406         (case-fold-search nil)
2407         seen out file)
2408     (while (setq file (pop files))
2409       (cond
2410        ;; Ignore "." and "..".
2411        ((member (file-name-nondirectory file) '("." ".."))
2412         nil)
2413        ;; Add subtrees of directory to also be searched.
2414        ((and (file-directory-p file)
2415              (not (member (file-truename file) seen)))
2416         (push (file-truename file) seen)
2417         (setq files (nconc (directory-files file t nil t) files)))
2418        ;; Add files to the list of score files.
2419        ((string-match regexp file)
2420         (push file out))))
2421     (or out
2422         ;; Return a dummy value.
2423         (list "~/News/this.file.does.not.exist.SCORE"))))
2424
2425 (defun gnus-score-file-regexp ()
2426   "Return a regexp that match all score files."
2427   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2428           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2429
2430 (defun gnus-score-find-bnews (group)
2431   "Return a list of score files for GROUP.
2432 The score files are those files in the ~/News/ directory which matches
2433 GROUP using BNews sys file syntax."
2434   (let* ((sfiles (append (gnus-score-score-files group)
2435                          gnus-internal-global-score-files))
2436          (kill-dir (file-name-as-directory
2437                     (expand-file-name gnus-kill-files-directory)))
2438          (klen (length kill-dir))
2439          (score-regexp (gnus-score-file-regexp))
2440          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2441          ofiles not-match regexp)
2442     (save-excursion
2443       (set-buffer (get-buffer-create "*gnus score files*"))
2444       (buffer-disable-undo (current-buffer))
2445       ;; Go through all score file names and create regexp with them
2446       ;; as the source.
2447       (while sfiles
2448         (erase-buffer)
2449         (insert (car sfiles))
2450         (goto-char (point-min))
2451         ;; First remove the suffix itself.
2452         (when (re-search-forward (concat "." score-regexp) nil t)
2453           (replace-match "" t t)
2454           (goto-char (point-min))
2455           (if (looking-at (regexp-quote kill-dir))
2456               ;; If the file name was just "SCORE", `klen' is one character
2457               ;; too much.
2458               (delete-char (min (1- (point-max)) klen))
2459             (goto-char (point-max))
2460             (search-backward "/")
2461             (delete-region (1+ (point)) (point-min)))
2462           ;; If short file names were used, we have to translate slashes.
2463           (goto-char (point-min))
2464           (let ((regexp (concat
2465                          "[/:" (if trans (char-to-string trans) "") "]")))
2466             (while (re-search-forward regexp nil t)
2467               (replace-match "." t t)))
2468           ;; Kludge to get rid of "nntp+" problems.
2469           (goto-char (point-min))
2470           (when (looking-at "nn[a-z]+\\+")
2471             (search-forward "+")
2472             (forward-char -1)
2473             (insert "\\")
2474             (forward-char 1))
2475           ;; Kludge to deal with "++".
2476           (while (search-forward "+" nil t)
2477             (replace-match "\\+" t t))
2478           ;; Translate "all" to ".*".
2479           (goto-char (point-min))
2480           (while (search-forward "all" nil t)
2481             (replace-match ".*" t t))
2482           (goto-char (point-min))
2483           ;; Deal with "not."s.
2484           (if (looking-at "not.")
2485               (progn
2486                 (setq not-match t)
2487                 (setq regexp (concat "^" (buffer-substring 5 (point-max)) "$")))
2488             (setq regexp (concat "^" (buffer-substring 1 (point-max)) "$"))
2489             (setq not-match nil))
2490           ;; Finally - if this resulting regexp matches the group name,
2491           ;; we add this score file to the list of score files
2492           ;; applicable to this group.
2493           (when (or (and not-match
2494                          (not (string-match regexp group)))
2495                     (and (not not-match)
2496                          (string-match regexp group)))
2497             (push (car sfiles) ofiles)))
2498         (setq sfiles (cdr sfiles)))
2499       (kill-buffer (current-buffer))
2500       ;; Slight kludge here - the last score file returned should be
2501       ;; the local score file, whether it exists or not.  This is so
2502       ;; that any score commands the user enters will go to the right
2503       ;; file, and not end up in some global score file.
2504       (let ((localscore (gnus-score-file-name group)))
2505         (setq ofiles (cons localscore (delete localscore ofiles))))
2506       (gnus-sort-score-files (nreverse ofiles)))))
2507
2508 (defun gnus-score-find-single (group)
2509   "Return list containing the score file for GROUP."
2510   (list (or gnus-newsgroup-adaptive-score-file
2511             (gnus-score-file-name group gnus-adaptive-file-suffix))
2512         (gnus-score-file-name group)))
2513
2514 (defun gnus-score-find-hierarchical (group)
2515   "Return list of score files for GROUP.
2516 This includes the score file for the group and all its parents."
2517   (let* ((prefix (gnus-group-real-prefix group))
2518          (all (list nil))
2519          (group (gnus-group-real-name group))
2520          (start 0))
2521     (while (string-match "\\." group (1+ start))
2522       (setq start (match-beginning 0))
2523       (push (substring group 0 start) all))
2524     (push group all)
2525     (setq all
2526           (nconc
2527            (mapcar (lambda (group)
2528                      (gnus-score-file-name group gnus-adaptive-file-suffix))
2529                    (setq all (nreverse all)))
2530            (mapcar 'gnus-score-file-name all)))
2531     (if (equal prefix "")
2532         all
2533       (mapcar
2534        (lambda (file)
2535          (nnheader-translate-file-chars
2536           (concat (file-name-directory file) prefix
2537                   (file-name-nondirectory file))))
2538        all))))
2539
2540 (defun gnus-score-file-rank (file)
2541   "Return a number that says how specific score FILE is.
2542 Destroys the current buffer."
2543   (if (member file gnus-internal-global-score-files)
2544       0
2545     (when (string-match
2546            (concat "^" (regexp-quote
2547                         (expand-file-name
2548                          (file-name-as-directory gnus-kill-files-directory))))
2549            file)
2550       (setq file (substring file (match-end 0))))
2551     (insert file)
2552     (goto-char (point-min))
2553     (let ((beg (point))
2554           elems)
2555       (while (re-search-forward "[./]" nil t)
2556         (push (buffer-substring beg (1- (point)))
2557               elems))
2558       (erase-buffer)
2559       (setq elems (delete "all" elems))
2560       (length elems))))
2561
2562 (defun gnus-sort-score-files (files)
2563   "Sort FILES so that the most general files come first."
2564   (nnheader-temp-write nil
2565     (let ((alist
2566            (mapcar
2567             (lambda (file)
2568               (cons (inline (gnus-score-file-rank file)) file))
2569             files)))
2570       (mapcar
2571        (lambda (f) (cdr f))
2572        (sort alist 'car-less-than-car)))))
2573
2574 (defun gnus-score-find-alist (group)
2575   "Return list of score files for GROUP.
2576 The list is determined from the variable gnus-score-file-alist."
2577   (let ((alist gnus-score-file-multiple-match-alist)
2578         score-files)
2579     ;; if this group has been seen before, return the cached entry
2580     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2581         (cdr score-files)               ;ensures caching groups with no matches
2582       ;; handle the multiple match alist
2583       (while alist
2584         (when (string-match (caar alist) group)
2585           (setq score-files
2586                 (nconc score-files (copy-sequence (cdar alist)))))
2587         (setq alist (cdr alist)))
2588       (setq alist gnus-score-file-single-match-alist)
2589       ;; handle the single match alist
2590       (while alist
2591         (when (string-match (caar alist) group)
2592           ;; progn used just in case ("regexp") has no files
2593           ;; and score-files is still nil.  -sj
2594           ;; this can be construed as a "stop searching here" feature :>
2595           ;; and used to simplify regexps in the single-alist
2596           (setq score-files
2597                 (nconc score-files (copy-sequence (cdar alist))))
2598           (setq alist nil))
2599         (setq alist (cdr alist)))
2600       ;; cache the score files
2601       (push (cons group score-files) gnus-score-file-alist-cache)
2602       score-files)))
2603
2604 (defun gnus-all-score-files (&optional group)
2605   "Return a list of all score files for the current group."
2606   (let ((funcs gnus-score-find-score-files-function)
2607         (group (or group gnus-newsgroup-name))
2608         score-files)
2609     (when group
2610       ;; Make sure funcs is a list.
2611       (and funcs
2612            (not (listp funcs))
2613            (setq funcs (list funcs)))
2614       ;; Get the initial score files for this group.
2615       (when funcs
2616         (setq score-files (nreverse (gnus-score-find-alist group))))
2617       ;; Add any home adapt files.
2618       (let ((home (gnus-home-score-file group t)))
2619         (when home
2620           (push home score-files)
2621           (setq gnus-newsgroup-adaptive-score-file home)))
2622       ;; Check whether there is a `adapt-file' group parameter.
2623       (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2624         (when param-file
2625           (push param-file score-files)
2626           (setq gnus-newsgroup-adaptive-score-file param-file)))
2627       ;; Go through all the functions for finding score files (or actual
2628       ;; scores) and add them to a list.
2629       (while funcs
2630         (when (gnus-functionp (car funcs))
2631           (setq score-files
2632                 (nconc score-files (nreverse (funcall (car funcs) group)))))
2633         (setq funcs (cdr funcs)))
2634       ;; Add any home score files.
2635       (let ((home (gnus-home-score-file group)))
2636         (when home
2637           (push home score-files)))
2638       ;; Check whether there is a `score-file' group parameter.
2639       (let ((param-file (gnus-group-find-parameter group 'score-file)))
2640         (when param-file
2641           (push param-file score-files)))
2642       ;; Expand all files names.
2643       (let ((files score-files))
2644         (while files
2645           (when (stringp (car files))
2646             (setcar files (expand-file-name
2647                            (car files) gnus-kill-files-directory)))
2648           (pop files)))
2649       (setq score-files (nreverse score-files))
2650       ;; Remove any duplicate score files.
2651       (while (and score-files
2652                   (member (car score-files) (cdr score-files)))
2653         (pop score-files))
2654       (let ((files score-files))
2655         (while (cdr files)
2656           (if (member (cadr files) (cddr files))
2657               (setcdr files (cddr files))
2658             (pop files))))
2659       ;; Do the scoring if there are any score files for this group.
2660       score-files)))
2661
2662 (defun gnus-possibly-score-headers (&optional trace)
2663   "Do scoring if scoring is required."
2664   (let ((score-files (gnus-all-score-files)))
2665     (when score-files
2666       (gnus-score-headers score-files trace))))
2667
2668 (defun gnus-score-file-name (newsgroup &optional suffix)
2669   "Return the name of a score file for NEWSGROUP."
2670   (let ((suffix (or suffix gnus-score-file-suffix)))
2671     (nnheader-translate-file-chars
2672      (cond
2673       ((or (null newsgroup)
2674            (string-equal newsgroup ""))
2675        ;; The global score file is placed at top of the directory.
2676        (expand-file-name
2677         suffix gnus-kill-files-directory))
2678       ((gnus-use-long-file-name 'not-score)
2679        ;; Append ".SCORE" to newsgroup name.
2680        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2681                                  "." suffix)
2682                          gnus-kill-files-directory))
2683       (t
2684        ;; Place "SCORE" under the hierarchical directory.
2685        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2686                                  "/" suffix)
2687                          gnus-kill-files-directory))))))
2688
2689 (defun gnus-score-search-global-directories (files)
2690   "Scan all global score directories for score files."
2691   ;; Set the variable `gnus-internal-global-score-files' to all
2692   ;; available global score files.
2693   (interactive (list gnus-global-score-files))
2694   (let (out)
2695     (while files
2696       (if (string-match "/$" (car files))
2697           (setq out (nconc (directory-files
2698                             (car files) t
2699                             (concat (gnus-score-file-regexp) "$"))))
2700         (push (car files) out))
2701       (setq files (cdr files)))
2702     (setq gnus-internal-global-score-files out)))
2703
2704 (defun gnus-score-default-fold-toggle ()
2705   "Toggle folding for new score file entries."
2706   (interactive)
2707   (setq gnus-score-default-fold (not gnus-score-default-fold))
2708   (if gnus-score-default-fold
2709       (gnus-message 1 "New score file entries will be case insensitive.")
2710     (gnus-message 1 "New score file entries will be case sensitive.")))
2711
2712 ;;; Home score file.
2713
2714 (defun gnus-home-score-file (group &optional adapt)
2715   "Return the home score file for GROUP.
2716 If ADAPT, return the home adaptive file instead."
2717   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2718         elem found)
2719     ;; Make sure we have a list.
2720     (unless (listp list)
2721       (setq list (list list)))
2722     ;; Go through the list and look for matches.
2723     (while (and (not found)
2724                 (setq elem (pop list)))
2725       (setq found
2726             (cond
2727              ;; Simple string.
2728              ((stringp elem)
2729               elem)
2730              ;; Function.
2731              ((gnus-functionp elem)
2732               (funcall elem group))
2733              ;; Regexp-file cons
2734              ((consp elem)
2735               (when (string-match (car elem) group)
2736                 (cadr elem))))))
2737     (when found
2738       (nnheader-concat gnus-kill-files-directory found))))
2739
2740 (defun gnus-hierarchial-home-score-file (group)
2741   "Return the score file of the top-level hierarchy of GROUP."
2742   (if (string-match "^[^.]+\\." group)
2743       (concat (match-string 0 group) gnus-score-file-suffix)
2744     ;; Group name without any dots.
2745     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2746             gnus-score-file-suffix)))
2747
2748 (defun gnus-hierarchial-home-adapt-file (group)
2749   "Return the adapt file of the top-level hierarchy of GROUP."
2750   (if (string-match "^[^.]+\\." group)
2751       (concat (match-string 0 group) gnus-adaptive-file-suffix)
2752     ;; Group name without any dots.
2753     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2754             gnus-adaptive-file-suffix)))
2755
2756 ;;;
2757 ;;; Score decays
2758 ;;;
2759
2760 (defun gnus-decay-score (score)
2761   "Decay SCORE according to `gnus-score-decay-constant' and `gnus-score-decay-scale'."
2762   (floor
2763    (- score
2764       (* (if (< score 0) -1 1)
2765          (min (abs score)
2766               (max gnus-score-decay-constant
2767                    (* (abs score)
2768                       gnus-score-decay-scale)))))))
2769
2770 (defun gnus-decay-scores (alist day)
2771   "Decay non-permanent scores in ALIST."
2772   (let ((times (- (gnus-time-to-day (current-time)) day))
2773         kill entry updated score n)
2774     (unless (zerop times)               ;Done decays today already?
2775       (while (setq entry (pop alist))
2776         (when (stringp (car entry))
2777           (setq entry (cdr entry))
2778           (while (setq kill (pop entry))
2779             (when (nth 2 kill)
2780               (setq updated t)
2781               (setq score (or (nth 1 kill)
2782                               gnus-score-interactive-default-score)
2783                     n times)
2784               (while (natnump (decf n))
2785                 (setq score (funcall gnus-decay-score-function score)))
2786               (setcdr kill (cons score 
2787                                  (cdr (cdr kill)))))))))
2788     ;; Return whether this score file needs to be saved.  By Je-haysuss!
2789     updated))
2790
2791 (defun gnus-score-regexp-bad-p (regexp)
2792   "Test whether REGEXP is safe for Gnus scoring.
2793 A regexp is unsafe if it matches newline or a buffer boundary.
2794
2795 If the regexp is good, return nil.  If the regexp is bad, return a
2796 cons cell (SYM . STRING), where the symbol SYM is `new' or `bad'.
2797 In the `new' case, the string is a safe replacement for REGEXP.
2798 In the `bad' case, the string is a unsafe subexpression of REGEXP,
2799 and we do not have a simple replacement to suggest.
2800
2801 See `(Gnus)Scoring Tips' for examples of good regular expressions."
2802   (let (case-fold-search)
2803     (and
2804      ;; First, try a relatively fast necessary condition.
2805      ;; Notice ranges (like [^:] or [\t-\r]), \s>, \Sw, \W, \', \`:
2806      (string-match "\n\\|\\\\[SsW`']\\|\\[\\^\\|[\0-\n]-" regexp)
2807      ;; Now break the regexp into tokens, and check each:
2808      (let ((tail regexp)                ; remaining regexp to check
2809            tok                          ; current token
2810            bad                          ; nil, or bad subexpression
2811            new                          ; nil, or replacement regexp so far
2812            end)                         ; length of current token
2813        (while (and (not bad)
2814                    (string-match
2815                     "\\`\\(\\\\[sS]?.\\|\\[\\^?]?[^]]*]\\|[^\\]\\)"
2816                     tail))
2817          (setq end (match-end 0)
2818                tok (substring tail 0 end)
2819                tail (substring tail end))
2820          (if;; Is token `bad' (matching newline or buffer ends)?
2821              (or (member tok '("\n" "\\W" "\\`" "\\'"))
2822                  ;; This next handles "[...]", "\\s.", and "\\S.":
2823                  (and (> end 2) (string-match tok "\n")))
2824              (let ((newtok
2825                     ;; Try to suggest a replacement for tok ...
2826                     (cond ((string-equal tok "\\`") "^") ; or "\\(^\\)"
2827                           ((string-equal tok "\\'") "$") ; or "\\($\\)"
2828                           ((string-match "\\[\\^" tok) ; very common
2829                            (concat (substring tok 0 -1) "\n]")))))
2830                (if newtok
2831                    (setq new
2832                          (concat
2833                           (or new
2834                               ;; good prefix so far:
2835                               (substring regexp 0 (- (+ (length tail) end))))
2836                           newtok))
2837                  ;; No replacement idea, so give up:
2838                  (setq bad tok)))
2839            ;; tok is good, may need to extend new
2840            (and new (setq new (concat new tok)))))
2841        ;; Now return a value:
2842        (cond
2843         (bad (cons 'bad bad))
2844         (new (cons 'new new))
2845         ;; or nil
2846         )))))
2847
2848 (provide 'gnus-score)
2849
2850 ;;; gnus-score.el ends here