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