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