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