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