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