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