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