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