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