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