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