*** empty log message ***
[gnus] / 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             (?r "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" "message-id" 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 ?t)))
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 (gnus-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   (interactive)
747   "Enter score file entry.
748 HEADER is the header being scored.
749 MATCH is the string we are looking for.
750 TYPE is the match type: substring, regexp, exact, fuzzy.
751 SCORE is the score to add.
752 DATE is the expire date, or nil for no expire, or 'now for immediate expire.
753 If optional argument `PROMPT' is non-nil, allow user to edit match.
754 If optional argument `SILENT' is nil, show effect of score entry."
755   ;; Regexp is the default type.
756   (when (eq type t)
757     (setq type 'r))
758   ;; Simplify matches...
759   (cond ((or (eq type 'r) (eq type 's) (eq type nil))
760          (setq match (if match (gnus-simplify-subject-re match) "")))
761         ((eq type 'f)
762          (setq match (gnus-simplify-subject-fuzzy match))))
763   (let ((score (gnus-score-default score))
764         (header (format "%s" (downcase header)))
765         new)
766     (when prompt
767       (setq match (read-string
768                    (format "Match %s on %s, %s: "
769                            (cond ((eq date 'now)
770                                   "now")
771                                  ((stringp date)
772                                   "temp")
773                                  (t "permanent"))
774                            header
775                            (if (< score 0) "lower" "raise"))
776                    (if (numberp match)
777                        (int-to-string match)
778                      match))))
779
780     ;; Get rid of string props.
781     (setq match (format "%s" match))
782
783     ;; If this is an integer comparison, we transform from string to int.
784     (when (eq (nth 2 (assoc header gnus-header-index)) 'gnus-score-integer)
785       (setq match (string-to-int match)))
786
787     (unless (eq date 'now)
788       ;; Add the score entry to the score file.
789       (when (= score gnus-score-interactive-default-score)
790         (setq score nil))
791       (let ((old (gnus-score-get header))
792             elem)
793         (setq new
794               (cond
795                (type
796                 (list match score
797                       (and date (if (numberp date) date
798                                   (date-to-day date)))
799                       type))
800                (date (list match score (date-to-day date)))
801                (score (list match score))
802                (t (list match))))
803         ;; We see whether we can collapse some score entries.
804         ;; This isn't quite correct, because there may be more elements
805         ;; later on with the same key that have matching elems...  Hm.
806         (if (and old
807                  (setq elem (assoc match old))
808                  (eq (nth 3 elem) (nth 3 new))
809                  (or (and (numberp (nth 2 elem)) (numberp (nth 2 new)))
810                      (and (not (nth 2 elem)) (not (nth 2 new)))))
811             ;; Yup, we just add this new score to the old elem.
812             (setcar (cdr elem) (+ (or (nth 1 elem)
813                                       gnus-score-interactive-default-score)
814                                   (or (nth 1 new)
815                                       gnus-score-interactive-default-score)))
816           ;; Nope, we have to add a new elem.
817           (gnus-score-set header (if old (cons new old) (list new)) nil t))
818         (gnus-score-set 'touched '(t))))
819
820     ;; Score the current buffer.
821     (unless silent
822       (if (and (>= (nth 1 (assoc header gnus-header-index)) 0)
823                (eq (nth 2 (assoc header gnus-header-index))
824                    'gnus-score-string))
825           (gnus-summary-score-effect header match type score)
826         (gnus-summary-rescore)))
827
828     ;; Return the new scoring rule.
829     new))
830
831 (defun gnus-summary-score-effect (header match type score)
832   "Simulate the effect of a score file entry.
833 HEADER is the header being scored.
834 MATCH is the string we are looking for.
835 TYPE is the score type.
836 SCORE is the score to add."
837   (interactive (list (completing-read "Header: "
838                                       gnus-header-index
839                                       (lambda (x) (fboundp (nth 2 x)))
840                                       t)
841                      (read-string "Match: ")
842                      (y-or-n-p "Use regexp match? ")
843                      (prefix-numeric-value current-prefix-arg)))
844   (save-excursion
845     (unless (and (stringp match) (> (length match) 0))
846       (error "No match"))
847     (goto-char (point-min))
848     (let ((regexp (cond ((eq type 'f)
849                          (gnus-simplify-subject-fuzzy match))
850                         ((eq type 'r)
851                          match)
852                         ((eq type 'e)
853                          (concat "\\`" (regexp-quote match) "\\'"))
854                         (t
855                          (regexp-quote match)))))
856       (while (not (eobp))
857         (let ((content (gnus-summary-header header 'noerr))
858               (case-fold-search t))
859           (and content
860                (when (if (eq type 'f)
861                          (string-equal (gnus-simplify-subject-fuzzy content)
862                                        regexp)
863                        (string-match regexp content))
864                  (gnus-summary-raise-score score))))
865         (beginning-of-line 2))))
866   (gnus-set-mode-line 'summary))
867
868 (defun gnus-summary-score-crossposting (score date)
869   ;; Enter score file entry for current crossposting.
870   ;; SCORE is the score to add.
871   ;; DATE is the expire date.
872   (let ((xref (gnus-summary-header "xref"))
873         (start 0)
874         group)
875     (unless xref
876       (error "This article is not crossposted"))
877     (while (string-match " \\([^ \t]+\\):" xref start)
878       (setq start (match-end 0))
879       (when (not (string=
880                   (setq group
881                         (substring xref (match-beginning 1) (match-end 1)))
882                   gnus-newsgroup-name))
883         (gnus-summary-score-entry
884          "xref" (concat " " group ":") nil score date t)))))
885
886 \f
887 ;;;
888 ;;; Gnus Score Files
889 ;;;
890
891 ;; All score code written by Per Abrahamsen <abraham@iesd.auc.dk>.
892
893 ;; Added by Per Abrahamsen <amanda@iesd.auc.dk>.
894 (defun gnus-score-set-mark-below (score)
895   "Automatically mark articles with score below SCORE as read."
896   (interactive
897    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
898              (string-to-int (read-string "Mark below: ")))))
899   (setq score (or score gnus-summary-default-score 0))
900   (gnus-score-set 'mark (list score))
901   (gnus-score-set 'touched '(t))
902   (setq gnus-summary-mark-below score)
903   (gnus-score-update-lines))
904
905 (defun gnus-score-update-lines ()
906   "Update all lines in the summary buffer."
907   (save-excursion
908     (goto-char (point-min))
909     (while (not (eobp))
910       (gnus-summary-update-line)
911       (forward-line 1))))
912
913 (defun gnus-score-update-all-lines ()
914   "Update all lines in the summary buffer, even the hidden ones."
915   (save-excursion
916     (goto-char (point-min))
917     (let (hidden)
918       (while (not (eobp))
919         (when (gnus-summary-show-thread)
920           (push (point) hidden))
921         (gnus-summary-update-line)
922         (forward-line 1))
923       ;; Re-hide the hidden threads.
924       (while hidden
925         (goto-char (pop hidden))
926         (gnus-summary-hide-thread)))))
927
928 (defun gnus-score-set-expunge-below (score)
929   "Automatically expunge articles with score below SCORE."
930   (interactive
931    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
932              (string-to-int (read-string "Set expunge below: ")))))
933   (setq score (or score gnus-summary-default-score 0))
934   (gnus-score-set 'expunge (list score))
935   (gnus-score-set 'touched '(t)))
936
937 (defun gnus-score-followup-article (&optional score)
938   "Add SCORE to all followups to the article in the current buffer."
939   (interactive "P")
940   (setq score (gnus-score-default score))
941   (when (gnus-buffer-live-p gnus-summary-buffer)
942     (save-excursion
943       (save-restriction
944         (message-narrow-to-headers)
945         (let ((id (mail-fetch-field "message-id")))
946           (when id
947             (set-buffer gnus-summary-buffer)
948             (gnus-summary-score-entry
949              "references" (concat id "[ \t]*$") 'r
950              score (current-time-string) nil t)))))))
951
952 (defun gnus-score-followup-thread (&optional score)
953   "Add SCORE to all later articles in the thread the current buffer is part of."
954   (interactive "P")
955   (setq score (gnus-score-default score))
956   (when (gnus-buffer-live-p gnus-summary-buffer)
957     (save-excursion
958       (save-restriction
959         (goto-char (point-min))
960         (let ((id (mail-fetch-field "message-id")))
961           (when id
962             (set-buffer gnus-summary-buffer)
963             (gnus-summary-score-entry
964              "references" id 's
965              score (current-time-string))))))))
966
967 (defun gnus-score-set (symbol value &optional alist warn)
968   ;; Set SYMBOL to VALUE in ALIST.
969   (let* ((alist
970           (or alist
971               gnus-score-alist
972               (gnus-newsgroup-score-alist)))
973          (entry (assoc symbol alist)))
974     (cond ((gnus-score-get 'read-only alist)
975            ;; This is a read-only score file, so we do nothing.
976            (when warn
977              (gnus-message 4 "Note: read-only score file; entry discarded")))
978           (entry
979            (setcdr entry value))
980           ((null alist)
981            (error "Empty alist"))
982           (t
983            (setcdr alist
984                    (cons (cons symbol value) (cdr alist)))))))
985
986 (defun gnus-summary-raise-score (n)
987   "Raise the score of the current article by N."
988   (interactive "p")
989   (gnus-summary-set-score (+ (gnus-summary-article-score)
990                              (or n gnus-score-interactive-default-score ))))
991
992 (defun gnus-summary-set-score (n)
993   "Set the score of the current article to N."
994   (interactive "p")
995   (save-excursion
996     (gnus-summary-show-thread)
997     (let ((buffer-read-only nil))
998       ;; Set score.
999       (gnus-summary-update-mark
1000        (if (= n (or gnus-summary-default-score 0)) ? 
1001          (if (< n (or gnus-summary-default-score 0))
1002              gnus-score-below-mark gnus-score-over-mark))
1003        'score))
1004     (let* ((article (gnus-summary-article-number))
1005            (score (assq article gnus-newsgroup-scored)))
1006       (if score (setcdr score n)
1007         (push (cons article n) gnus-newsgroup-scored)))
1008     (gnus-summary-update-line)))
1009
1010 (defun gnus-summary-current-score ()
1011   "Return the score of the current article."
1012   (interactive)
1013   (gnus-message 1 "%s" (gnus-summary-article-score)))
1014
1015 (defun gnus-score-change-score-file (file)
1016   "Change current score alist."
1017   (interactive
1018    (list (read-file-name "Change to score file: " gnus-kill-files-directory)))
1019   (gnus-score-load-file file)
1020   (gnus-set-mode-line 'summary))
1021
1022 (defvar gnus-score-edit-exit-function)
1023 (defun gnus-score-edit-current-scores (file)
1024   "Edit the current score alist."
1025   (interactive (list gnus-current-score-file))
1026   (if (not gnus-current-score-file)
1027       (error "No current score file")
1028     (let ((winconf (current-window-configuration)))
1029       (when (buffer-name gnus-summary-buffer)
1030         (gnus-score-save))
1031       (gnus-make-directory (file-name-directory file))
1032       (setq gnus-score-edit-buffer (find-file-noselect file))
1033       (gnus-configure-windows 'edit-score)
1034       (gnus-score-mode)
1035       (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1036       (make-local-variable 'gnus-prev-winconf)
1037       (setq gnus-prev-winconf winconf))
1038     (gnus-message
1039      4 (substitute-command-keys
1040         "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits"))))
1041
1042 (defun gnus-score-edit-file (file)
1043   "Edit a score file."
1044   (interactive
1045    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
1046   (gnus-make-directory (file-name-directory file))
1047   (when (buffer-name gnus-summary-buffer)
1048     (gnus-score-save))
1049   (let ((winconf (current-window-configuration)))
1050     (setq gnus-score-edit-buffer (find-file-noselect file))
1051     (gnus-configure-windows 'edit-score)
1052     (gnus-score-mode)
1053     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1054     (make-local-variable 'gnus-prev-winconf)
1055     (setq gnus-prev-winconf winconf))
1056   (gnus-message
1057    4 (substitute-command-keys
1058       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
1059
1060 (defun gnus-score-load-file (file)
1061   ;; Load score file FILE.  Returns a list a retrieved score-alists.
1062   (let* ((file (expand-file-name
1063                 (or (and (string-match
1064                           (concat "^" (regexp-quote
1065                                        (expand-file-name
1066                                         gnus-kill-files-directory)))
1067                           (expand-file-name file))
1068                          file)
1069                     (concat (file-name-as-directory gnus-kill-files-directory)
1070                             file))))
1071          (cached (assoc file gnus-score-cache))
1072          (global (member file gnus-internal-global-score-files))
1073          lists alist)
1074     (if cached
1075         ;; The score file was already loaded.
1076         (setq alist (cdr cached))
1077       ;; We load the score file.
1078       (setq gnus-score-alist nil)
1079       (setq alist (gnus-score-load-score-alist file))
1080       ;; We add '(touched) to the alist to signify that it hasn't been
1081       ;; touched (yet).
1082       (unless (assq 'touched alist)
1083         (push (list 'touched nil) alist))
1084       ;; If it is a global score file, we make it read-only.
1085       (and global
1086            (not (assq 'read-only alist))
1087            (push (list 'read-only t) alist))
1088       (push (cons file alist) gnus-score-cache))
1089     (let ((a alist)
1090           found)
1091       (while a
1092         ;; Downcase all header names.
1093         (cond
1094          ((stringp (caar a))
1095           (setcar (car a) (downcase (caar a)))
1096           (setq found t))
1097          ;; Advanced scoring.
1098          ((consp (caar a))
1099           (setq found t)))
1100         (pop a))
1101       ;; If there are actual scores in the alist, we add it to the
1102       ;; return value of this function.
1103       (when found
1104         (setq lists (list alist))))
1105     ;; Treat the other possible atoms in the score alist.
1106     (let ((mark (car (gnus-score-get 'mark alist)))
1107           (expunge (car (gnus-score-get 'expunge alist)))
1108           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
1109           (files (gnus-score-get 'files alist))
1110           (exclude-files (gnus-score-get 'exclude-files alist))
1111           (orphan (car (gnus-score-get 'orphan alist)))
1112           (adapt (gnus-score-get 'adapt alist))
1113           (thread-mark-and-expunge
1114            (car (gnus-score-get 'thread-mark-and-expunge alist)))
1115           (adapt-file (car (gnus-score-get 'adapt-file alist)))
1116           (local (gnus-score-get 'local alist))
1117           (decay (car (gnus-score-get 'decay alist)))
1118           (eval (car (gnus-score-get 'eval alist))))
1119       ;; Perform possible decays.
1120       (when (and gnus-decay-scores
1121                  (or cached (file-exists-p file))
1122                  (or (not decay)
1123                      (gnus-decay-scores alist decay)))
1124         (gnus-score-set 'touched '(t) alist)
1125         (gnus-score-set 'decay (list (time-to-day (current-time))) alist))
1126       ;; We do not respect eval and files atoms from global score
1127       ;; files.
1128       (when (and files (not global))
1129         (setq lists (apply 'append lists
1130                            (mapcar (lambda (file)
1131                                      (gnus-score-load-file file))
1132                                    (if adapt-file (cons adapt-file files)
1133                                      files)))))
1134       (when (and eval (not global))
1135         (eval eval))
1136       ;; We then expand any exclude-file directives.
1137       (setq gnus-scores-exclude-files
1138             (nconc
1139              (apply
1140               'nconc
1141               (mapcar
1142                (lambda (sfile)
1143                  (list
1144                   (expand-file-name sfile (file-name-directory file))
1145                   (expand-file-name sfile gnus-kill-files-directory)))
1146                exclude-files))
1147              gnus-scores-exclude-files))
1148       (when local
1149         (save-excursion
1150           (set-buffer gnus-summary-buffer)
1151           (while local
1152             (and (consp (car local))
1153                  (symbolp (caar local))
1154                  (progn
1155                    (make-local-variable (caar local))
1156                    (set (caar local) (nth 1 (car local)))))
1157             (setq local (cdr local)))))
1158       (when orphan
1159         (setq gnus-orphan-score orphan))
1160       (setq gnus-adaptive-score-alist
1161             (cond ((equal adapt '(t))
1162                    (setq gnus-newsgroup-adaptive t)
1163                    gnus-default-adaptive-score-alist)
1164                   ((equal adapt '(ignore))
1165                    (setq gnus-newsgroup-adaptive nil))
1166                   ((consp adapt)
1167                    (setq gnus-newsgroup-adaptive t)
1168                    adapt)
1169                   (t
1170                    ;;(setq gnus-newsgroup-adaptive gnus-use-adaptive-scoring)
1171                    gnus-default-adaptive-score-alist)))
1172       (setq gnus-thread-expunge-below
1173             (or thread-mark-and-expunge gnus-thread-expunge-below))
1174       (setq gnus-summary-mark-below
1175             (or mark mark-and-expunge gnus-summary-mark-below))
1176       (setq gnus-summary-expunge-below
1177             (or expunge mark-and-expunge gnus-summary-expunge-below))
1178       (setq gnus-newsgroup-adaptive-score-file
1179             (or adapt-file gnus-newsgroup-adaptive-score-file)))
1180     (setq gnus-current-score-file file)
1181     (setq gnus-score-alist alist)
1182     lists))
1183
1184 (defun gnus-score-load (file)
1185   ;; Load score FILE.
1186   (let ((cache (assoc file gnus-score-cache)))
1187     (if cache
1188         (setq gnus-score-alist (cdr cache))
1189       (setq gnus-score-alist nil)
1190       (gnus-score-load-score-alist file)
1191       (unless gnus-score-alist
1192         (setq gnus-score-alist (copy-alist '((touched nil)))))
1193       (push (cons file gnus-score-alist) gnus-score-cache))))
1194
1195 (defun gnus-score-remove-from-cache (file)
1196   (setq gnus-score-cache
1197         (delq (assoc file gnus-score-cache) gnus-score-cache)))
1198
1199 (defun gnus-score-load-score-alist (file)
1200   "Read score FILE."
1201   (let (alist)
1202     (if (not (file-readable-p file))
1203         ;; Couldn't read file.
1204         (setq gnus-score-alist nil)
1205       ;; Read file.
1206       (with-temp-buffer
1207         (let ((coding-system-for-write score-mode-coding-system))
1208           (insert-file-contents file))
1209         (goto-char (point-min))
1210         ;; Only do the loading if the score file isn't empty.
1211         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
1212           (setq alist
1213                 (condition-case ()
1214                     (read (current-buffer))
1215                   (error
1216                    (gnus-error 3.2 "Problem with score file %s" file))))))
1217       (cond
1218        ((and alist
1219              (atom alist))
1220         ;; Bogus score file.
1221         (error "Invalid syntax with score file %s" file))
1222        ((eq (car alist) 'setq)
1223         ;; This is an old-style score file.
1224         (setq gnus-score-alist (gnus-score-transform-old-to-new alist)))
1225        (t
1226         (setq gnus-score-alist alist)))
1227       ;; Check the syntax of the score file.
1228       (setq gnus-score-alist
1229             (gnus-score-check-syntax gnus-score-alist file)))))
1230
1231 (defun gnus-score-check-syntax (alist file)
1232   "Check the syntax of the score ALIST."
1233   (cond
1234    ((null alist)
1235     nil)
1236    ((not (consp alist))
1237     (gnus-message 1 "Score file is not a list: %s" file)
1238     (ding)
1239     nil)
1240    (t
1241     (let ((a alist)
1242           sr err s type)
1243       (while (and a (not err))
1244         (setq
1245          err
1246          (cond
1247           ((not (listp (car a)))
1248            (format "Illegal score element %s in %s" (car a) file))
1249           ((stringp (caar a))
1250            (cond
1251             ((not (listp (setq sr (cdar a))))
1252              (format "Illegal header match %s in %s" (nth 1 (car a)) file))
1253             (t
1254              (setq type (caar a))
1255              (while (and sr (not err))
1256                (setq s (pop sr))
1257                (setq
1258                 err
1259                 (cond
1260                  ((if (member (downcase type) '("lines" "chars"))
1261                       (not (numberp (car s)))
1262                     (not (stringp (car s))))
1263                   (format "Illegal match %s in %s" (car s) file))
1264                  ((and (cadr s) (not (integerp (cadr s))))
1265                   (format "Non-integer score %s in %s" (cadr s) file))
1266                  ((and (caddr s) (not (integerp (caddr s))))
1267                   (format "Non-integer date %s in %s" (caddr s) file))
1268                  ((and (cadddr s) (not (symbolp (cadddr s))))
1269                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1270              err)))))
1271         (setq a (cdr a)))
1272       (if err
1273           (progn
1274             (ding)
1275             (gnus-message 3 err)
1276             (sit-for 2)
1277             nil)
1278         alist)))))
1279
1280 (defun gnus-score-transform-old-to-new (alist)
1281   (let* ((alist (nth 2 alist))
1282          out entry)
1283     (when (eq (car alist) 'quote)
1284       (setq alist (nth 1 alist)))
1285     (while alist
1286       (setq entry (car alist))
1287       (if (stringp (car entry))
1288           (let ((scor (cdr entry)))
1289             (push entry out)
1290             (while scor
1291               (setcar scor
1292                       (list (caar scor) (nth 2 (car scor))
1293                             (and (nth 3 (car scor))
1294                                  (date-to-day (nth 3 (car scor))))
1295                             (if (nth 1 (car scor)) 'r 's)))
1296               (setq scor (cdr scor))))
1297         (push (if (not (listp (cdr entry)))
1298                   (list (car entry) (cdr entry))
1299                 entry)
1300               out))
1301       (setq alist (cdr alist)))
1302     (cons (list 'touched t) (nreverse out))))
1303
1304 (defun gnus-score-save ()
1305   ;; Save all score information.
1306   (let ((cache gnus-score-cache)
1307         entry score file)
1308     (save-excursion
1309       (setq gnus-score-alist nil)
1310       (nnheader-set-temp-buffer " *Gnus Scores*")
1311       (while cache
1312         (current-buffer)
1313         (setq entry (pop cache)
1314               file (car entry)
1315               score (cdr entry))
1316         (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1317                 (gnus-score-get 'read-only score)
1318                 (and (file-exists-p file)
1319                      (not (file-writable-p file))))
1320             ()
1321           (setq score (setcdr entry (gnus-delete-alist 'touched score)))
1322           (erase-buffer)
1323           (let (emacs-lisp-mode-hook)
1324             (if (string-match
1325                  (concat (regexp-quote gnus-adaptive-file-suffix) "$")
1326                  file)
1327                 ;; This is an adaptive score file, so we do not run
1328                 ;; it through `pp'.  These files can get huge, and
1329                 ;; are not meant to be edited by human hands.
1330                 (gnus-prin1 score)
1331               ;; This is a normal score file, so we print it very
1332               ;; prettily.
1333               (let ((lisp-mode-syntax-table score-mode-syntax-table))
1334                 (pp score (current-buffer)))))
1335           (gnus-make-directory (file-name-directory file))
1336           ;; If the score file is empty, we delete it.
1337           (if (zerop (buffer-size))
1338               (delete-file file)
1339             ;; There are scores, so we write the file.
1340             (when (file-writable-p file)
1341               (let ((coding-system-for-write score-mode-coding-system))
1342                 (gnus-write-buffer file))
1343               (when gnus-score-after-write-file-function
1344                 (funcall gnus-score-after-write-file-function file)))))
1345         (and gnus-score-uncacheable-files
1346              (string-match gnus-score-uncacheable-files file)
1347              (gnus-score-remove-from-cache file)))
1348       (kill-buffer (current-buffer)))))
1349
1350 (defun gnus-score-load-files (score-files)
1351   "Load all score files in SCORE-FILES."
1352   ;; Load the score files.
1353   (let (scores)
1354     (while score-files
1355       (if (stringp (car score-files))
1356           ;; It is a string, which means that it's a score file name,
1357           ;; so we load the score file and add the score alist to
1358           ;; the list of alists.
1359           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1360         ;; It is an alist, so we just add it to the list directly.
1361         (setq scores (nconc (car score-files) scores)))
1362       (setq score-files (cdr score-files)))
1363     ;; Prune the score files that are to be excluded, if any.
1364     (when gnus-scores-exclude-files
1365       (let ((s scores)
1366             c)
1367         (while s
1368           (and (setq c (rassq (car s) gnus-score-cache))
1369                (member (car c) gnus-scores-exclude-files)
1370                (setq scores (delq (car s) scores)))
1371           (setq s (cdr s)))))
1372     scores))
1373
1374 (defun gnus-score-headers (score-files &optional trace)
1375   ;; Score `gnus-newsgroup-headers'.
1376   (let (scores news)
1377     ;; PLM: probably this is not the best place to clear orphan-score
1378     (setq gnus-orphan-score nil
1379           gnus-scores-articles nil
1380           gnus-scores-exclude-files nil
1381           scores (gnus-score-load-files score-files))
1382     (setq news scores)
1383     ;; Do the scoring.
1384     (while news
1385       (setq scores news
1386             news nil)
1387       (when (and gnus-summary-default-score
1388                  scores)
1389         (let* ((entries gnus-header-index)
1390                (now (date-to-day (current-time-string)))
1391                (expire (and gnus-score-expiry-days
1392                             (- now gnus-score-expiry-days)))
1393                (headers gnus-newsgroup-headers)
1394                (current-score-file gnus-current-score-file)
1395                entry header new)
1396           (gnus-message 5 "Scoring...")
1397           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1398           (while (setq header (pop headers))
1399             ;; WARNING: The assq makes the function O(N*S) while it could
1400             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1401             ;; and S is (length gnus-newsgroup-scored).
1402             (unless (assq (mail-header-number header) gnus-newsgroup-scored)
1403               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1404                     (cons (cons header (or gnus-summary-default-score 0))
1405                           gnus-scores-articles))))
1406
1407           (save-excursion
1408             (set-buffer (gnus-get-buffer-create "*Headers*"))
1409             (buffer-disable-undo (current-buffer))
1410             (when (gnus-buffer-live-p gnus-summary-buffer)
1411               (message-clone-locals gnus-summary-buffer))
1412
1413             ;; Set the global variant of this variable.
1414             (setq gnus-current-score-file current-score-file)
1415             ;; score orphans
1416             (when gnus-orphan-score
1417               (setq gnus-score-index
1418                     (nth 1 (assoc "references" gnus-header-index)))
1419               (gnus-score-orphans gnus-orphan-score))
1420             ;; Run each header through the score process.
1421             (while entries
1422               (setq entry (pop entries)
1423                     header (nth 0 entry)
1424                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1425               (when (< 0 (apply 'max (mapcar
1426                                       (lambda (score)
1427                                         (length (gnus-score-get header score)))
1428                                       scores)))
1429                 ;; Call the scoring function for this type of "header".
1430                 (when (setq new (funcall (nth 2 entry) scores header
1431                                          now expire trace))
1432                   (push new news))))
1433             ;; Remove the buffer.
1434             (kill-buffer (current-buffer)))
1435
1436           ;; Add articles to `gnus-newsgroup-scored'.
1437           (while gnus-scores-articles
1438             (when (or (/= gnus-summary-default-score
1439                           (cdar gnus-scores-articles))
1440                       gnus-save-score)
1441               (push (cons (mail-header-number (caar gnus-scores-articles))
1442                           (cdar gnus-scores-articles))
1443                     gnus-newsgroup-scored))
1444             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1445
1446           (let (score)
1447             (while (setq score (pop scores))
1448               (while score
1449                 (when (listp (caar score))
1450                   (gnus-score-advanced (car score) trace))
1451                 (pop score))))
1452
1453           (gnus-message 5 "Scoring...done"))))))
1454
1455
1456 (defun gnus-get-new-thread-ids (articles)
1457   (let ((index (nth 1 (assoc "message-id" gnus-header-index)))
1458         (refind gnus-score-index)
1459         id-list art this tref)
1460     (while articles
1461       (setq art (car articles)
1462             this (aref (car art) index)
1463             tref (aref (car art) refind)
1464             articles (cdr articles))
1465       (when (string-equal tref "")      ;no references line
1466         (push this id-list)))
1467     id-list))
1468
1469 ;; Orphan functions written by plm@atcmp.nl (Peter Mutsaers).
1470 (defun gnus-score-orphans (score)
1471   (let ((new-thread-ids (gnus-get-new-thread-ids gnus-scores-articles))
1472         alike articles art arts this last this-id)
1473
1474     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1475           articles gnus-scores-articles)
1476
1477     ;;more or less the same as in gnus-score-string
1478     (erase-buffer)
1479     (while articles
1480       (setq art (car articles)
1481             this (aref (car art) gnus-score-index)
1482             articles (cdr articles))
1483       ;;completely skip if this is empty (not a child, so not an orphan)
1484       (when (not (string= this ""))
1485         (if (equal last this)
1486             ;; O(N*H) cons-cells used here, where H is the number of
1487             ;; headers.
1488             (push art alike)
1489           (when last
1490             ;; Insert the line, with a text property on the
1491             ;; terminating newline referring to the articles with
1492             ;; this line.
1493             (insert last ?\n)
1494             (put-text-property (1- (point)) (point) 'articles alike))
1495           (setq alike (list art)
1496                 last this))))
1497     (when last                          ; Bwadr, duplicate code.
1498       (insert last ?\n)
1499       (put-text-property (1- (point)) (point) 'articles alike))
1500
1501     ;; PLM: now delete those lines that contain an entry from new-thread-ids
1502     (while new-thread-ids
1503       (setq this-id (car new-thread-ids)
1504             new-thread-ids (cdr new-thread-ids))
1505       (goto-char (point-min))
1506       (while (search-forward this-id nil t)
1507         ;; found a match.  remove this line
1508         (beginning-of-line)
1509         (kill-line 1)))
1510
1511     ;; now for each line: update its articles with score by moving to
1512     ;; every end-of-line in the buffer and read the articles property
1513     (goto-char (point-min))
1514     (while (eq 0 (progn
1515                    (end-of-line)
1516                    (setq arts (get-text-property (point) 'articles))
1517                    (while arts
1518                      (setq art (car arts)
1519                            arts (cdr arts))
1520                      (setcdr art (+ score (cdr art))))
1521                    (forward-line))))))
1522
1523
1524 (defun gnus-score-integer (scores header now expire &optional trace)
1525   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1526         entries alist)
1527
1528     ;; Find matches.
1529     (while scores
1530       (setq alist (car scores)
1531             scores (cdr scores)
1532             entries (assoc header alist))
1533       (while (cdr entries)              ;First entry is the header index.
1534         (let* ((rest (cdr entries))
1535                (kill (car rest))
1536                (match (nth 0 kill))
1537                (type (or (nth 3 kill) '>))
1538                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1539                (date (nth 2 kill))
1540                (found nil)
1541                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1542                                    (eq type '>=) (eq type '=))
1543                                type
1544                              (error "Illegal match type: %s" type)))
1545                (articles gnus-scores-articles))
1546           ;; Instead of doing all the clever stuff that
1547           ;; `gnus-score-string' does to minimize searches and stuff,
1548           ;; I will assume that people generally will put so few
1549           ;; matches on numbers that any cleverness will take more
1550           ;; time than one would gain.
1551           (while articles
1552             (when (funcall match-func
1553                            (or (aref (caar articles) gnus-score-index) 0)
1554                            match)
1555               (when trace
1556                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1557                       gnus-score-trace))
1558               (setq found t)
1559               (setcdr (car articles) (+ score (cdar articles))))
1560             (setq articles (cdr articles)))
1561           ;; Update expire date
1562           (cond ((null date))           ;Permanent entry.
1563                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1564                  (gnus-score-set 'touched '(t) alist)
1565                  (setcar (nthcdr 2 kill) now))
1566                 ((and expire (< date expire)) ;Old entry, remove.
1567                  (gnus-score-set 'touched '(t) alist)
1568                  (setcdr entries (cdr rest))
1569                  (setq rest entries)))
1570           (setq entries rest)))))
1571   nil)
1572
1573 (defun gnus-score-date (scores header now expire &optional trace)
1574   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1575         entries alist match match-func article)
1576
1577     ;; Find matches.
1578     (while scores
1579       (setq alist (car scores)
1580             scores (cdr scores)
1581             entries (assoc header alist))
1582       (while (cdr entries)              ;First entry is the header index.
1583         (let* ((rest (cdr entries))
1584                (kill (car rest))
1585                (type (or (nth 3 kill) 'before))
1586                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1587                (date (nth 2 kill))
1588                (found nil)
1589                (articles gnus-scores-articles)
1590                l)
1591           (cond
1592            ((eq type 'after)
1593             (setq match-func 'string<
1594                   match (gnus-date-iso8601 (nth 0 kill))))
1595            ((eq type 'before)
1596             (setq match-func 'gnus-string>
1597                   match (gnus-date-iso8601 (nth 0 kill))))
1598            ((eq type 'at)
1599             (setq match-func 'string=
1600                   match (gnus-date-iso8601 (nth 0 kill))))
1601            ((eq type 'regexp)
1602             (setq match-func 'string-match
1603                   match (nth 0 kill)))
1604            (t (error "Illegal match type: %s" type)))
1605           ;; Instead of doing all the clever stuff that
1606           ;; `gnus-score-string' does to minimize searches and stuff,
1607           ;; I will assume that people generally will put so few
1608           ;; matches on numbers that any cleverness will take more
1609           ;; time than one would gain.
1610           (while (setq article (pop articles))
1611             (when (and
1612                    (setq l (aref (car article) gnus-score-index))
1613                    (funcall match-func match (gnus-date-iso8601 l)))
1614               (when trace
1615                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1616                       gnus-score-trace))
1617               (setq found t)
1618               (setcdr article (+ score (cdr article)))))
1619           ;; Update expire date
1620           (cond ((null date))           ;Permanent entry.
1621                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1622                  (gnus-score-set 'touched '(t) alist)
1623                  (setcar (nthcdr 2 kill) now))
1624                 ((and expire (< date expire)) ;Old entry, remove.
1625                  (gnus-score-set 'touched '(t) alist)
1626                  (setcdr entries (cdr rest))
1627                  (setq rest entries)))
1628           (setq entries rest)))))
1629   nil)
1630
1631 (defun gnus-score-body (scores header now expire &optional trace)
1632   (save-excursion
1633     (setq gnus-scores-articles
1634           (sort gnus-scores-articles
1635                 (lambda (a1 a2)
1636                   (< (mail-header-number (car a1))
1637                      (mail-header-number (car a2))))))
1638     (set-buffer nntp-server-buffer)
1639     (save-restriction
1640       (let* ((buffer-read-only nil)
1641              (articles gnus-scores-articles)
1642              (all-scores scores)
1643              (request-func (cond ((string= "head" header)
1644                                   'gnus-request-head)
1645                                  ((string= "body" header)
1646                                   'gnus-request-body)
1647                                  (t 'gnus-request-article)))
1648              entries alist ofunc article last)
1649         (when articles
1650           (setq last (mail-header-number (caar (last articles))))
1651           ;; Not all backends support partial fetching.  In that case,
1652           ;; we just fetch the entire article.
1653           (unless (gnus-check-backend-function
1654                    (and (string-match "^gnus-" (symbol-name request-func))
1655                         (intern (substring (symbol-name request-func)
1656                                            (match-end 0))))
1657                    gnus-newsgroup-name)
1658             (setq ofunc request-func)
1659             (setq request-func 'gnus-request-article))
1660           (while articles
1661             (setq article (mail-header-number (caar articles)))
1662             (gnus-message 7 "Scoring article %s of %s..." article last)
1663             (when (funcall request-func article gnus-newsgroup-name)
1664               (widen)
1665               (goto-char (point-min))
1666               ;; If just parts of the article is to be searched, but the
1667               ;; backend didn't support partial fetching, we just narrow
1668               ;; to the relevant parts.
1669               (when ofunc
1670                 (if (eq ofunc 'gnus-request-head)
1671                     (narrow-to-region
1672                      (point)
1673                      (or (search-forward "\n\n" nil t) (point-max)))
1674                   (narrow-to-region
1675                    (or (search-forward "\n\n" nil t) (point))
1676                    (point-max))))
1677               (setq scores all-scores)
1678               ;; Find matches.
1679               (while scores
1680                 (setq alist (pop scores)
1681                       entries (assoc header alist))
1682                 (while (cdr entries)    ;First entry is the header index.
1683                   (let* ((rest (cdr entries))
1684                          (kill (car rest))
1685                          (match (nth 0 kill))
1686                          (type (or (nth 3 kill) 's))
1687                          (score (or (nth 1 kill)
1688                                     gnus-score-interactive-default-score))
1689                          (date (nth 2 kill))
1690                          (found nil)
1691                          (case-fold-search
1692                           (not (or (eq type 'R) (eq type 'S)
1693                                    (eq type 'Regexp) (eq type 'String))))
1694                          (search-func
1695                           (cond ((or (eq type 'r) (eq type 'R)
1696                                      (eq type 'regexp) (eq type 'Regexp))
1697                                  're-search-forward)
1698                                 ((or (eq type 's) (eq type 'S)
1699                                      (eq type 'string) (eq type 'String))
1700                                  'search-forward)
1701                                 (t
1702                                  (error "Illegal match type: %s" type)))))
1703                     (goto-char (point-min))
1704                     (when (funcall search-func match nil t)
1705                       ;; Found a match, update scores.
1706                       (setcdr (car articles) (+ score (cdar articles)))
1707                       (setq found t)
1708                       (when trace
1709                         (push
1710                          (cons (car-safe (rassq alist gnus-score-cache)) kill)
1711                          gnus-score-trace)))
1712                     ;; Update expire date
1713                     (unless trace
1714                       (cond
1715                        ((null date))    ;Permanent entry.
1716                        ((and found gnus-update-score-entry-dates)
1717                         ;; Match, update date.
1718                         (gnus-score-set 'touched '(t) alist)
1719                         (setcar (nthcdr 2 kill) now))
1720                        ((and expire (< date expire)) ;Old entry, remove.
1721                         (gnus-score-set 'touched '(t) alist)
1722                         (setcdr entries (cdr rest))
1723                         (setq rest entries))))
1724                     (setq entries rest)))))
1725             (setq articles (cdr articles)))))))
1726   nil)
1727
1728 (defun gnus-score-thread (scores header now expire &optional trace)
1729   (gnus-score-followup scores header now expire trace t))
1730
1731 (defun gnus-score-followup (scores header now expire &optional trace thread)
1732   ;; Insert the unique article headers in the buffer.
1733   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1734         (current-score-file gnus-current-score-file)
1735         (all-scores scores)
1736         ;; gnus-score-index is used as a free variable.
1737         alike last this art entries alist articles
1738         new news)
1739
1740     ;; Change score file to the adaptive score file.  All entries that
1741     ;; this function makes will be put into this file.
1742     (save-excursion
1743       (set-buffer gnus-summary-buffer)
1744       (gnus-score-load-file
1745        (or gnus-newsgroup-adaptive-score-file
1746            (gnus-score-file-name
1747             gnus-newsgroup-name gnus-adaptive-file-suffix))))
1748
1749     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1750           articles gnus-scores-articles)
1751
1752     (erase-buffer)
1753     (while articles
1754       (setq art (car articles)
1755             this (aref (car art) gnus-score-index)
1756             articles (cdr articles))
1757       (if (equal last this)
1758           (push art alike)
1759         (when last
1760           (insert last ?\n)
1761           (put-text-property (1- (point)) (point) 'articles alike))
1762         (setq alike (list art)
1763               last this)))
1764     (when last                          ; Bwadr, duplicate code.
1765       (insert last ?\n)
1766       (put-text-property (1- (point)) (point) 'articles alike))
1767
1768     ;; Find matches.
1769     (while scores
1770       (setq alist (car scores)
1771             scores (cdr scores)
1772             entries (assoc header alist))
1773       (while (cdr entries)              ;First entry is the header index.
1774         (let* ((rest (cdr entries))
1775                (kill (car rest))
1776                (match (nth 0 kill))
1777                (type (or (nth 3 kill) 's))
1778                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1779                (date (nth 2 kill))
1780                (found nil)
1781                (mt (aref (symbol-name type) 0))
1782                (case-fold-search
1783                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1784                (dmt (downcase mt))
1785                (search-func
1786                 (cond ((= dmt ?r) 're-search-forward)
1787                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1788                       (t (error "Illegal match type: %s" type))))
1789                arts art)
1790           (goto-char (point-min))
1791           (if (= dmt ?e)
1792               (while (funcall search-func match nil t)
1793                 (and (= (progn (beginning-of-line) (point))
1794                         (match-beginning 0))
1795                      (= (progn (end-of-line) (point))
1796                         (match-end 0))
1797                      (progn
1798                        (setq found (setq arts (get-text-property
1799                                                (point) 'articles)))
1800                        ;; Found a match, update scores.
1801                        (while arts
1802                          (setq art (car arts)
1803                                arts (cdr arts))
1804                          (gnus-score-add-followups
1805                           (car art) score all-scores thread))))
1806                 (end-of-line))
1807             (while (funcall search-func match nil t)
1808               (end-of-line)
1809               (setq found (setq arts (get-text-property (point) 'articles)))
1810               ;; Found a match, update scores.
1811               (while (setq art (pop arts))
1812                 (when (setq new (gnus-score-add-followups
1813                                  (car art) score all-scores thread))
1814                   (push new news)))))
1815           ;; Update expire date
1816           (cond ((null date))           ;Permanent entry.
1817                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1818                  (gnus-score-set 'touched '(t) alist)
1819                  (setcar (nthcdr 2 kill) now))
1820                 ((and expire (< date expire)) ;Old entry, remove.
1821                  (gnus-score-set 'touched '(t) alist)
1822                  (setcdr entries (cdr rest))
1823                  (setq rest entries)))
1824           (setq entries rest))))
1825     ;; We change the score file back to the previous one.
1826     (save-excursion
1827       (set-buffer gnus-summary-buffer)
1828       (gnus-score-load-file current-score-file))
1829     (list (cons "references" news))))
1830
1831 (defun gnus-score-add-followups (header score scores &optional thread)
1832   "Add a score entry to the adapt file."
1833   (save-excursion
1834     (set-buffer gnus-summary-buffer)
1835     (let* ((id (mail-header-id header))
1836            (scores (car scores))
1837            entry dont)
1838       ;; Don't enter a score if there already is one.
1839       (while (setq entry (pop scores))
1840         (and (equal "references" (car entry))
1841              (or (null (nth 3 (cadr entry)))
1842                  (eq 's (nth 3 (cadr entry))))
1843              (assoc id entry)
1844              (setq dont t)))
1845       (unless dont
1846         (gnus-summary-score-entry
1847          (if thread "thread" "references")
1848          id 's score (current-time-string) nil t)))))
1849
1850 (defun gnus-score-string (score-list header now expire &optional trace)
1851   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1852   ;; Update matching entries to NOW and remove unmatched entries older
1853   ;; than EXPIRE.
1854
1855   ;; Insert the unique article headers in the buffer.
1856   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1857         ;; gnus-score-index is used as a free variable.
1858         (simplify (and gnus-score-thread-simplify
1859                        (string= "subject" header)))
1860         alike last this art entries alist articles
1861         fuzzies arts words kill)
1862
1863     ;; Sorting the articles costs os O(N*log N) but will allow us to
1864     ;; only match with each unique header.  Thus the actual matching
1865     ;; will be O(M*U) where M is the number of strings to match with,
1866     ;; and U is the number of unique headers.  It is assumed (but
1867     ;; untested) this will be a net win because of the large constant
1868     ;; factor involved with string matching.
1869     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1870           articles gnus-scores-articles)
1871
1872     (erase-buffer)
1873     (while (setq art (pop articles))
1874       (setq this (aref (car art) gnus-score-index))
1875       (if simplify
1876           (setq this (gnus-map-function gnus-simplify-subject-functions this)))
1877       (if (equal last this)
1878           ;; O(N*H) cons-cells used here, where H is the number of
1879           ;; headers.
1880           (push art alike)
1881         (when last
1882           ;; Insert the line, with a text property on the
1883           ;; terminating newline referring to the articles with
1884           ;; this line.
1885           (insert last ?\n)
1886           (put-text-property (1- (point)) (point) 'articles alike))
1887         (setq alike (list art)
1888               last this)))
1889     (when last                          ; Bwadr, duplicate code.
1890       (insert last ?\n)
1891       (put-text-property (1- (point)) (point) 'articles alike))
1892
1893     ;; Go through all the score alists and pick out the entries
1894     ;; for this header.
1895     (while score-list
1896       (setq alist (pop score-list)
1897             ;; There's only one instance of this header for
1898             ;; each score alist.
1899             entries (assoc header alist))
1900       (while (cdr entries)              ;First entry is the header index.
1901         (let* ((kill (cadr entries))
1902                (type (or (nth 3 kill) 's))
1903                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1904                (date (nth 2 kill))
1905                (found nil)
1906                (mt (aref (symbol-name type) 0))
1907                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
1908                (dmt (downcase mt))
1909                                         ; Assume user already simplified regexp and fuzzies
1910                (match (if (and simplify (not (memq dmt '(?f ?r))))
1911                           (gnus-map-function
1912                            gnus-simplify-subject-functions
1913                            (nth 0 kill))
1914                         (nth 0 kill)))
1915                (search-func
1916                 (cond ((= dmt ?r) 're-search-forward)
1917                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1918                       ((= dmt ?w) nil)
1919                       (t (error "Illegal match type: %s" type)))))
1920           (cond
1921            ;; Fuzzy matches.  We save these for later.
1922            ((= dmt ?f)
1923             (push (cons entries alist) fuzzies)
1924             (setq entries (cdr entries)))
1925            ;; Word matches.  Save these for even later.
1926            ((= dmt ?w)
1927             (push (cons entries alist) words)
1928             (setq entries (cdr entries)))
1929            ;; Exact matches.
1930            ((= dmt ?e)
1931             ;; Do exact matching.
1932             (goto-char (point-min))
1933             (while (and (not (eobp))
1934                         (funcall search-func match nil t))
1935               ;; Is it really exact?
1936               (and (eolp)
1937                    (= (gnus-point-at-bol) (match-beginning 0))
1938                    ;; Yup.
1939                    (progn
1940                      (setq found (setq arts (get-text-property
1941                                              (point) 'articles)))
1942                      ;; Found a match, update scores.
1943                      (if trace
1944                          (while (setq art (pop arts))
1945                            (setcdr art (+ score (cdr art)))
1946                            (push
1947                             (cons
1948                              (car-safe (rassq alist gnus-score-cache))
1949                              kill)
1950                             gnus-score-trace))
1951                        (while (setq art (pop arts))
1952                          (setcdr art (+ score (cdr art)))))))
1953               (forward-line 1))
1954             ;; Update expiry date
1955             (if trace
1956                 (setq entries (cdr entries))
1957               (cond
1958                ;; Permanent entry.
1959                ((null date)
1960                 (setq entries (cdr entries)))
1961                ;; We have a match, so we update the date.
1962                ((and found gnus-update-score-entry-dates)
1963                 (gnus-score-set 'touched '(t) alist)
1964                 (setcar (nthcdr 2 kill) now)
1965                 (setq entries (cdr entries)))
1966                ;; This entry has expired, so we remove it.
1967                ((and expire (< date expire))
1968                 (gnus-score-set 'touched '(t) alist)
1969                 (setcdr entries (cddr entries)))
1970                ;; No match; go to next entry.
1971                (t
1972                 (setq entries (cdr entries))))))
1973            ;; Regexp and substring matching.
1974            (t
1975             (goto-char (point-min))
1976             (when (string= match "")
1977               (setq match "\n"))
1978             (while (and (not (eobp))
1979                         (funcall search-func match nil t))
1980               (goto-char (match-beginning 0))
1981               (end-of-line)
1982               (setq found (setq arts (get-text-property (point) 'articles)))
1983               ;; Found a match, update scores.
1984               (if trace
1985                   (while (setq art (pop arts))
1986                     (setcdr art (+ score (cdr art)))
1987                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1988                           gnus-score-trace))
1989                 (while (setq art (pop arts))
1990                   (setcdr art (+ score (cdr art)))))
1991               (forward-line 1))
1992             ;; Update expiry date
1993             (if trace
1994                 (setq entries (cdr entries))
1995               (cond
1996                ;; Permanent entry.
1997                ((null date)
1998                 (setq entries (cdr entries)))
1999                ;; We have a match, so we update the date.
2000                ((and found gnus-update-score-entry-dates)
2001                 (gnus-score-set 'touched '(t) alist)
2002                 (setcar (nthcdr 2 kill) now)
2003                 (setq entries (cdr entries)))
2004                ;; This entry has expired, so we remove it.
2005                ((and expire (< date expire))
2006                 (gnus-score-set 'touched '(t) alist)
2007                 (setcdr entries (cddr entries)))
2008                ;; No match; go to next entry.
2009                (t
2010                 (setq entries (cdr entries))))))))))
2011
2012     ;; Find fuzzy matches.
2013     (when fuzzies
2014       ;; Simplify the entire buffer for easy matching.
2015       (gnus-simplify-buffer-fuzzy)
2016       (while (setq kill (cadaar fuzzies))
2017         (let* ((match (nth 0 kill))
2018                (type (nth 3 kill))
2019                (score (or (nth 1 kill) gnus-score-interactive-default-score))
2020                (date (nth 2 kill))
2021                (mt (aref (symbol-name type) 0))
2022                (case-fold-search (not (= mt ?F)))
2023                found)
2024           (goto-char (point-min))
2025           (while (and (not (eobp))
2026                       (search-forward match nil t))
2027             (when (and (= (gnus-point-at-bol) (match-beginning 0))
2028                        (eolp))
2029               (setq found (setq arts (get-text-property (point) 'articles)))
2030               (if trace
2031                   (while (setq art (pop arts))
2032                     (setcdr art (+ score (cdr art)))
2033                     (push (cons
2034                            (car-safe (rassq (cdar fuzzies) gnus-score-cache))
2035                            kill)
2036                           gnus-score-trace))
2037                 ;; Found a match, update scores.
2038                 (while (setq art (pop arts))
2039                   (setcdr art (+ score (cdr art))))))
2040             (forward-line 1))
2041           ;; Update expiry date
2042           (if (not trace)
2043               (cond
2044                ;; Permanent.
2045                ((null date)
2046                 )
2047                ;; Match, update date.
2048                ((and found gnus-update-score-entry-dates)
2049                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2050                 (setcar (nthcdr 2 kill) now))
2051                ;; Old entry, remove.
2052                ((and expire (< date expire))
2053                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2054                 (setcdr (caar fuzzies) (cddaar fuzzies)))))
2055           (setq fuzzies (cdr fuzzies)))))
2056
2057     (when words
2058       ;; Enter all words into the hashtb.
2059       (let ((hashtb (gnus-make-hashtable
2060                      (* 10 (count-lines (point-min) (point-max))))))
2061         (gnus-enter-score-words-into-hashtb hashtb)
2062         (while (setq kill (cadaar words))
2063           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
2064                  (date (nth 2 kill))
2065                  found)
2066             (when (setq arts (intern-soft (nth 0 kill) hashtb))
2067               (setq arts (symbol-value arts))
2068               (setq found t)
2069               (if trace
2070                   (while (setq art (pop arts))
2071                     (setcdr art (+ score (cdr art)))
2072                     (push (cons
2073                            (car-safe (rassq (cdar words) gnus-score-cache))
2074                            kill)
2075                           gnus-score-trace))
2076                 ;; Found a match, update scores.
2077                 (while (setq art (pop arts))
2078                   (setcdr art (+ score (cdr art))))))
2079             ;; Update expiry date
2080             (if (not trace)
2081                 (cond
2082                  ;; Permanent.
2083                  ((null date)
2084                   )
2085                  ;; Match, update date.
2086                  ((and found gnus-update-score-entry-dates)
2087                   (gnus-score-set 'touched '(t) (cdar words))
2088                   (setcar (nthcdr 2 kill) now))
2089                  ;; Old entry, remove.
2090                  ((and expire (< date expire))
2091                   (gnus-score-set 'touched '(t) (cdar words))
2092                   (setcdr (caar words) (cddaar words)))))
2093             (setq words (cdr words))))))
2094     nil))
2095
2096 (defun gnus-enter-score-words-into-hashtb (hashtb)
2097   ;; Find all the words in the buffer and enter them into
2098   ;; the hashtable.
2099   (let ((syntab (syntax-table))
2100         word val)
2101     (goto-char (point-min))
2102     (unwind-protect
2103         (progn
2104           (set-syntax-table gnus-adaptive-word-syntax-table)
2105           (while (re-search-forward "\\b\\w+\\b" nil t)
2106             (setq val
2107                   (gnus-gethash
2108                    (setq word (downcase (buffer-substring
2109                                          (match-beginning 0) (match-end 0))))
2110                    hashtb))
2111             (gnus-sethash
2112              word
2113              (append (get-text-property (gnus-point-at-eol) 'articles) val)
2114              hashtb)))
2115       (set-syntax-table syntab))
2116     ;; Make all the ignorable words ignored.
2117     (let ((ignored (append gnus-ignored-adaptive-words
2118                            (if gnus-adaptive-word-no-group-words
2119                                (message-tokenize-header
2120                                 (gnus-group-real-name gnus-newsgroup-name)
2121                                 "."))
2122                            gnus-default-ignored-adaptive-words)))
2123       (while ignored
2124         (gnus-sethash (pop ignored) nil hashtb)))))
2125
2126 (defun gnus-score-string< (a1 a2)
2127   ;; Compare headers in articles A2 and A2.
2128   ;; The header index used is the free variable `gnus-score-index'.
2129   (string-lessp (aref (car a1) gnus-score-index)
2130                 (aref (car a2) gnus-score-index)))
2131
2132 (defun gnus-current-score-file-nondirectory (&optional score-file)
2133   (let ((score-file (or score-file gnus-current-score-file)))
2134     (if score-file
2135         (gnus-short-group-name (file-name-nondirectory score-file))
2136       "none")))
2137
2138 (defun gnus-score-adaptive ()
2139   "Create adaptive score rules for this newsgroup."
2140   (when gnus-newsgroup-adaptive
2141     ;; We change the score file to the adaptive score file.
2142     (save-excursion
2143       (set-buffer gnus-summary-buffer)
2144       (gnus-score-load-file
2145        (or gnus-newsgroup-adaptive-score-file
2146            (gnus-home-score-file gnus-newsgroup-name t)
2147            (gnus-score-file-name
2148             gnus-newsgroup-name gnus-adaptive-file-suffix))))
2149     ;; Perform ordinary line scoring.
2150     (when (or (not (listp gnus-newsgroup-adaptive))
2151               (memq 'line gnus-newsgroup-adaptive))
2152       (save-excursion
2153         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
2154                (alist malist)
2155                (date (current-time-string))
2156                (data gnus-newsgroup-data)
2157                elem headers match func)
2158           ;; First we transform the adaptive rule alist into something
2159           ;; that's faster to process.
2160           (while malist
2161             (setq elem (car malist))
2162             (when (symbolp (car elem))
2163               (setcar elem (symbol-value (car elem))))
2164             (setq elem (cdr elem))
2165             (while elem
2166               (when (fboundp
2167                      (setq func
2168                            (intern
2169                             (concat "mail-header-"
2170                                     (if (eq (caar elem) 'followup)
2171                                         "message-id"
2172                                       (downcase (symbol-name (caar elem))))))))
2173                 (setcdr (car elem)
2174                         (cons (if (eq (caar elem) 'followup)
2175                                   "references"
2176                                 (symbol-name (caar elem)))
2177                               (cdar elem)))
2178                 (setcar (car elem)
2179                         `(lambda (h)
2180                            (,func h))))
2181               (setq elem (cdr elem)))
2182             (setq malist (cdr malist)))
2183           ;; Then we score away.
2184           (while data
2185             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2186             (if (or (not elem)
2187                     (gnus-data-pseudo-p (car data)))
2188                 ()
2189               (when (setq headers (gnus-data-header (car data)))
2190                 (while elem
2191                   (setq match (funcall (caar elem) headers))
2192                   (gnus-summary-score-entry
2193                    (nth 1 (car elem)) match
2194                    (cond
2195                     ((numberp match)
2196                      '=)
2197                     ((equal (nth 1 (car elem)) "date")
2198                      'a)
2199                     (t
2200                      ;; Whether we use substring or exact matches is
2201                      ;; controlled here.
2202                      (if (or (not gnus-score-exact-adapt-limit)
2203                              (< (length match) gnus-score-exact-adapt-limit))
2204                          'e
2205                        (if (equal (nth 1 (car elem)) "subject")
2206                            'f 's))))
2207                    (nth 2 (car elem)) date nil t)
2208                   (setq elem (cdr elem)))))
2209             (setq data (cdr data))))))
2210
2211     ;; Perform adaptive word scoring.
2212     (when (and (listp gnus-newsgroup-adaptive)
2213                (memq 'word gnus-newsgroup-adaptive))
2214       (with-temp-buffer
2215         (let* ((hashtb (gnus-make-hashtable 1000))
2216                (date (date-to-day (current-time-string)))
2217                (data gnus-newsgroup-data)
2218                (syntab (syntax-table))
2219                word d score val)
2220           (unwind-protect
2221               (progn
2222                 (set-syntax-table gnus-adaptive-word-syntax-table)
2223                 ;; Go through all articles.
2224                 (while (setq d (pop data))
2225                   (when (and
2226                          (not (gnus-data-pseudo-p d))
2227                          (setq score
2228                                (cdr (assq
2229                                      (gnus-data-mark d)
2230                                      gnus-adaptive-word-score-alist))))
2231                     ;; This article has a mark that should lead to
2232                     ;; adaptive word rules, so we insert the subject
2233                     ;; and find all words in that string.
2234                     (insert (mail-header-subject (gnus-data-header d)))
2235                     (downcase-region (point-min) (point-max))
2236                     (goto-char (point-min))
2237                     (while (re-search-forward "\\b\\w+\\b" nil t)
2238                       ;; Put the word and score into the hashtb.
2239                       (setq val (gnus-gethash (setq word (match-string 0))
2240                                               hashtb))
2241                       (setq val (+ score (or val 0)))
2242                       (if (and gnus-adaptive-word-minimum
2243                                (< val gnus-adaptive-word-minimum))
2244                           (setq val gnus-adaptive-word-minimum))
2245                       (gnus-sethash word val hashtb))
2246                     (erase-buffer))))
2247             (set-syntax-table syntab))
2248           ;; Make all the ignorable words ignored.
2249           (let ((ignored (append gnus-ignored-adaptive-words
2250                                  (if gnus-adaptive-word-no-group-words
2251                                      (message-tokenize-header
2252                                       (gnus-group-real-name 
2253                                        gnus-newsgroup-name)
2254                                       "."))
2255                                  gnus-default-ignored-adaptive-words)))
2256             (while ignored
2257               (gnus-sethash (pop ignored) nil hashtb)))
2258           ;; Now we have all the words and scores, so we
2259           ;; add these rules to the ADAPT file.
2260           (set-buffer gnus-summary-buffer)
2261           (mapatoms
2262            (lambda (word)
2263              (when (symbol-value word)
2264                (gnus-summary-score-entry
2265                 "subject" (symbol-name word) 'w (symbol-value word)
2266                 date nil t)))
2267            hashtb))))))
2268
2269 (defun gnus-score-edit-done ()
2270   (let ((bufnam (buffer-file-name (current-buffer)))
2271         (winconf gnus-prev-winconf))
2272     (when winconf
2273       (set-window-configuration winconf))
2274     (gnus-score-remove-from-cache bufnam)
2275     (gnus-score-load-file bufnam)))
2276
2277 (defun gnus-score-find-trace ()
2278   "Find all score rules that applies to the current article."
2279   (interactive)
2280   (let ((old-scored gnus-newsgroup-scored))
2281     (let ((gnus-newsgroup-headers
2282            (list (gnus-summary-article-header)))
2283           (gnus-newsgroup-scored nil)
2284           trace)
2285       (save-excursion
2286         (nnheader-set-temp-buffer "*Score Trace*"))
2287       (setq gnus-score-trace nil)
2288       (gnus-possibly-score-headers 'trace)
2289       (if (not (setq trace gnus-score-trace))
2290           (gnus-error
2291            1 "No score rules apply to the current article (default score %d)."
2292            gnus-summary-default-score)
2293         (set-buffer "*Score Trace*")
2294         (while trace
2295           (insert (format "%S  ->  %s\n" (cdar trace)
2296                           (if (caar trace)
2297                               (file-name-nondirectory (caar trace))
2298                             "(non-file rule)")))
2299           (setq trace (cdr trace)))
2300         (goto-char (point-min))
2301         (gnus-configure-windows 'score-trace)))
2302     (set-buffer gnus-summary-buffer)
2303     (setq gnus-newsgroup-scored old-scored)))
2304
2305 (defun gnus-score-find-favourite-words ()
2306   "List words used in scoring."
2307   (interactive)
2308   (let ((alists (gnus-score-load-files (gnus-all-score-files)))
2309         alist rule rules kill)
2310     ;; Go through all the score alists for this group
2311     ;; and find all `w' rules.
2312     (while (setq alist (pop alists))
2313       (while (setq rule (pop alist))
2314         (when (and (stringp (car rule))
2315                    (equal "subject" (downcase (pop rule))))
2316           (while (setq kill (pop rule))
2317             (when (memq (nth 3 kill) '(w W word Word))
2318               (push (cons (or (nth 1 kill)
2319                               gnus-score-interactive-default-score)
2320                           (car kill))
2321                     rules))))))
2322     (setq rules (sort rules (lambda (r1 r2)
2323                               (string-lessp (cdr r1) (cdr r2)))))
2324     ;; Add up words that have appeared several times.
2325     (let ((r rules))
2326       (while (cdr r)
2327         (if (equal (cdar r) (cdadr r))
2328             (progn
2329               (setcar (car r) (+ (caar r) (caadr r)))
2330               (setcdr r (cddr r)))
2331           (pop r))))
2332     ;; Insert the words.
2333     (nnheader-set-temp-buffer "*Score Words*")
2334     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2335         (gnus-error 3 "No word score rules")
2336       (while rules
2337         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2338         (pop rules))
2339       (goto-char (point-min))
2340       (gnus-configure-windows 'score-words))))
2341
2342 (defun gnus-summary-rescore ()
2343   "Redo the entire scoring process in the current summary."
2344   (interactive)
2345   (gnus-score-save)
2346   (setq gnus-score-cache nil)
2347   (setq gnus-newsgroup-scored nil)
2348   (gnus-possibly-score-headers)
2349   (gnus-score-update-all-lines))
2350
2351 (defun gnus-score-flush-cache ()
2352   "Flush the cache of score files."
2353   (interactive)
2354   (gnus-score-save)
2355   (setq gnus-score-cache nil
2356         gnus-score-alist nil
2357         gnus-short-name-score-file-cache nil)
2358   (gnus-message 6 "The score cache is now flushed"))
2359
2360 (gnus-add-shutdown 'gnus-score-close 'gnus)
2361
2362 (defvar gnus-score-file-alist-cache nil)
2363
2364 (defun gnus-score-close ()
2365   "Clear all internal score variables."
2366   (setq gnus-score-cache nil
2367         gnus-internal-global-score-files nil
2368         gnus-score-file-list nil
2369         gnus-score-file-alist-cache nil))
2370
2371 ;; Summary score marking commands.
2372
2373 (defun gnus-summary-raise-same-subject-and-select (score)
2374   "Raise articles which has the same subject with SCORE and select the next."
2375   (interactive "p")
2376   (let ((subject (gnus-summary-article-subject)))
2377     (gnus-summary-raise-score score)
2378     (while (gnus-summary-find-subject subject)
2379       (gnus-summary-raise-score score))
2380     (gnus-summary-next-article t)))
2381
2382 (defun gnus-summary-raise-same-subject (score)
2383   "Raise articles which has the same subject with SCORE."
2384   (interactive "p")
2385   (let ((subject (gnus-summary-article-subject)))
2386     (gnus-summary-raise-score score)
2387     (while (gnus-summary-find-subject subject)
2388       (gnus-summary-raise-score score))
2389     (gnus-summary-next-subject 1 t)))
2390
2391 (defun gnus-score-default (level)
2392   (if level (prefix-numeric-value level)
2393     gnus-score-interactive-default-score))
2394
2395 (defun gnus-summary-raise-thread (&optional score)
2396   "Raise the score of the articles in the current thread with SCORE."
2397   (interactive "P")
2398   (setq score (gnus-score-default score))
2399   (let (e)
2400     (save-excursion
2401       (let ((articles (gnus-summary-articles-in-thread)))
2402         (while articles
2403           (gnus-summary-goto-subject (car articles))
2404           (gnus-summary-raise-score score)
2405           (setq articles (cdr articles))))
2406       (setq e (point)))
2407     (let ((gnus-summary-check-current t))
2408       (unless (zerop (gnus-summary-next-subject 1 t))
2409         (goto-char e))))
2410   (gnus-summary-recenter)
2411   (gnus-summary-position-point)
2412   (gnus-set-mode-line 'summary))
2413
2414 (defun gnus-summary-lower-same-subject-and-select (score)
2415   "Raise articles which has the same subject with SCORE and select the next."
2416   (interactive "p")
2417   (gnus-summary-raise-same-subject-and-select (- score)))
2418
2419 (defun gnus-summary-lower-same-subject (score)
2420   "Raise articles which has the same subject with SCORE."
2421   (interactive "p")
2422   (gnus-summary-raise-same-subject (- score)))
2423
2424 (defun gnus-summary-lower-thread (&optional score)
2425   "Lower score of articles in the current thread with SCORE."
2426   (interactive "P")
2427   (gnus-summary-raise-thread (- (1- (gnus-score-default score)))))
2428
2429 ;;; Finding score files.
2430
2431 (defun gnus-score-score-files (group)
2432   "Return a list of all possible score files."
2433   ;; Search and set any global score files.
2434   (when gnus-global-score-files
2435     (unless gnus-internal-global-score-files
2436       (gnus-score-search-global-directories gnus-global-score-files)))
2437   ;; Fix the kill-file dir variable.
2438   (setq gnus-kill-files-directory
2439         (file-name-as-directory gnus-kill-files-directory))
2440   ;; If we can't read it, there are no score files.
2441   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2442       (setq gnus-score-file-list nil)
2443     (if (not (gnus-use-long-file-name 'not-score))
2444         ;; We do not use long file names, so we have to do some
2445         ;; directory traversing.
2446         (setq gnus-score-file-list
2447               (cons nil
2448                     (or gnus-short-name-score-file-cache
2449                         (prog2
2450                             (gnus-message 6 "Finding all score files...")
2451                             (setq gnus-short-name-score-file-cache
2452                                   (gnus-score-score-files-1
2453                                    gnus-kill-files-directory))
2454                           (gnus-message 6 "Finding all score files...done")))))
2455       ;; We want long file names.
2456       (when (or (not gnus-score-file-list)
2457                 (not (car gnus-score-file-list))
2458                 (gnus-file-newer-than gnus-kill-files-directory
2459                                       (car gnus-score-file-list)))
2460         (setq gnus-score-file-list
2461               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2462                     (nreverse
2463                      (directory-files
2464                       gnus-kill-files-directory t
2465                       (gnus-score-file-regexp)))))))
2466     (cdr gnus-score-file-list)))
2467
2468 (defun gnus-score-score-files-1 (dir)
2469   "Return all possible score files under DIR."
2470   (let ((files (list (expand-file-name dir)))
2471         (regexp (gnus-score-file-regexp))
2472         (case-fold-search nil)
2473         seen out file)
2474     (while (setq file (pop files))
2475       (cond
2476        ;; Ignore "." and "..".
2477        ((member (file-name-nondirectory file) '("." ".."))
2478         nil)
2479        ;; Add subtrees of directory to also be searched.
2480        ((and (file-directory-p file)
2481              (not (member (file-truename file) seen)))
2482         (push (file-truename file) seen)
2483         (setq files (nconc (directory-files file t nil t) files)))
2484        ;; Add files to the list of score files.
2485        ((string-match regexp file)
2486         (push file out))))
2487     (or out
2488         ;; Return a dummy value.
2489         (list "~/News/this.file.does.not.exist.SCORE"))))
2490
2491 (defun gnus-score-file-regexp ()
2492   "Return a regexp that match all score files."
2493   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2494           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2495
2496 (defun gnus-score-find-bnews (group)
2497   "Return a list of score files for GROUP.
2498 The score files are those files in the ~/News/ directory which matches
2499 GROUP using BNews sys file syntax."
2500   (let* ((sfiles (append (gnus-score-score-files group)
2501                          gnus-internal-global-score-files))
2502          (kill-dir (file-name-as-directory
2503                     (expand-file-name gnus-kill-files-directory)))
2504          (klen (length kill-dir))
2505          (score-regexp (gnus-score-file-regexp))
2506          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2507          ofiles not-match regexp)
2508     (save-excursion
2509       (set-buffer (gnus-get-buffer-create "*gnus score files*"))
2510       (buffer-disable-undo (current-buffer))
2511       ;; Go through all score file names and create regexp with them
2512       ;; as the source.
2513       (while sfiles
2514         (erase-buffer)
2515         (insert (car sfiles))
2516         (goto-char (point-min))
2517         ;; First remove the suffix itself.
2518         (when (re-search-forward (concat "." score-regexp) nil t)
2519           (replace-match "" t t)
2520           (goto-char (point-min))
2521           (if (looking-at (regexp-quote kill-dir))
2522               ;; If the file name was just "SCORE", `klen' is one character
2523               ;; too much.
2524               (delete-char (min (1- (point-max)) klen))
2525             (goto-char (point-max))
2526             (search-backward "/")
2527             (delete-region (1+ (point)) (point-min)))
2528           ;; If short file names were used, we have to translate slashes.
2529           (goto-char (point-min))
2530           (let ((regexp (concat
2531                          "[/:" (if trans (char-to-string trans) "") "]")))
2532             (while (re-search-forward regexp nil t)
2533               (replace-match "." t t)))
2534           ;; Kludge to get rid of "nntp+" problems.
2535           (goto-char (point-min))
2536           (when (looking-at "nn[a-z]+\\+")
2537             (search-forward "+")
2538             (forward-char -1)
2539             (insert "\\")
2540             (forward-char 1))
2541           ;; Kludge to deal with "++".
2542           (while (search-forward "+" nil t)
2543             (replace-match "\\+" t t))
2544           ;; Translate "all" to ".*".
2545           (goto-char (point-min))
2546           (while (search-forward "all" nil t)
2547             (replace-match ".*" t t))
2548           (goto-char (point-min))
2549           ;; Deal with "not."s.
2550           (if (looking-at "not.")
2551               (progn
2552                 (setq not-match t)
2553                 (setq regexp (concat "^" (buffer-substring 5 (point-max)) "$")))
2554             (setq regexp (concat "^" (buffer-substring 1 (point-max)) "$"))
2555             (setq not-match nil))
2556           ;; Finally - if this resulting regexp matches the group name,
2557           ;; we add this score file to the list of score files
2558           ;; applicable to this group.
2559           (when (or (and not-match
2560                          (not (string-match regexp group)))
2561                     (and (not not-match)
2562                          (string-match regexp group)))
2563             (push (car sfiles) ofiles)))
2564         (setq sfiles (cdr sfiles)))
2565       (kill-buffer (current-buffer))
2566       ;; Slight kludge here - the last score file returned should be
2567       ;; the local score file, whether it exists or not.  This is so
2568       ;; that any score commands the user enters will go to the right
2569       ;; file, and not end up in some global score file.
2570       (let ((localscore (gnus-score-file-name group)))
2571         (setq ofiles (cons localscore (delete localscore ofiles))))
2572       (gnus-sort-score-files (nreverse ofiles)))))
2573
2574 (defun gnus-score-find-single (group)
2575   "Return list containing the score file for GROUP."
2576   (list (or gnus-newsgroup-adaptive-score-file
2577             (gnus-score-file-name group gnus-adaptive-file-suffix))
2578         (gnus-score-file-name group)))
2579
2580 (defun gnus-score-find-hierarchical (group)
2581   "Return list of score files for GROUP.
2582 This includes the score file for the group and all its parents."
2583   (let* ((prefix (gnus-group-real-prefix group))
2584          (all (list nil))
2585          (group (gnus-group-real-name group))
2586          (start 0))
2587     (while (string-match "\\." group (1+ start))
2588       (setq start (match-beginning 0))
2589       (push (substring group 0 start) all))
2590     (push group all)
2591     (setq all
2592           (nconc
2593            (mapcar (lambda (group)
2594                      (gnus-score-file-name group gnus-adaptive-file-suffix))
2595                    (setq all (nreverse all)))
2596            (mapcar 'gnus-score-file-name all)))
2597     (if (equal prefix "")
2598         all
2599       (mapcar
2600        (lambda (file)
2601          (nnheader-translate-file-chars
2602           (concat (file-name-directory file) prefix
2603                   (file-name-nondirectory file))))
2604        all))))
2605
2606 (defun gnus-score-file-rank (file)
2607   "Return a number that says how specific score FILE is.
2608 Destroys the current buffer."
2609   (if (member file gnus-internal-global-score-files)
2610       0
2611     (when (string-match
2612            (concat "^" (regexp-quote
2613                         (expand-file-name
2614                          (file-name-as-directory gnus-kill-files-directory))))
2615            file)
2616       (setq file (substring file (match-end 0))))
2617     (insert file)
2618     (goto-char (point-min))
2619     (let ((beg (point))
2620           elems)
2621       (while (re-search-forward "[./]" nil t)
2622         (push (buffer-substring beg (1- (point)))
2623               elems))
2624       (erase-buffer)
2625       (setq elems (delete "all" elems))
2626       (length elems))))
2627
2628 (defun gnus-sort-score-files (files)
2629   "Sort FILES so that the most general files come first."
2630   (with-temp-buffer
2631     (let ((alist
2632            (mapcar
2633             (lambda (file)
2634               (cons (inline (gnus-score-file-rank file)) file))
2635             files)))
2636       (mapcar
2637        (lambda (f) (cdr f))
2638        (sort alist 'car-less-than-car)))))
2639
2640 (defun gnus-score-find-alist (group)
2641   "Return list of score files for GROUP.
2642 The list is determined from the variable gnus-score-file-alist."
2643   (let ((alist gnus-score-file-multiple-match-alist)
2644         score-files)
2645     ;; if this group has been seen before, return the cached entry
2646     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2647         (cdr score-files)               ;ensures caching groups with no matches
2648       ;; handle the multiple match alist
2649       (while alist
2650         (when (string-match (caar alist) group)
2651           (setq score-files
2652                 (nconc score-files (copy-sequence (cdar alist)))))
2653         (setq alist (cdr alist)))
2654       (setq alist gnus-score-file-single-match-alist)
2655       ;; handle the single match alist
2656       (while alist
2657         (when (string-match (caar alist) group)
2658           ;; progn used just in case ("regexp") has no files
2659           ;; and score-files is still nil.  -sj
2660           ;; this can be construed as a "stop searching here" feature :>
2661           ;; and used to simplify regexps in the single-alist
2662           (setq score-files
2663                 (nconc score-files (copy-sequence (cdar alist))))
2664           (setq alist nil))
2665         (setq alist (cdr alist)))
2666       ;; cache the score files
2667       (push (cons group score-files) gnus-score-file-alist-cache)
2668       score-files)))
2669
2670 (defun gnus-all-score-files (&optional group)
2671   "Return a list of all score files for the current group."
2672   (let ((funcs gnus-score-find-score-files-function)
2673         (group (or group gnus-newsgroup-name))
2674         score-files)
2675     (when group
2676       ;; Make sure funcs is a list.
2677       (and funcs
2678            (not (listp funcs))
2679            (setq funcs (list funcs)))
2680       ;; Get the initial score files for this group.
2681       (when funcs
2682         (setq score-files (nreverse (gnus-score-find-alist group))))
2683       ;; Add any home adapt files.
2684       (let ((home (gnus-home-score-file group t)))
2685         (when home
2686           (push home score-files)
2687           (setq gnus-newsgroup-adaptive-score-file home)))
2688       ;; Check whether there is a `adapt-file' group parameter.
2689       (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2690         (when param-file
2691           (push param-file score-files)
2692           (setq gnus-newsgroup-adaptive-score-file param-file)))
2693       ;; Go through all the functions for finding score files (or actual
2694       ;; scores) and add them to a list.
2695       (while funcs
2696         (when (gnus-functionp (car funcs))
2697           (setq score-files
2698                 (nconc score-files (nreverse (funcall (car funcs) group)))))
2699         (setq funcs (cdr funcs)))
2700       ;; Add any home score files.
2701       (let ((home (gnus-home-score-file group)))
2702         (when home
2703           (push home score-files)))
2704       ;; Check whether there is a `score-file' group parameter.
2705       (let ((param-file (gnus-group-find-parameter group 'score-file)))
2706         (when param-file
2707           (push param-file score-files)))
2708       ;; Expand all files names.
2709       (let ((files score-files))
2710         (while files
2711           (when (stringp (car files))
2712             (setcar files (expand-file-name
2713                            (car files) gnus-kill-files-directory)))
2714           (pop files)))
2715       (setq score-files (nreverse score-files))
2716       ;; Remove any duplicate score files.
2717       (while (and score-files
2718                   (member (car score-files) (cdr score-files)))
2719         (pop score-files))
2720       (let ((files score-files))
2721         (while (cdr files)
2722           (if (member (cadr files) (cddr files))
2723               (setcdr files (cddr files))
2724             (pop files))))
2725       ;; Do the scoring if there are any score files for this group.
2726       score-files)))
2727
2728 (defun gnus-possibly-score-headers (&optional trace)
2729   "Do scoring if scoring is required."
2730   (let ((score-files (gnus-all-score-files)))
2731     (when score-files
2732       (gnus-score-headers score-files trace))))
2733
2734 (defun gnus-score-file-name (newsgroup &optional suffix)
2735   "Return the name of a score file for NEWSGROUP."
2736   (let ((suffix (or suffix gnus-score-file-suffix)))
2737     (nnheader-translate-file-chars
2738      (cond
2739       ((or (null newsgroup)
2740            (string-equal newsgroup ""))
2741        ;; The global score file is placed at top of the directory.
2742        (expand-file-name suffix gnus-kill-files-directory))
2743       ((gnus-use-long-file-name 'not-score)
2744        ;; Append ".SCORE" to newsgroup name.
2745        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2746                                  "." suffix)
2747                          gnus-kill-files-directory))
2748       (t
2749        ;; Place "SCORE" under the hierarchical directory.
2750        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2751                                  "/" suffix)
2752                          gnus-kill-files-directory))))))
2753
2754 (defun gnus-score-search-global-directories (files)
2755   "Scan all global score directories for score files."
2756   ;; Set the variable `gnus-internal-global-score-files' to all
2757   ;; available global score files.
2758   (interactive (list gnus-global-score-files))
2759   (let (out)
2760     (while files
2761       ;; #### /$ Unix-specific?
2762       (if (string-match "/$" (car files))
2763           (setq out (nconc (directory-files
2764                             (car files) t
2765                             (concat (gnus-score-file-regexp) "$"))))
2766         (push (car files) out))
2767       (setq files (cdr files)))
2768     (setq gnus-internal-global-score-files out)))
2769
2770 (defun gnus-score-default-fold-toggle ()
2771   "Toggle folding for new score file entries."
2772   (interactive)
2773   (setq gnus-score-default-fold (not gnus-score-default-fold))
2774   (if gnus-score-default-fold
2775       (gnus-message 1 "New score file entries will be case insensitive.")
2776     (gnus-message 1 "New score file entries will be case sensitive.")))
2777
2778 ;;; Home score file.
2779
2780 (defun gnus-home-score-file (group &optional adapt)
2781   "Return the home score file for GROUP.
2782 If ADAPT, return the home adaptive file instead."
2783   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2784         elem found)
2785     ;; Make sure we have a list.
2786     (unless (listp list)
2787       (setq list (list list)))
2788     ;; Go through the list and look for matches.
2789     (while (and (not found)
2790                 (setq elem (pop list)))
2791       (setq found
2792             (cond
2793              ;; Simple string.
2794              ((stringp elem)
2795               elem)
2796              ;; Function.
2797              ((gnus-functionp elem)
2798               (funcall elem group))
2799              ;; Regexp-file cons
2800              ((consp elem)
2801               (when (string-match (gnus-globalify-regexp (car elem)) group)
2802                 (replace-match (cadr elem) t nil group ))))))
2803     (when found
2804       (nnheader-concat gnus-kill-files-directory found))))
2805
2806 (defun gnus-hierarchial-home-score-file (group)
2807   "Return the score file of the top-level hierarchy of GROUP."
2808   (if (string-match "^[^.]+\\." group)
2809       (concat (match-string 0 group) gnus-score-file-suffix)
2810     ;; Group name without any dots.
2811     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2812             gnus-score-file-suffix)))
2813
2814 (defun gnus-hierarchial-home-adapt-file (group)
2815   "Return the adapt file of the top-level hierarchy of GROUP."
2816   (if (string-match "^[^.]+\\." group)
2817       (concat (match-string 0 group) gnus-adaptive-file-suffix)
2818     ;; Group name without any dots.
2819     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2820             gnus-adaptive-file-suffix)))
2821
2822 (defun gnus-current-home-score-file (group)
2823   "Return the \"current\" regular score file."
2824   (car (nreverse (gnus-score-find-alist group))))
2825
2826 ;;;
2827 ;;; Score decays
2828 ;;;
2829
2830 (defun gnus-decay-score (score)
2831   "Decay SCORE according to `gnus-score-decay-constant' and `gnus-score-decay-scale'."
2832   (floor
2833    (- score
2834       (* (if (< score 0) -1 1)
2835          (min (abs score)
2836               (max gnus-score-decay-constant
2837                    (* (abs score)
2838                       gnus-score-decay-scale)))))))
2839
2840 (defun gnus-decay-scores (alist day)
2841   "Decay non-permanent scores in ALIST."
2842   (let ((times (- (time-to-day (current-time)) day))
2843         kill entry updated score n)
2844     (unless (zerop times)               ;Done decays today already?
2845       (while (setq entry (pop alist))
2846         (when (stringp (car entry))
2847           (setq entry (cdr entry))
2848           (while (setq kill (pop entry))
2849             (when (nth 2 kill)
2850               (setq updated t)
2851               (setq score (or (nth 1 kill)
2852                               gnus-score-interactive-default-score)
2853                     n times)
2854               (while (natnump (decf n))
2855                 (setq score (funcall gnus-decay-score-function score)))
2856               (setcdr kill (cons score 
2857                                  (cdr (cdr kill)))))))))
2858     ;; Return whether this score file needs to be saved.  By Je-haysuss!
2859     updated))
2860
2861 (defun gnus-score-regexp-bad-p (regexp)
2862   "Test whether REGEXP is safe for Gnus scoring.
2863 A regexp is unsafe if it matches newline or a buffer boundary.
2864
2865 If the regexp is good, return nil.  If the regexp is bad, return a
2866 cons cell (SYM . STRING), where the symbol SYM is `new' or `bad'.
2867 In the `new' case, the string is a safe replacement for REGEXP.
2868 In the `bad' case, the string is a unsafe subexpression of REGEXP,
2869 and we do not have a simple replacement to suggest.
2870
2871 See `(Gnus)Scoring Tips' for examples of good regular expressions."
2872   (let (case-fold-search)
2873     (and
2874      ;; First, try a relatively fast necessary condition.
2875      ;; Notice ranges (like [^:] or [\t-\r]), \s>, \Sw, \W, \', \`:
2876      (string-match "\n\\|\\\\[SsW`']\\|\\[\\^\\|[\0-\n]-" regexp)
2877      ;; Now break the regexp into tokens, and check each:
2878      (let ((tail regexp)                ; remaining regexp to check
2879            tok                          ; current token
2880            bad                          ; nil, or bad subexpression
2881            new                          ; nil, or replacement regexp so far
2882            end)                         ; length of current token
2883        (while (and (not bad)
2884                    (string-match
2885                     "\\`\\(\\\\[sS]?.\\|\\[\\^?]?[^]]*]\\|[^\\]\\)"
2886                     tail))
2887          (setq end (match-end 0)
2888                tok (substring tail 0 end)
2889                tail (substring tail end))
2890          (if;; Is token `bad' (matching newline or buffer ends)?
2891              (or (member tok '("\n" "\\W" "\\`" "\\'"))
2892                  ;; This next handles "[...]", "\\s.", and "\\S.":
2893                  (and (> end 2) (string-match tok "\n")))
2894              (let ((newtok
2895                     ;; Try to suggest a replacement for tok ...
2896                     (cond ((string-equal tok "\\`") "^") ; or "\\(^\\)"
2897                           ((string-equal tok "\\'") "$") ; or "\\($\\)"
2898                           ((string-match "\\[\\^" tok) ; very common
2899                            (concat (substring tok 0 -1) "\n]")))))
2900                (if newtok
2901                    (setq new
2902                          (concat
2903                           (or new
2904                               ;; good prefix so far:
2905                               (substring regexp 0 (- (+ (length tail) end))))
2906                           newtok))
2907                  ;; No replacement idea, so give up:
2908                  (setq bad tok)))
2909            ;; tok is good, may need to extend new
2910            (and new (setq new (concat new tok)))))
2911        ;; Now return a value:
2912        (cond
2913         (bad (cons 'bad bad))
2914         (new (cons 'new new))
2915         ;; or nil
2916         )))))
2917
2918 (provide 'gnus-score)
2919
2920 ;;; gnus-score.el ends here