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