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