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