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