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