5cd60ddaabf0139418c291950173ca135ce699d4
[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                 (gnus-completing-read-with-default
684                  (symbol-name (car gnus-extra-headers)) ; default response
685                  "Score extra header"   ; prompt
686                  (mapcar (lambda (x)    ; completion list
687                            (cons (symbol-name x) x))
688                          gnus-extra-headers)
689                  nil                    ; no completion limit
690                  t))))                  ; require match
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 (completing-read "Header: "
917                                       gnus-header-index
918                                       (lambda (x) (fboundp (nth 2 x)))
919                                       t)
920                      (read-string "Match: ")
921                      (if (y-or-n-p "Use regexp match? ") 'r 's)
922                      (string-to-number (read-string "Score: "))))
923   (save-excursion
924     (unless (and (stringp match) (> (length match) 0))
925       (error "No match"))
926     (goto-char (point-min))
927     (let ((regexp (cond ((eq type 'f)
928                          (gnus-simplify-subject-fuzzy match))
929                         ((eq type 'r)
930                          match)
931                         ((eq type 'e)
932                          (concat "\\`" (regexp-quote match) "\\'"))
933                         (t
934                          (regexp-quote match)))))
935       (while (not (eobp))
936         (let ((content (gnus-summary-header header 'noerr extra))
937               (case-fold-search t))
938           (and content
939                (when (if (eq type 'f)
940                          (string-equal (gnus-simplify-subject-fuzzy content)
941                                        regexp)
942                        (string-match regexp content))
943                  (gnus-summary-raise-score score))))
944         (beginning-of-line 2))))
945   (gnus-set-mode-line 'summary))
946
947 (defun gnus-summary-score-crossposting (score date)
948   ;; Enter score file entry for current crossposting.
949   ;; SCORE is the score to add.
950   ;; DATE is the expire date.
951   (let ((xref (gnus-summary-header "xref"))
952         (start 0)
953         group)
954     (unless xref
955       (error "This article is not crossposted"))
956     (while (string-match " \\([^ \t]+\\):" xref start)
957       (setq start (match-end 0))
958       (when (not (string=
959                   (setq group
960                         (substring xref (match-beginning 1) (match-end 1)))
961                   gnus-newsgroup-name))
962         (gnus-summary-score-entry
963          "xref" (concat " " group ":") nil score date t)))))
964
965 \f
966 ;;;
967 ;;; Gnus Score Files
968 ;;;
969
970 ;; All score code written by Per Abrahamsen <abraham@iesd.auc.dk>.
971
972 (defun gnus-score-set-mark-below (score)
973   "Automatically mark articles with score below SCORE as read."
974   (interactive
975    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
976              (string-to-number (read-string "Mark below: ")))))
977   (setq score (or score gnus-summary-default-score 0))
978   (gnus-score-set 'mark (list score))
979   (gnus-score-set 'touched '(t))
980   (setq gnus-summary-mark-below score)
981   (gnus-score-update-lines))
982
983 (defun gnus-score-update-lines ()
984   "Update all lines in the summary buffer."
985   (save-excursion
986     (goto-char (point-min))
987     (while (not (eobp))
988       (gnus-summary-update-line)
989       (forward-line 1))))
990
991 (defun gnus-score-update-all-lines ()
992   "Update all lines in the summary buffer, even the hidden ones."
993   (save-excursion
994     (goto-char (point-min))
995     (let (hidden)
996       (while (not (eobp))
997         (when (gnus-summary-show-thread)
998           (push (point) hidden))
999         (gnus-summary-update-line)
1000         (forward-line 1))
1001       ;; Re-hide the hidden threads.
1002       (while hidden
1003         (goto-char (pop hidden))
1004         (gnus-summary-hide-thread)))))
1005
1006 (defun gnus-score-set-expunge-below (score)
1007   "Automatically expunge articles with score below SCORE."
1008   (interactive
1009    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
1010              (string-to-number (read-string "Set expunge below: ")))))
1011   (setq score (or score gnus-summary-default-score 0))
1012   (gnus-score-set 'expunge (list score))
1013   (gnus-score-set 'touched '(t)))
1014
1015 (defun gnus-score-followup-article (&optional score)
1016   "Add SCORE to all followups to the article in the current buffer."
1017   (interactive "P")
1018   (setq score (gnus-score-delta-default score))
1019   (when (gnus-buffer-live-p gnus-summary-buffer)
1020     (save-excursion
1021       (save-restriction
1022         (message-narrow-to-headers)
1023         (let ((id (mail-fetch-field "message-id")))
1024           (when id
1025             (set-buffer gnus-summary-buffer)
1026             (gnus-summary-score-entry
1027              "references" (concat id "[ \t]*$") 'r
1028              score (current-time-string) nil t)))))))
1029
1030 (defun gnus-score-followup-thread (&optional score)
1031   "Add SCORE to all later articles in the thread the current buffer is part of."
1032   (interactive "P")
1033   (setq score (gnus-score-delta-default score))
1034   (when (gnus-buffer-live-p gnus-summary-buffer)
1035     (save-excursion
1036       (save-restriction
1037         (goto-char (point-min))
1038         (let ((id (mail-fetch-field "message-id")))
1039           (when id
1040             (set-buffer gnus-summary-buffer)
1041             (gnus-summary-score-entry
1042              "references" id 's
1043              score (current-time-string))))))))
1044
1045 (defun gnus-score-set (symbol value &optional alist warn)
1046   ;; Set SYMBOL to VALUE in ALIST.
1047   (let* ((alist
1048           (or alist
1049               gnus-score-alist
1050               (gnus-newsgroup-score-alist)))
1051          (entry (assoc symbol alist)))
1052     (cond ((gnus-score-get 'read-only alist)
1053            ;; This is a read-only score file, so we do nothing.
1054            (when warn
1055              (gnus-message 4 "Note: read-only score file; entry discarded")))
1056           (entry
1057            (setcdr entry value))
1058           ((null alist)
1059            (error "Empty alist"))
1060           (t
1061            (setcdr alist
1062                    (cons (cons symbol value) (cdr alist)))))))
1063
1064 (defun gnus-summary-raise-score (n)
1065   "Raise the score of the current article by N."
1066   (interactive "p")
1067   (gnus-summary-set-score (+ (gnus-summary-article-score)
1068                              (or n gnus-score-interactive-default-score ))))
1069
1070 (defun gnus-summary-set-score (n)
1071   "Set the score of the current article to N."
1072   (interactive "p")
1073   (save-excursion
1074     (gnus-summary-show-thread)
1075     (let ((buffer-read-only nil))
1076       ;; Set score.
1077       (gnus-summary-update-mark
1078        (if (= n (or gnus-summary-default-score 0)) ?  ;Whitespace
1079          (if (< n (or gnus-summary-default-score 0))
1080              gnus-score-below-mark gnus-score-over-mark))
1081        'score))
1082     (let* ((article (gnus-summary-article-number))
1083            (score (assq article gnus-newsgroup-scored)))
1084       (if score (setcdr score n)
1085         (push (cons article n) gnus-newsgroup-scored)))
1086     (gnus-summary-update-line)))
1087
1088 (defun gnus-summary-current-score ()
1089   "Return the score of the current article."
1090   (interactive)
1091   (gnus-message 1 "%s" (gnus-summary-article-score)))
1092
1093 (defun gnus-score-change-score-file (file)
1094   "Change current score alist."
1095   (interactive
1096    (list (read-file-name "Change to score file: " gnus-kill-files-directory)))
1097   (gnus-score-load-file file)
1098   (gnus-set-mode-line 'summary))
1099
1100 (defvar gnus-score-edit-exit-function)
1101 (defun gnus-score-edit-current-scores (file)
1102   "Edit the current score alist."
1103   (interactive (list gnus-current-score-file))
1104   (if (not gnus-current-score-file)
1105       (error "No current score file")
1106     (let ((winconf (current-window-configuration)))
1107       (when (buffer-name gnus-summary-buffer)
1108         (gnus-score-save))
1109       (gnus-make-directory (file-name-directory file))
1110       (setq gnus-score-edit-buffer (find-file-noselect file))
1111       (gnus-configure-windows 'edit-score)
1112       (gnus-score-mode)
1113       (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1114       (make-local-variable 'gnus-prev-winconf)
1115       (setq gnus-prev-winconf winconf))
1116     (gnus-message
1117      4 (substitute-command-keys
1118         "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits"))))
1119
1120 (defun gnus-score-edit-all-score ()
1121   "Edit the all.SCORE file."
1122   (interactive)
1123   (find-file (gnus-score-file-name "all"))
1124   (gnus-score-mode)
1125   (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1126   (gnus-message
1127    4 (substitute-command-keys
1128       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
1129
1130 (defun gnus-score-edit-file (file)
1131   "Edit a score file."
1132   (interactive
1133    (list (read-file-name "Edit score file: " gnus-kill-files-directory)))
1134   (gnus-make-directory (file-name-directory file))
1135   (when (buffer-name gnus-summary-buffer)
1136     (gnus-score-save))
1137   (let ((winconf (current-window-configuration)))
1138     (setq gnus-score-edit-buffer (find-file-noselect file))
1139     (gnus-configure-windows 'edit-score)
1140     (gnus-score-mode)
1141     (setq gnus-score-edit-exit-function 'gnus-score-edit-done)
1142     (make-local-variable 'gnus-prev-winconf)
1143     (setq gnus-prev-winconf winconf))
1144   (gnus-message
1145    4 (substitute-command-keys
1146       "\\<gnus-score-mode-map>\\[gnus-score-edit-exit] to save edits")))
1147
1148 (defun gnus-score-edit-file-at-point (&optional format)
1149   "Edit score file at point in Score Trace buffers.
1150 If FORMAT, also format the current score file."
1151   (let* ((rule (save-excursion
1152                  (beginning-of-line)
1153                  (read (current-buffer))))
1154          (sep "[ \n\r\t]*")
1155          ;; Must be synced with `gnus-score-find-trace':
1156          (reg " -> +")
1157          (file (save-excursion
1158                  (end-of-line)
1159                  (if (and (re-search-backward reg (point-at-bol) t)
1160                           (re-search-forward  reg (point-at-eol) t))
1161                      (buffer-substring (point) (point-at-eol))
1162                    nil))))
1163     (if (or (not file)
1164             (string-match "\\<\\(non-file rule\\|A file\\)\\>" file)
1165             ;; (see `gnus-score-find-trace' and `gnus-score-advanced')
1166             (string= "" file))
1167         (gnus-error 3 "Can't find a score file in current line.")
1168       (gnus-score-edit-file file)
1169       (when format
1170         (gnus-score-pretty-print))
1171       (when (consp rule) ;; the rule exists
1172         (setq rule (mapconcat #'(lambda (obj)
1173                                   (regexp-quote (format "%S" obj)))
1174                               rule
1175                               sep))
1176         (goto-char (point-min))
1177         (re-search-forward rule nil t)
1178         ;; make it easy to use `kill-sexp':
1179         (goto-char (1- (match-beginning 0)))))))
1180
1181 (defun gnus-score-load-file (file)
1182   ;; Load score file FILE.  Returns a list a retrieved score-alists.
1183   (let* ((file (expand-file-name
1184                 (or (and (string-match
1185                           (concat "^" (regexp-quote
1186                                        (expand-file-name
1187                                         gnus-kill-files-directory)))
1188                           (expand-file-name file))
1189                          file)
1190                     (expand-file-name file gnus-kill-files-directory))))
1191          (cached (assoc file gnus-score-cache))
1192          (global (member file gnus-internal-global-score-files))
1193          lists alist)
1194     (if cached
1195         ;; The score file was already loaded.
1196         (setq alist (cdr cached))
1197       ;; We load the score file.
1198       (setq gnus-score-alist nil)
1199       (setq alist (gnus-score-load-score-alist file))
1200       ;; We add '(touched) to the alist to signify that it hasn't been
1201       ;; touched (yet).
1202       (unless (assq 'touched alist)
1203         (push (list 'touched nil) alist))
1204       ;; If it is a global score file, we make it read-only.
1205       (and global
1206            (not (assq 'read-only alist))
1207            (push (list 'read-only t) alist))
1208       (push (cons file alist) gnus-score-cache))
1209     (let ((a alist)
1210           found)
1211       (while a
1212         ;; Downcase all header names.
1213         (cond
1214          ((stringp (caar a))
1215           (setcar (car a) (downcase (caar a)))
1216           (setq found t))
1217          ;; Advanced scoring.
1218          ((consp (caar a))
1219           (setq found t)))
1220         (pop a))
1221       ;; If there are actual scores in the alist, we add it to the
1222       ;; return value of this function.
1223       (when found
1224         (setq lists (list alist))))
1225     ;; Treat the other possible atoms in the score alist.
1226     (let ((mark (car (gnus-score-get 'mark alist)))
1227           (expunge (car (gnus-score-get 'expunge alist)))
1228           (mark-and-expunge (car (gnus-score-get 'mark-and-expunge alist)))
1229           (files (gnus-score-get 'files alist))
1230           (exclude-files (gnus-score-get 'exclude-files alist))
1231           (orphan (car (gnus-score-get 'orphan alist)))
1232           (adapt (gnus-score-get 'adapt alist))
1233           (thread-mark-and-expunge
1234            (car (gnus-score-get 'thread-mark-and-expunge alist)))
1235           (adapt-file (car (gnus-score-get 'adapt-file alist)))
1236           (local (gnus-score-get 'local alist))
1237           (decay (car (gnus-score-get 'decay alist)))
1238           (eval (car (gnus-score-get 'eval alist))))
1239       ;; Perform possible decays.
1240       (when (and (if (stringp gnus-decay-scores)
1241                      (string-match gnus-decay-scores file)
1242                    gnus-decay-scores)
1243                  (or cached (file-exists-p file))
1244                  (or (not decay)
1245                      (gnus-decay-scores alist decay)))
1246         (gnus-score-set 'touched '(t) alist)
1247         (gnus-score-set 'decay (list (time-to-days (current-time))) alist))
1248       ;; We do not respect eval and files atoms from global score
1249       ;; files.
1250       (when (and files (not global))
1251         (setq lists (apply 'append lists
1252                            (mapcar 'gnus-score-load-file
1253                                    (if adapt-file (cons adapt-file files)
1254                                      files)))))
1255       (when (and eval (not global))
1256         (eval eval))
1257       ;; We then expand any exclude-file directives.
1258       (setq gnus-scores-exclude-files
1259             (nconc
1260              (apply
1261               'nconc
1262               (mapcar
1263                (lambda (sfile)
1264                  (list
1265                   (expand-file-name sfile (file-name-directory file))
1266                   (expand-file-name sfile gnus-kill-files-directory)))
1267                exclude-files))
1268              gnus-scores-exclude-files))
1269       (when local
1270         (with-current-buffer gnus-summary-buffer
1271           (while local
1272             (and (consp (car local))
1273                  (symbolp (caar local))
1274                  (progn
1275                    (make-local-variable (caar local))
1276                    (set (caar local) (nth 1 (car local)))))
1277             (setq local (cdr local)))))
1278       (when orphan
1279         (setq gnus-orphan-score orphan))
1280       (setq gnus-adaptive-score-alist
1281             (cond ((equal adapt '(t))
1282                    (setq gnus-newsgroup-adaptive t)
1283                    gnus-default-adaptive-score-alist)
1284                   ((equal adapt '(ignore))
1285                    (setq gnus-newsgroup-adaptive nil))
1286                   ((consp adapt)
1287                    (setq gnus-newsgroup-adaptive t)
1288                    adapt)
1289                   (t
1290                    gnus-default-adaptive-score-alist)))
1291       (setq gnus-thread-expunge-below
1292             (or thread-mark-and-expunge gnus-thread-expunge-below))
1293       (setq gnus-summary-mark-below
1294             (or mark mark-and-expunge gnus-summary-mark-below))
1295       (setq gnus-summary-expunge-below
1296             (or expunge mark-and-expunge gnus-summary-expunge-below))
1297       (setq gnus-newsgroup-adaptive-score-file
1298             (or adapt-file gnus-newsgroup-adaptive-score-file)))
1299     (setq gnus-current-score-file file)
1300     (setq gnus-score-alist alist)
1301     lists))
1302
1303 (defun gnus-score-load (file)
1304   ;; Load score FILE.
1305   (let ((cache (assoc file gnus-score-cache)))
1306     (if cache
1307         (setq gnus-score-alist (cdr cache))
1308       (setq gnus-score-alist nil)
1309       (gnus-score-load-score-alist file)
1310       (unless gnus-score-alist
1311         (setq gnus-score-alist (copy-alist '((touched nil)))))
1312       (push (cons file gnus-score-alist) gnus-score-cache))))
1313
1314 (defun gnus-score-remove-from-cache (file)
1315   (setq gnus-score-cache
1316         (delq (assoc file gnus-score-cache) gnus-score-cache)))
1317
1318 (defun gnus-score-load-score-alist (file)
1319   "Read score FILE."
1320   (let (alist)
1321     (if (not (file-readable-p file))
1322         ;; Couldn't read file.
1323         (setq gnus-score-alist nil)
1324       ;; Read file.
1325       (with-temp-buffer
1326         (let ((coding-system-for-read score-mode-coding-system))
1327           (insert-file-contents file))
1328         (goto-char (point-min))
1329         ;; Only do the loading if the score file isn't empty.
1330         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
1331           (setq alist
1332                 (condition-case ()
1333                     (read (current-buffer))
1334                   (error
1335                    (gnus-error 3.2 "Problem with score file %s" file))))))
1336       (cond
1337        ((and alist
1338              (atom alist))
1339         ;; Bogus score file.
1340         (error "Invalid syntax with score file %s" file))
1341        ((eq (car alist) 'setq)
1342         ;; This is an old-style score file.
1343         (setq gnus-score-alist (gnus-score-transform-old-to-new alist)))
1344        (t
1345         (setq gnus-score-alist alist)))
1346       ;; Check the syntax of the score file.
1347       (setq gnus-score-alist
1348             (gnus-score-check-syntax gnus-score-alist file)))))
1349
1350 (defun gnus-score-check-syntax (alist file)
1351   "Check the syntax of the score ALIST."
1352   (cond
1353    ((null alist)
1354     nil)
1355    ((not (consp alist))
1356     (gnus-message 1 "Score file is not a list: %s" file)
1357     (ding)
1358     nil)
1359    (t
1360     (let ((a alist)
1361           sr err s type)
1362       (while (and a (not err))
1363         (setq
1364          err
1365          (cond
1366           ((not (listp (car a)))
1367            (format "Invalid score element %s in %s" (car a) file))
1368           ((stringp (caar a))
1369            (cond
1370             ((not (listp (setq sr (cdar a))))
1371              (format "Invalid header match %s in %s" (nth 1 (car a)) file))
1372             (t
1373              (setq type (caar a))
1374              (while (and sr (not err))
1375                (setq s (pop sr))
1376                (setq
1377                 err
1378                 (cond
1379                  ((if (member (downcase type) '("lines" "chars"))
1380                       (not (numberp (car s)))
1381                     (not (stringp (car s))))
1382                   (format "Invalid match %s in %s" (car s) file))
1383                  ((and (cadr s) (not (integerp (cadr s))))
1384                   (format "Non-integer score %s in %s" (cadr s) file))
1385                  ((and (caddr s) (not (integerp (caddr s))))
1386                   (format "Non-integer date %s in %s" (caddr s) file))
1387                  ((and (cadddr s) (not (symbolp (cadddr s))))
1388                   (format "Non-symbol match type %s in %s" (cadddr s) file)))))
1389              err)))))
1390         (setq a (cdr a)))
1391       (if err
1392           (progn
1393             (ding)
1394             (gnus-message 3 err)
1395             (sit-for 2)
1396             nil)
1397         alist)))))
1398
1399 (defun gnus-score-transform-old-to-new (alist)
1400   (let* ((alist (nth 2 alist))
1401          out entry)
1402     (when (eq (car alist) 'quote)
1403       (setq alist (nth 1 alist)))
1404     (while alist
1405       (setq entry (car alist))
1406       (if (stringp (car entry))
1407           (let ((scor (cdr entry)))
1408             (push entry out)
1409             (while scor
1410               (setcar scor
1411                       (list (caar scor) (nth 2 (car scor))
1412                             (and (nth 3 (car scor))
1413                                  (date-to-day (nth 3 (car scor))))
1414                             (if (nth 1 (car scor)) 'r 's)))
1415               (setq scor (cdr scor))))
1416         (push (if (not (listp (cdr entry)))
1417                   (list (car entry) (cdr entry))
1418                 entry)
1419               out))
1420       (setq alist (cdr alist)))
1421     (cons (list 'touched t) (nreverse out))))
1422
1423 (defun gnus-score-save ()
1424   ;; Save all score information.
1425   (let ((cache gnus-score-cache)
1426         entry score file)
1427     (save-excursion
1428       (setq gnus-score-alist nil)
1429       (nnheader-set-temp-buffer " *Gnus Scores*")
1430       (while cache
1431         (current-buffer)
1432         (setq entry (pop cache)
1433               file (nnheader-translate-file-chars (car entry) t)
1434               score (cdr entry))
1435         (if (or (not (equal (gnus-score-get 'touched score) '(t)))
1436                 (gnus-score-get 'read-only score)
1437                 (and (file-exists-p file)
1438                      (not (file-writable-p file))))
1439             ()
1440           (setq score (setcdr entry (gnus-delete-alist 'touched score)))
1441           (erase-buffer)
1442           (let (emacs-lisp-mode-hook)
1443             (if (and (not gnus-adaptive-pretty-print)
1444                      (string-match
1445                       (concat (regexp-quote gnus-adaptive-file-suffix) "$")
1446                       file))
1447                 ;; This is an adaptive score file, so we do not run it through
1448                 ;; `pp' unless requested.  These files can get huge, and are
1449                 ;; not meant to be edited by human hands.
1450                 (gnus-prin1 score)
1451               ;; This is a normal score file, so we print it very
1452               ;; prettily.
1453               (let ((lisp-mode-syntax-table score-mode-syntax-table))
1454                 (gnus-pp score))))
1455           (gnus-make-directory (file-name-directory file))
1456           ;; If the score file is empty, we delete it.
1457           (if (zerop (buffer-size))
1458               (delete-file file)
1459             ;; There are scores, so we write the file.
1460             (when (file-writable-p file)
1461               (let ((coding-system-for-write score-mode-coding-system))
1462                 (gnus-write-buffer file))
1463               (when gnus-score-after-write-file-function
1464                 (funcall gnus-score-after-write-file-function file)))))
1465         (and gnus-score-uncacheable-files
1466              (string-match gnus-score-uncacheable-files file)
1467              (gnus-score-remove-from-cache file)))
1468       (kill-buffer (current-buffer)))))
1469
1470 (defun gnus-score-load-files (score-files)
1471   "Load all score files in SCORE-FILES."
1472   ;; Load the score files.
1473   (let (scores)
1474     (while score-files
1475       (if (stringp (car score-files))
1476           ;; It is a string, which means that it's a score file name,
1477           ;; so we load the score file and add the score alist to
1478           ;; the list of alists.
1479           (setq scores (nconc (gnus-score-load-file (car score-files)) scores))
1480         ;; It is an alist, so we just add it to the list directly.
1481         (setq scores (nconc (car score-files) scores)))
1482       (setq score-files (cdr score-files)))
1483     ;; Prune the score files that are to be excluded, if any.
1484     (when gnus-scores-exclude-files
1485       (let ((s scores)
1486             c)
1487         (while s
1488           (and (setq c (rassq (car s) gnus-score-cache))
1489                (member (car c) gnus-scores-exclude-files)
1490                (setq scores (delq (car s) scores)))
1491           (setq s (cdr s)))))
1492     scores))
1493
1494 (defun gnus-score-headers (score-files &optional trace)
1495   ;; Score `gnus-newsgroup-headers'.
1496   (let (scores news)
1497     ;; PLM: probably this is not the best place to clear orphan-score
1498     (setq gnus-orphan-score nil
1499           gnus-scores-articles nil
1500           gnus-scores-exclude-files nil
1501           scores (gnus-score-load-files score-files))
1502     (setq news scores)
1503     ;; Do the scoring.
1504     (while news
1505       (setq scores news
1506             news nil)
1507       (when (and gnus-summary-default-score
1508                  scores)
1509         (let* ((entries gnus-header-index)
1510                (now (date-to-day (current-time-string)))
1511                (expire (and gnus-score-expiry-days
1512                             (- now gnus-score-expiry-days)))
1513                (headers gnus-newsgroup-headers)
1514                (current-score-file gnus-current-score-file)
1515                entry header new)
1516           (gnus-message 7 "Scoring...")
1517           ;; Create articles, an alist of the form `(HEADER . SCORE)'.
1518           (while (setq header (pop headers))
1519             ;; WARNING: The assq makes the function O(N*S) while it could
1520             ;; be written as O(N+S), where N is (length gnus-newsgroup-headers)
1521             ;; and S is (length gnus-newsgroup-scored).
1522             (unless (assq (mail-header-number header) gnus-newsgroup-scored)
1523               (setq gnus-scores-articles ;Total of 2 * N cons-cells used.
1524                     (cons (cons header (or gnus-summary-default-score 0))
1525                           gnus-scores-articles))))
1526
1527           (with-current-buffer (gnus-get-buffer-create "*Headers*")
1528             (buffer-disable-undo)
1529             (when (gnus-buffer-live-p gnus-summary-buffer)
1530               (message-clone-locals gnus-summary-buffer))
1531
1532             ;; Set the global variant of this variable.
1533             (setq gnus-current-score-file current-score-file)
1534             ;; score orphans
1535             (when gnus-orphan-score
1536               (setq gnus-score-index
1537                     (nth 1 (assoc "references" gnus-header-index)))
1538               (gnus-score-orphans gnus-orphan-score))
1539             ;; Run each header through the score process.
1540             (while entries
1541               (setq entry (pop entries)
1542                     header (nth 0 entry)
1543                     gnus-score-index (nth 1 (assoc header gnus-header-index)))
1544               (when (< 0 (apply 'max (mapcar
1545                                       (lambda (score)
1546                                         (length (gnus-score-get header score)))
1547                                       scores)))
1548                 (when (if (and gnus-inhibit-slow-scoring
1549                                (or (eq gnus-inhibit-slow-scoring t)
1550                                    (and (stringp gnus-inhibit-slow-scoring)
1551                                         ;; Always true here?
1552                                         ;; (stringp gnus-newsgroup-name)
1553                                         (string-match
1554                                          gnus-inhibit-slow-scoring
1555                                          gnus-newsgroup-name)))
1556                                (> 0 (nth 1 (assoc header gnus-header-index))))
1557                           (progn
1558                             (gnus-message
1559                              7 "Scoring on headers or body skipped.")
1560                             nil)
1561                         ;; Call the scoring function for this type of "header".
1562                         (setq new (funcall (nth 2 entry) scores header
1563                                            now expire trace)))
1564                   (push new news))))
1565             (when (gnus-buffer-live-p gnus-summary-buffer)
1566               (let ((scored gnus-newsgroup-scored))
1567                 (with-current-buffer gnus-summary-buffer
1568                   (setq gnus-newsgroup-scored scored))))
1569             ;; Remove the buffer.
1570             (gnus-kill-buffer (current-buffer)))
1571
1572           ;; Add articles to `gnus-newsgroup-scored'.
1573           (while gnus-scores-articles
1574             (when (or (/= gnus-summary-default-score
1575                           (cdar gnus-scores-articles))
1576                       gnus-save-score)
1577               (push (cons (mail-header-number (caar gnus-scores-articles))
1578                           (cdar gnus-scores-articles))
1579                     gnus-newsgroup-scored))
1580             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1581
1582           (let (score)
1583             (while (setq score (pop scores))
1584               (while score
1585                 (when (consp (caar score))
1586                   (gnus-score-advanced (car score) trace))
1587                 (pop score))))
1588
1589           (gnus-message 7 "Scoring...done"))))))
1590
1591 (defun gnus-score-lower-thread (thread score-adjust)
1592   "Lower the score on THREAD with SCORE-ADJUST.
1593 THREAD is expected to contain a list of the form `(PARENT [CHILD1
1594 CHILD2 ...])' where PARENT is a header array and each CHILD is a list
1595 of the same form as THREAD.  The empty list nil is valid.  For each
1596 article in the tree, the score of the corresponding entry in
1597 `gnus-newsgroup-scored' is adjusted by SCORE-ADJUST."
1598   (while thread
1599     (let ((head (car thread)))
1600       (if (listp head)
1601           ;; handle a child and its descendants
1602           (gnus-score-lower-thread head score-adjust)
1603         ;; handle the parent
1604         (let* ((article (mail-header-number head))
1605                (score (assq article gnus-newsgroup-scored)))
1606           (if score (setcdr score (+ (cdr score) score-adjust))
1607             (push (cons article score-adjust) gnus-newsgroup-scored)))))
1608     (setq thread (cdr thread))))
1609
1610 (defun gnus-score-orphans (score)
1611   "Score orphans.
1612 A root is an article with no references.  An orphan is an article
1613 which has references, but is not connected via its references to a
1614 root article.  This function finds all the orphans, and adjusts their
1615 score in `gnus-newsgroup-scored' by SCORE."
1616   ;; gnus-make-threads produces a list, where each entry is a "thread"
1617   ;; as described in the gnus-score-lower-thread docs.  This function
1618   ;; will be called again (after limiting has been done) if the display
1619   ;; is threaded.  It would be nice to somehow save this info and use
1620   ;; it later.
1621   (dolist (thread (gnus-make-threads))
1622     (let ((id (aref (car thread) gnus-score-index)))
1623       ;; If the parent of the thread is not a root, lower the score of
1624       ;; it and its descendants.  Note that some roots seem to satisfy
1625       ;; (eq id nil) and some (eq id "");  not sure why.
1626       (when (and id
1627                  (not (string= id "")))
1628         (gnus-score-lower-thread thread score)))))
1629
1630 (defun gnus-score-integer (scores header now expire &optional trace)
1631   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1632         entries alist)
1633     ;; Find matches.
1634     (while scores
1635       (setq alist (car scores)
1636             scores (cdr scores)
1637             entries (assoc header alist))
1638       (while (cdr entries)              ;First entry is the header index.
1639         (let* ((rest (cdr entries))
1640                (kill (car rest))
1641                (match (nth 0 kill))
1642                (type (or (nth 3 kill) '>))
1643                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1644                (date (nth 2 kill))
1645                (found nil)
1646                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1647                                    (eq type '>=) (eq type '=))
1648                                type
1649                              (error "Invalid match type: %s" type)))
1650                (articles gnus-scores-articles))
1651           ;; Instead of doing all the clever stuff that
1652           ;; `gnus-score-string' does to minimize searches and stuff,
1653           ;; I will assume that people generally will put so few
1654           ;; matches on numbers that any cleverness will take more
1655           ;; time than one would gain.
1656           (while articles
1657             (when (funcall match-func
1658                            (or (aref (caar articles) gnus-score-index) 0)
1659                            match)
1660               (when trace
1661                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1662                       gnus-score-trace))
1663               (setq found t)
1664               (setcdr (car articles) (+ score (cdar articles))))
1665             (setq articles (cdr articles)))
1666           ;; Update expire date
1667           (cond ((null date))           ;Permanent entry.
1668                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1669                  (gnus-score-set 'touched '(t) alist)
1670                  (setcar (nthcdr 2 kill) now))
1671                 ((and expire (< date expire)) ;Old entry, remove.
1672                  (gnus-score-set 'touched '(t) alist)
1673                  (setcdr entries (cdr rest))
1674                  (setq rest entries)))
1675           (setq entries rest)))))
1676   nil)
1677
1678 (defun gnus-score-date (scores header now expire &optional trace)
1679   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1680         entries alist match match-func article)
1681     ;; Find matches.
1682     (while scores
1683       (setq alist (car scores)
1684             scores (cdr scores)
1685             entries (assoc header alist))
1686       (while (cdr entries)              ;First entry is the header index.
1687         (let* ((rest (cdr entries))
1688                (kill (car rest))
1689                (type (or (nth 3 kill) 'before))
1690                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1691                (date (nth 2 kill))
1692                (found nil)
1693                (articles gnus-scores-articles)
1694                l)
1695           (cond
1696            ((eq type 'after)
1697             (setq match-func 'string<
1698                   match (gnus-date-iso8601 (nth 0 kill))))
1699            ((eq type 'before)
1700             (setq match-func 'gnus-string>
1701                   match (gnus-date-iso8601 (nth 0 kill))))
1702            ((eq type 'at)
1703             (setq match-func 'string=
1704                   match (gnus-date-iso8601 (nth 0 kill))))
1705            ((eq type 'regexp)
1706             (setq match-func 'string-match
1707                   match (nth 0 kill)))
1708            (t (error "Invalid match type: %s" type)))
1709           ;; Instead of doing all the clever stuff that
1710           ;; `gnus-score-string' does to minimize searches and stuff,
1711           ;; I will assume that people generally will put so few
1712           ;; matches on numbers that any cleverness will take more
1713           ;; time than one would gain.
1714           (while (setq article (pop articles))
1715             (when (and
1716                    (setq l (aref (car article) gnus-score-index))
1717                    (funcall match-func match (gnus-date-iso8601 l)))
1718               (when trace
1719                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1720                       gnus-score-trace))
1721               (setq found t)
1722               (setcdr article (+ score (cdr article)))))
1723           ;; Update expire date
1724           (cond ((null date))           ;Permanent entry.
1725                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1726                  (gnus-score-set 'touched '(t) alist)
1727                  (setcar (nthcdr 2 kill) now))
1728                 ((and expire (< date expire)) ;Old entry, remove.
1729                  (gnus-score-set 'touched '(t) alist)
1730                  (setcdr entries (cdr rest))
1731                  (setq rest entries)))
1732           (setq entries rest)))))
1733   nil)
1734
1735 (defun gnus-score-body (scores header now expire &optional trace)
1736   (if gnus-agent-fetching
1737       nil
1738     (save-excursion
1739       (setq gnus-scores-articles
1740             (sort gnus-scores-articles
1741                   (lambda (a1 a2)
1742                     (< (mail-header-number (car a1))
1743                        (mail-header-number (car a2))))))
1744       (set-buffer nntp-server-buffer)
1745       (save-restriction
1746         (let* ((buffer-read-only nil)
1747                (articles gnus-scores-articles)
1748                (all-scores scores)
1749                (request-func (cond ((string= "head" header)
1750                                     'gnus-request-head)
1751                                    ((string= "body" header)
1752                                     'gnus-request-body)
1753                                    (t 'gnus-request-article)))
1754                entries alist ofunc article last)
1755           (when articles
1756             (setq last (mail-header-number (caar (last articles))))
1757           ;; Not all backends support partial fetching.  In that case,
1758             ;; we just fetch the entire article.
1759             (unless (gnus-check-backend-function
1760                      (and (string-match "^gnus-" (symbol-name request-func))
1761                           (intern (substring (symbol-name request-func)
1762                                              (match-end 0))))
1763                      gnus-newsgroup-name)
1764               (setq ofunc request-func)
1765               (setq request-func 'gnus-request-article))
1766             (while articles
1767               (setq article (mail-header-number (caar articles)))
1768               (gnus-message 7 "Scoring article %s of %s..." article last)
1769               (widen)
1770               (when (funcall request-func article gnus-newsgroup-name)
1771                 (goto-char (point-min))
1772             ;; If just parts of the article is to be searched, but the
1773             ;; backend didn't support partial fetching, we just narrow
1774                 ;; to the relevant parts.
1775                 (when ofunc
1776                   (if (eq ofunc 'gnus-request-head)
1777                       (narrow-to-region
1778                        (point)
1779                        (or (search-forward "\n\n" nil t) (point-max)))
1780                     (narrow-to-region
1781                      (or (search-forward "\n\n" nil t) (point))
1782                      (point-max))))
1783                 (setq scores all-scores)
1784                 ;; Find matches.
1785                 (while scores
1786                   (setq alist (pop scores)
1787                         entries (assoc header alist))
1788                   (while (cdr entries) ;First entry is the header index.
1789                     (let* ((rest (cdr entries))
1790                            (kill (car rest))
1791                            (match (nth 0 kill))
1792                            (type (or (nth 3 kill) 's))
1793                            (score (or (nth 1 kill)
1794                                       gnus-score-interactive-default-score))
1795                            (date (nth 2 kill))
1796                            (found nil)
1797                            (case-fold-search
1798                             (not (or (eq type 'R) (eq type 'S)
1799                                      (eq type 'Regexp) (eq type 'String))))
1800                            (search-func
1801                             (cond ((or (eq type 'r) (eq type 'R)
1802                                        (eq type 'regexp) (eq type 'Regexp))
1803                                    're-search-forward)
1804                                   ((or (eq type 's) (eq type 'S)
1805                                        (eq type 'string) (eq type 'String))
1806                                    'search-forward)
1807                                   (t
1808                                    (error "Invalid match type: %s" type)))))
1809                       (goto-char (point-min))
1810                       (when (funcall search-func match nil t)
1811                         ;; Found a match, update scores.
1812                         (setcdr (car articles) (+ score (cdar articles)))
1813                         (setq found t)
1814                         (when trace
1815                           (push
1816                            (cons (car-safe (rassq alist gnus-score-cache))
1817                                  kill)
1818                            gnus-score-trace)))
1819                       ;; Update expire date
1820                       (unless trace
1821                         (cond
1822                          ((null date))  ;Permanent entry.
1823                          ((and found gnus-update-score-entry-dates)
1824                           ;; Match, update date.
1825                           (gnus-score-set 'touched '(t) alist)
1826                           (setcar (nthcdr 2 kill) now))
1827                          ((and expire (< date expire)) ;Old entry, remove.
1828                           (gnus-score-set 'touched '(t) alist)
1829                           (setcdr entries (cdr rest))
1830                           (setq rest entries))))
1831                       (setq entries rest)))))
1832               (setq articles (cdr articles)))))))
1833     nil))
1834
1835 (defun gnus-score-thread (scores header now expire &optional trace)
1836   (gnus-score-followup scores header now expire trace t))
1837
1838 (defun gnus-score-followup (scores header now expire &optional trace thread)
1839   (if gnus-agent-fetching
1840       ;; FIXME: It seems doable in fetching mode.
1841       nil
1842     ;; Insert the unique article headers in the buffer.
1843     (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1844           (current-score-file gnus-current-score-file)
1845           (all-scores scores)
1846           ;; gnus-score-index is used as a free variable.
1847           alike last this art entries alist articles
1848           new news)
1849
1850       ;; Change score file to the adaptive score file.  All entries that
1851       ;; this function makes will be put into this file.
1852       (with-current-buffer gnus-summary-buffer
1853         (gnus-score-load-file
1854          (or gnus-newsgroup-adaptive-score-file
1855              (gnus-score-file-name
1856               gnus-newsgroup-name gnus-adaptive-file-suffix))))
1857
1858       (setq gnus-scores-articles (sort gnus-scores-articles
1859                                        'gnus-score-string<)
1860             articles gnus-scores-articles)
1861
1862       (erase-buffer)
1863       (while articles
1864         (setq art (car articles)
1865               this (aref (car art) gnus-score-index)
1866               articles (cdr articles))
1867         (if (equal last this)
1868             (push art alike)
1869           (when last
1870             (insert last ?\n)
1871             (put-text-property (1- (point)) (point) 'articles alike))
1872           (setq alike (list art)
1873                 last this)))
1874       (when last                        ; Bwadr, duplicate code.
1875         (insert last ?\n)
1876         (put-text-property (1- (point)) (point) 'articles alike))
1877
1878       ;; Find matches.
1879       (while scores
1880         (setq alist (car scores)
1881               scores (cdr scores)
1882               entries (assoc header alist))
1883         (while (cdr entries)            ;First entry is the header index.
1884           (let* ((rest (cdr entries))
1885                  (kill (car rest))
1886                  (match (nth 0 kill))
1887                  (type (or (nth 3 kill) 's))
1888                  (score (or (nth 1 kill) gnus-score-interactive-default-score))
1889                  (date (nth 2 kill))
1890                  (found nil)
1891                  (mt (aref (symbol-name type) 0))
1892                  (case-fold-search
1893                   (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1894                  (dmt (downcase mt))
1895                  (search-func
1896                   (cond ((= dmt ?r) 're-search-forward)
1897                         ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1898                         (t (error "Invalid match type: %s" type))))
1899                  arts art)
1900             (goto-char (point-min))
1901             (if (= dmt ?e)
1902                 (while (funcall search-func match nil t)
1903                   (and (= (point-at-bol)
1904                           (match-beginning 0))
1905                        (= (progn (end-of-line) (point))
1906                           (match-end 0))
1907                        (progn
1908                          (setq found (setq arts (get-text-property
1909                                                  (point) 'articles)))
1910                          ;; Found a match, update scores.
1911                          (while arts
1912                            (setq art (car arts)
1913                                  arts (cdr arts))
1914                            (gnus-score-add-followups
1915                             (car art) score all-scores thread))))
1916                   (end-of-line))
1917               (while (funcall search-func match nil t)
1918                 (end-of-line)
1919                 (setq found (setq arts (get-text-property (point) 'articles)))
1920                 ;; Found a match, update scores.
1921                 (while (setq art (pop arts))
1922                   (setcdr art (+ score (cdr art)))
1923                   (when trace
1924                     (push (cons
1925                            (car-safe (rassq alist gnus-score-cache))
1926                            kill)
1927                           gnus-score-trace))
1928                   (when (setq new (gnus-score-add-followups
1929                                    (car art) score all-scores thread))
1930                     (push new news)))))
1931             ;; Update expire date
1932             (cond ((null date))         ;Permanent entry.
1933                   ((and found gnus-update-score-entry-dates)
1934                                         ;Match, update date.
1935                    (gnus-score-set 'touched '(t) alist)
1936                    (setcar (nthcdr 2 kill) now))
1937                   ((and expire (< date expire)) ;Old entry, remove.
1938                    (gnus-score-set 'touched '(t) alist)
1939                    (setcdr entries (cdr rest))
1940                    (setq rest entries)))
1941             (setq entries rest))))
1942       ;; We change the score file back to the previous one.
1943       (with-current-buffer gnus-summary-buffer
1944         (gnus-score-load-file current-score-file))
1945       (list (cons "references" news)))))
1946
1947 (defun gnus-score-add-followups (header score scores &optional thread)
1948   "Add a score entry to the adapt file."
1949   (with-current-buffer gnus-summary-buffer
1950     (let* ((id (mail-header-id header))
1951            (scores (car scores))
1952            entry dont)
1953       ;; Don't enter a score if there already is one.
1954       (while (setq entry (pop scores))
1955         (and (equal "references" (car entry))
1956              (or (null (nth 3 (cadr entry)))
1957                  (eq 's (nth 3 (cadr entry))))
1958              (assoc id entry)
1959              (setq dont t)))
1960       (unless dont
1961         (gnus-summary-score-entry
1962          (if thread "thread" "references")
1963          id 's score (current-time-string) nil t)))))
1964
1965 (defun gnus-score-string (score-list header now expire &optional trace)
1966   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1967   ;; Update matching entries to NOW and remove unmatched entries older
1968   ;; than EXPIRE.
1969
1970   ;; Insert the unique article headers in the buffer.
1971   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1972         ;; gnus-score-index is used as a free variable.
1973         (simplify (and gnus-score-thread-simplify
1974                        (string= "subject" header)))
1975         alike last this art entries alist articles
1976         fuzzies arts words kill)
1977
1978     ;; Sorting the articles costs os O(N*log N) but will allow us to
1979     ;; only match with each unique header.  Thus the actual matching
1980     ;; will be O(M*U) where M is the number of strings to match with,
1981     ;; and U is the number of unique headers.  It is assumed (but
1982     ;; untested) this will be a net win because of the large constant
1983     ;; factor involved with string matching.
1984     (setq gnus-scores-articles
1985           ;; We cannot string-sort the extra headers list.  *sigh*
1986           (if (= gnus-score-index 9)
1987               gnus-scores-articles
1988             (sort gnus-scores-articles 'gnus-score-string<))
1989           articles gnus-scores-articles)
1990
1991     (erase-buffer)
1992     (while (setq art (pop articles))
1993       (setq this (aref (car art) gnus-score-index))
1994
1995       ;; If we're working with non-standard headers, we are stuck
1996       ;; with working on them as a group.  What a hassle.
1997       ;; Just wait 'til you see what horrors we commit against `match'...
1998       (if (= gnus-score-index 9)
1999           (setq this (gnus-prin1-to-string this))) ; ick.
2000
2001       (if simplify
2002           (setq this (gnus-map-function gnus-simplify-subject-functions this)))
2003       (if (equal last this)
2004           ;; O(N*H) cons-cells used here, where H is the number of
2005           ;; headers.
2006           (push art alike)
2007         (when last
2008           ;; Insert the line, with a text property on the
2009           ;; terminating newline referring to the articles with
2010           ;; this line.
2011           (insert last ?\n)
2012           (put-text-property (1- (point)) (point) 'articles alike))
2013         (setq alike (list art)
2014               last this)))
2015     (when last                          ; Bwadr, duplicate code.
2016       (insert last ?\n)
2017       (put-text-property (1- (point)) (point) 'articles alike))
2018
2019     ;; Go through all the score alists and pick out the entries
2020     ;; for this header.
2021     (while score-list
2022       (setq alist (pop score-list)
2023             ;; There's only one instance of this header for
2024             ;; each score alist.
2025             entries (assoc header alist))
2026       (while (cdr entries)              ;First entry is the header index.
2027         (let* ((kill (cadr entries))
2028                (type (or (nth 3 kill) 's))
2029                (score (or (nth 1 kill) gnus-score-interactive-default-score))
2030                (date (nth 2 kill))
2031                (extra (nth 4 kill))     ; non-standard header; string.
2032                (found nil)
2033                (mt (aref (symbol-name type) 0))
2034                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
2035                (dmt (downcase mt))
2036                ;; Assume user already simplified regexp and fuzzies
2037                (match (if (and simplify (not (memq dmt '(?f ?r))))
2038                           (gnus-map-function
2039                            gnus-simplify-subject-functions
2040                            (nth 0 kill))
2041                         (nth 0 kill)))
2042                (search-func
2043                 (cond ((= dmt ?r) 're-search-forward)
2044                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
2045                       ((= dmt ?w) nil)
2046                       (t (error "Invalid match type: %s" type)))))
2047
2048           ;; Evil hackery to make match usable in non-standard headers.
2049           (when extra
2050             (setq match (concat "[ (](" extra " \\. \"\\([^\"]*\\\\\"\\)*[^\"]*"
2051                                 (if (eq search-func 're-search-forward)
2052                                     match
2053                                   (regexp-quote match))
2054                                 "\\([^\"]*\\\\\"\\)*[^\"]*\")[ )]")
2055                   search-func 're-search-forward)) ; XXX danger?!?
2056
2057           (cond
2058            ;; Fuzzy matches.  We save these for later.
2059            ((= dmt ?f)
2060             (push (cons entries alist) fuzzies)
2061             (setq entries (cdr entries)))
2062            ;; Word matches.  Save these for even later.
2063            ((= dmt ?w)
2064             (push (cons entries alist) words)
2065             (setq entries (cdr entries)))
2066            ;; Exact matches.
2067            ((= dmt ?e)
2068             ;; Do exact matching.
2069             (goto-char (point-min))
2070             (while (and (not (eobp))
2071                         (funcall search-func match nil t))
2072               ;; Is it really exact?
2073               (and (eolp)
2074                    (= (point-at-bol) (match-beginning 0))
2075                    ;; Yup.
2076                    (progn
2077                      (setq found (setq arts (get-text-property
2078                                              (point) 'articles)))
2079                      ;; Found a match, update scores.
2080                      (if trace
2081                          (while (setq art (pop arts))
2082                            (setcdr art (+ score (cdr art)))
2083                            (push
2084                             (cons
2085                              (car-safe (rassq alist gnus-score-cache))
2086                              kill)
2087                             gnus-score-trace))
2088                        (while (setq art (pop arts))
2089                          (setcdr art (+ score (cdr art)))))))
2090               (forward-line 1))
2091             ;; Update expiry date
2092             (if trace
2093                 (setq entries (cdr entries))
2094               (cond
2095                ;; Permanent entry.
2096                ((null date)
2097                 (setq entries (cdr entries)))
2098                ;; We have a match, so we update the date.
2099                ((and found gnus-update-score-entry-dates)
2100                 (gnus-score-set 'touched '(t) alist)
2101                 (setcar (nthcdr 2 kill) now)
2102                 (setq entries (cdr entries)))
2103                ;; This entry has expired, so we remove it.
2104                ((and expire (< date expire))
2105                 (gnus-score-set 'touched '(t) alist)
2106                 (setcdr entries (cddr entries)))
2107                ;; No match; go to next entry.
2108                (t
2109                 (setq entries (cdr entries))))))
2110            ;; Regexp and substring matching.
2111            (t
2112             (goto-char (point-min))
2113             (when (string= match "")
2114               (setq match "\n"))
2115             (while (and (not (eobp))
2116                         (funcall search-func match nil t))
2117               (goto-char (match-beginning 0))
2118               (end-of-line)
2119               (setq found (setq arts (get-text-property (point) 'articles)))
2120               ;; Found a match, update scores.
2121               (if trace
2122                   (while (setq art (pop arts))
2123                     (setcdr art (+ score (cdr art)))
2124                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
2125                           gnus-score-trace))
2126                 (while (setq art (pop arts))
2127                   (setcdr art (+ score (cdr art)))))
2128               (forward-line 1))
2129             ;; Update expiry date
2130             (if trace
2131                 (setq entries (cdr entries))
2132               (cond
2133                ;; Permanent entry.
2134                ((null date)
2135                 (setq entries (cdr entries)))
2136                ;; We have a match, so we update the date.
2137                ((and found gnus-update-score-entry-dates)
2138                 (gnus-score-set 'touched '(t) alist)
2139                 (setcar (nthcdr 2 kill) now)
2140                 (setq entries (cdr entries)))
2141                ;; This entry has expired, so we remove it.
2142                ((and expire (< date expire))
2143                 (gnus-score-set 'touched '(t) alist)
2144                 (setcdr entries (cddr entries)))
2145                ;; No match; go to next entry.
2146                (t
2147                 (setq entries (cdr entries))))))))))
2148
2149     ;; Find fuzzy matches.
2150     (when fuzzies
2151       ;; Simplify the entire buffer for easy matching.
2152       (gnus-simplify-buffer-fuzzy)
2153       (while (setq kill (cadaar fuzzies))
2154         (let* ((match (nth 0 kill))
2155                (type (nth 3 kill))
2156                (score (or (nth 1 kill) gnus-score-interactive-default-score))
2157                (date (nth 2 kill))
2158                (mt (aref (symbol-name type) 0))
2159                (case-fold-search (not (= mt ?F)))
2160                found)
2161           (goto-char (point-min))
2162           (while (and (not (eobp))
2163                       (search-forward match nil t))
2164             (when (and (= (point-at-bol) (match-beginning 0))
2165                        (eolp))
2166               (setq found (setq arts (get-text-property (point) 'articles)))
2167               (if trace
2168                   (while (setq art (pop arts))
2169                     (setcdr art (+ score (cdr art)))
2170                     (push (cons
2171                            (car-safe (rassq (cdar fuzzies) gnus-score-cache))
2172                            kill)
2173                           gnus-score-trace))
2174                 ;; Found a match, update scores.
2175                 (while (setq art (pop arts))
2176                   (setcdr art (+ score (cdr art))))))
2177             (forward-line 1))
2178           ;; Update expiry date
2179           (if (not trace)
2180               (cond
2181                ;; Permanent.
2182                ((null date)
2183                 ;; Do nothing.
2184                 )
2185                ;; Match, update date.
2186                ((and found gnus-update-score-entry-dates)
2187                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2188                 (setcar (nthcdr 2 kill) now))
2189                ;; Old entry, remove.
2190                ((and expire (< date expire))
2191                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2192                 (setcdr (caar fuzzies) (cddaar fuzzies)))))
2193           (setq fuzzies (cdr fuzzies)))))
2194
2195     (when words
2196       ;; Enter all words into the hashtb.
2197       (let ((hashtb (gnus-make-hashtable
2198                      (* 10 (count-lines (point-min) (point-max))))))
2199         (gnus-enter-score-words-into-hashtb hashtb)
2200         (while (setq kill (cadaar words))
2201           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
2202                  (date (nth 2 kill))
2203                  found)
2204             (when (setq arts (intern-soft (nth 0 kill) hashtb))
2205               (setq arts (symbol-value arts))
2206               (setq found t)
2207               (if trace
2208                   (while (setq art (pop arts))
2209                     (setcdr art (+ score (cdr art)))
2210                     (push (cons
2211                            (car-safe (rassq (cdar words) gnus-score-cache))
2212                            kill)
2213                           gnus-score-trace))
2214                 ;; Found a match, update scores.
2215                 (while (setq art (pop arts))
2216                   (setcdr art (+ score (cdr art))))))
2217             ;; Update expiry date
2218             (if (not trace)
2219                 (cond
2220                  ;; Permanent.
2221                  ((null date)
2222                   ;; Do nothing.
2223                   )
2224                  ;; Match, update date.
2225                  ((and found gnus-update-score-entry-dates)
2226                   (gnus-score-set 'touched '(t) (cdar words))
2227                   (setcar (nthcdr 2 kill) now))
2228                  ;; Old entry, remove.
2229                  ((and expire (< date expire))
2230                   (gnus-score-set 'touched '(t) (cdar words))
2231                   (setcdr (caar words) (cddaar words)))))
2232             (setq words (cdr words))))))
2233     nil))
2234
2235 (defun gnus-enter-score-words-into-hashtb (hashtb)
2236   ;; Find all the words in the buffer and enter them into
2237   ;; the hashtable.
2238   (let (word val)
2239     (goto-char (point-min))
2240     (with-syntax-table gnus-adaptive-word-syntax-table
2241       (while (re-search-forward "\\b\\w+\\b" nil t)
2242         (setq val
2243               (gnus-gethash
2244                (setq word (downcase (buffer-substring
2245                                      (match-beginning 0) (match-end 0))))
2246                hashtb))
2247         (gnus-sethash
2248          word
2249          (append (get-text-property (point-at-eol) 'articles) val)
2250          hashtb)))
2251     ;; Make all the ignorable words ignored.
2252     (let ((ignored (append gnus-ignored-adaptive-words
2253                            (if gnus-adaptive-word-no-group-words
2254                                (message-tokenize-header
2255                                 (gnus-group-real-name gnus-newsgroup-name)
2256                                 "."))
2257                            gnus-default-ignored-adaptive-words)))
2258       (while ignored
2259         (gnus-sethash (pop ignored) nil hashtb)))))
2260
2261 (defun gnus-score-string< (a1 a2)
2262   ;; Compare headers in articles A2 and A2.
2263   ;; The header index used is the free variable `gnus-score-index'.
2264   (string-lessp (aref (car a1) gnus-score-index)
2265                 (aref (car a2) gnus-score-index)))
2266
2267 (defun gnus-current-score-file-nondirectory (&optional score-file)
2268   (let ((score-file (or score-file gnus-current-score-file)))
2269     (if score-file
2270         (gnus-short-group-name (file-name-nondirectory score-file))
2271       "none")))
2272
2273 (defun gnus-score-adaptive ()
2274   "Create adaptive score rules for this newsgroup."
2275   (when gnus-newsgroup-adaptive
2276     ;; We change the score file to the adaptive score file.
2277     (with-current-buffer gnus-summary-buffer
2278       (gnus-score-load-file
2279        (or gnus-newsgroup-adaptive-score-file
2280            (gnus-home-score-file gnus-newsgroup-name t)
2281            (gnus-score-file-name
2282             gnus-newsgroup-name gnus-adaptive-file-suffix))))
2283     ;; Perform ordinary line scoring.
2284     (when (or (not (listp gnus-newsgroup-adaptive))
2285               (memq 'line gnus-newsgroup-adaptive))
2286       (save-excursion
2287         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
2288                (alist malist)
2289                (date (current-time-string))
2290                (data gnus-newsgroup-data)
2291                elem headers match func)
2292           ;; First we transform the adaptive rule alist into something
2293           ;; that's faster to process.
2294           (while malist
2295             (setq elem (car malist))
2296             (when (symbolp (car elem))
2297               (setcar elem (symbol-value (car elem))))
2298             (setq elem (cdr elem))
2299             (while elem
2300               (when (fboundp
2301                      (setq func
2302                            (intern
2303                             (concat "mail-header-"
2304                                     (if (eq (caar elem) 'followup)
2305                                         "message-id"
2306                                       (downcase (symbol-name (caar elem))))))))
2307                 (setcdr (car elem)
2308                         (cons (if (eq (caar elem) 'followup)
2309                                   "references"
2310                                 (symbol-name (caar elem)))
2311                               (cdar elem)))
2312                 (setcar (car elem)
2313                         `(lambda (h)
2314                            (,func h))))
2315               (setq elem (cdr elem)))
2316             (setq malist (cdr malist)))
2317           ;; Then we score away.
2318           (while data
2319             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2320             (if (or (not elem)
2321                     (gnus-data-pseudo-p (car data)))
2322                 ()
2323               (when (setq headers (gnus-data-header (car data)))
2324                 (while elem
2325                   (setq match (funcall (caar elem) headers))
2326                   (gnus-summary-score-entry
2327                    (nth 1 (car elem)) match
2328                    (cond
2329                     ((numberp match)
2330                      '=)
2331                     ((equal (nth 1 (car elem)) "date")
2332                      'a)
2333                     (t
2334                      ;; Whether we use substring or exact matches is
2335                      ;; controlled here.
2336                      (if (or (not gnus-score-exact-adapt-limit)
2337                              (< (length match) gnus-score-exact-adapt-limit))
2338                          'e
2339                        (if (equal (nth 1 (car elem)) "subject")
2340                            'f 's))))
2341                    (nth 2 (car elem)) date nil t)
2342                   (setq elem (cdr elem)))))
2343             (setq data (cdr data))))))
2344
2345     ;; Perform adaptive word scoring.
2346     (when (and (listp gnus-newsgroup-adaptive)
2347                (memq 'word gnus-newsgroup-adaptive))
2348       (with-temp-buffer
2349         (let* ((hashtb (gnus-make-hashtable 1000))
2350                (date (date-to-day (current-time-string)))
2351                (data gnus-newsgroup-data)
2352                word d score val)
2353           (with-syntax-table gnus-adaptive-word-syntax-table
2354             ;; Go through all articles.
2355             (while (setq d (pop data))
2356               (when (and
2357                      (not (gnus-data-pseudo-p d))
2358                      (setq score
2359                            (cdr (assq
2360                                  (gnus-data-mark d)
2361                                  gnus-adaptive-word-score-alist))))
2362                 ;; This article has a mark that should lead to
2363                 ;; adaptive word rules, so we insert the subject
2364                 ;; and find all words in that string.
2365                 (insert (mail-header-subject (gnus-data-header d)))
2366                 (downcase-region (point-min) (point-max))
2367                 (goto-char (point-min))
2368                 (while (re-search-forward "\\b\\w+\\b" nil t)
2369                   ;; Put the word and score into the hashtb.
2370                   (setq val (gnus-gethash (setq word (match-string 0))
2371                                           hashtb))
2372                   (when (or (not gnus-adaptive-word-length-limit)
2373                             (> (length word)
2374                                gnus-adaptive-word-length-limit))
2375                     (setq val (+ score (or val 0)))
2376                     (if (and gnus-adaptive-word-minimum
2377                              (< val gnus-adaptive-word-minimum))
2378                         (setq val gnus-adaptive-word-minimum))
2379                     (gnus-sethash word val hashtb)))
2380                 (erase-buffer))))
2381           ;; Make all the ignorable words ignored.
2382           (let ((ignored (append gnus-ignored-adaptive-words
2383                                  (if gnus-adaptive-word-no-group-words
2384                                      (message-tokenize-header
2385                                       (gnus-group-real-name
2386                                        gnus-newsgroup-name)
2387                                       "."))
2388                                  gnus-default-ignored-adaptive-words)))
2389             (while ignored
2390               (gnus-sethash (pop ignored) nil hashtb)))
2391           ;; Now we have all the words and scores, so we
2392           ;; add these rules to the ADAPT file.
2393           (set-buffer gnus-summary-buffer)
2394           (mapatoms
2395            (lambda (word)
2396              (when (symbol-value word)
2397                (gnus-summary-score-entry
2398                 "subject" (symbol-name word) 'w (symbol-value word)
2399                 date nil t)))
2400            hashtb))))))
2401
2402 (defun gnus-score-edit-done ()
2403   (let ((bufnam (buffer-file-name (current-buffer)))
2404         (winconf gnus-prev-winconf))
2405     (when winconf
2406       (set-window-configuration winconf))
2407     (gnus-score-remove-from-cache bufnam)
2408     (gnus-score-load-file bufnam)
2409     (run-hooks 'gnus-score-edit-done-hook)))
2410
2411 (defun gnus-score-find-trace ()
2412   "Find all score rules that applies to the current article."
2413   (interactive)
2414   (let ((old-scored gnus-newsgroup-scored))
2415     (let ((gnus-newsgroup-headers
2416            (list (gnus-summary-article-header)))
2417           (gnus-newsgroup-scored nil)
2418           ;; Must be synced with `gnus-score-edit-file-at-point':
2419           (frmt "%S [%s] -> %s\n")
2420           trace
2421           file)
2422       (save-excursion
2423         (nnheader-set-temp-buffer "*Score Trace*"))
2424       (setq gnus-score-trace nil)
2425       (gnus-possibly-score-headers 'trace)
2426       (if (not (setq trace gnus-score-trace))
2427           (gnus-error
2428            1 "No score rules apply to the current article (default score %d)."
2429            gnus-summary-default-score)
2430         (set-buffer "*Score Trace*")
2431         ;; Use a keymap instead?
2432         (local-set-key "q"
2433                        (lambda ()
2434                          (interactive)
2435                          (bury-buffer nil)
2436                          (gnus-summary-expand-window)))
2437         (local-set-key "k"
2438                        (lambda ()
2439                          (interactive)
2440                          (kill-buffer (current-buffer))
2441                          (gnus-summary-expand-window)))
2442         (local-set-key "e" (lambda ()
2443                              "Run `gnus-score-edit-file-at-point'."
2444                              (interactive)
2445                              (gnus-score-edit-file-at-point)))
2446         (local-set-key "f" (lambda ()
2447                              "Run `gnus-score-edit-file-at-point'."
2448                              (interactive)
2449                              (gnus-score-edit-file-at-point 'format)))
2450         (local-set-key "t" 'toggle-truncate-lines)
2451         (setq truncate-lines t)
2452         (dolist (entry trace)
2453           (setq file (or (car entry)
2454                          ;; Must be synced with
2455                          ;; `gnus-score-edit-file-at-point':
2456                          "(non-file rule)"))
2457           (insert
2458            (format frmt
2459                    (cdr entry)
2460                    ;; Don't use `file-name-sans-extension' to see .SCORE and
2461                    ;; .ADAPT directly:
2462                    (file-name-nondirectory file)
2463                    (abbreviate-file-name file))))
2464         (insert
2465          (format "\nTotal score: %d"
2466                  (apply '+ (mapcar
2467                             (lambda (s)
2468                               (or (caddr s)
2469                                   gnus-score-interactive-default-score))
2470                             trace))))
2471         (insert
2472          "\n\nQuick help:
2473
2474 Type `e' to edit score file corresponding to the score rule on current line,
2475 `f' to format (pretty print) the score file and edit it,
2476 `t' toggle to truncate long lines in this buffer,
2477 `q' to quit, `k' to kill score trace buffer.
2478
2479 The first sexp on each line is the score rule, followed by the file name of
2480 the score file and its full name, including the directory.")
2481         (goto-char (point-min))
2482         (gnus-configure-windows 'score-trace)))
2483     (set-buffer gnus-summary-buffer)
2484     (setq gnus-newsgroup-scored old-scored)))
2485
2486 (defun gnus-score-find-favourite-words ()
2487   "List words used in scoring."
2488   (interactive)
2489   (let ((alists (gnus-score-load-files (gnus-all-score-files)))
2490         alist rule rules kill)
2491     ;; Go through all the score alists for this group
2492     ;; and find all `w' rules.
2493     (while (setq alist (pop alists))
2494       (while (setq rule (pop alist))
2495         (when (and (stringp (car rule))
2496                    (equal "subject" (downcase (pop rule))))
2497           (while (setq kill (pop rule))
2498             (when (memq (nth 3 kill) '(w W word Word))
2499               (push (cons (or (nth 1 kill)
2500                               gnus-score-interactive-default-score)
2501                           (car kill))
2502                     rules))))))
2503     (setq rules (sort rules (lambda (r1 r2)
2504                               (string-lessp (cdr r1) (cdr r2)))))
2505     ;; Add up words that have appeared several times.
2506     (let ((r rules))
2507       (while (cdr r)
2508         (if (equal (cdar r) (cdadr r))
2509             (progn
2510               (setcar (car r) (+ (caar r) (caadr r)))
2511               (setcdr r (cddr r)))
2512           (pop r))))
2513     ;; Insert the words.
2514     (nnheader-set-temp-buffer "*Score Words*")
2515     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2516         (gnus-error 3 "No word score rules")
2517       (while rules
2518         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2519         (pop rules))
2520       (goto-char (point-min))
2521       (gnus-configure-windows 'score-words))))
2522
2523 (defun gnus-summary-rescore ()
2524   "Redo the entire scoring process in the current summary."
2525   (interactive)
2526   (gnus-score-save)
2527   (setq gnus-score-cache nil)
2528   (setq gnus-newsgroup-scored nil)
2529   (gnus-possibly-score-headers)
2530   (gnus-score-update-all-lines))
2531
2532 (defun gnus-score-flush-cache ()
2533   "Flush the cache of score files."
2534   (interactive)
2535   (gnus-score-save)
2536   (setq gnus-score-cache nil
2537         gnus-score-alist nil
2538         gnus-short-name-score-file-cache nil)
2539   (gnus-message 6 "The score cache is now flushed"))
2540
2541 (gnus-add-shutdown 'gnus-score-close 'gnus)
2542
2543 (defvar gnus-score-file-alist-cache nil)
2544
2545 (defun gnus-score-close ()
2546   "Clear all internal score variables."
2547   (setq gnus-score-cache nil
2548         gnus-internal-global-score-files nil
2549         gnus-score-file-list nil
2550         gnus-score-file-alist-cache nil))
2551
2552 ;; Summary score marking commands.
2553
2554 (defun gnus-summary-raise-same-subject-and-select (score)
2555   "Raise articles which has the same subject with SCORE and select the next."
2556   (interactive "p")
2557   (let ((subject (gnus-summary-article-subject)))
2558     (gnus-summary-raise-score score)
2559     (while (gnus-summary-find-subject subject)
2560       (gnus-summary-raise-score score))
2561     (gnus-summary-next-article t)))
2562
2563 (defun gnus-summary-raise-same-subject (score)
2564   "Raise articles which has the same subject with SCORE."
2565   (interactive "p")
2566   (let ((subject (gnus-summary-article-subject)))
2567     (gnus-summary-raise-score score)
2568     (while (gnus-summary-find-subject subject)
2569       (gnus-summary-raise-score score))
2570     (gnus-summary-next-subject 1 t)))
2571
2572 (defun gnus-score-delta-default (level)
2573   (if level (prefix-numeric-value level)
2574     gnus-score-interactive-default-score))
2575
2576 (defun gnus-summary-raise-thread (&optional score)
2577   "Raise the score of the articles in the current thread with SCORE."
2578   (interactive "P")
2579   (setq score (gnus-score-delta-default score))
2580   (let (e)
2581     (save-excursion
2582       (let ((articles (gnus-summary-articles-in-thread)))
2583         (while articles
2584           (gnus-summary-goto-subject (car articles))
2585           (gnus-summary-raise-score score)
2586           (setq articles (cdr articles))))
2587       (setq e (point)))
2588     (let ((gnus-summary-check-current t))
2589       (unless (zerop (gnus-summary-next-subject 1 t))
2590         (goto-char e))))
2591   (gnus-summary-recenter)
2592   (gnus-summary-position-point)
2593   (gnus-set-mode-line 'summary))
2594
2595 (defun gnus-summary-lower-same-subject-and-select (score)
2596   "Raise articles which has the same subject with SCORE and select the next."
2597   (interactive "p")
2598   (gnus-summary-raise-same-subject-and-select (- score)))
2599
2600 (defun gnus-summary-lower-same-subject (score)
2601   "Raise articles which has the same subject with SCORE."
2602   (interactive "p")
2603   (gnus-summary-raise-same-subject (- score)))
2604
2605 (defun gnus-summary-lower-thread (&optional score)
2606   "Lower score of articles in the current thread with SCORE."
2607   (interactive "P")
2608   (gnus-summary-raise-thread (- (gnus-score-delta-default score))))
2609
2610 ;;; Finding score files.
2611
2612 (defun gnus-score-score-files (group)
2613   "Return a list of all possible score files."
2614   ;; Search and set any global score files.
2615   (when gnus-global-score-files
2616     (unless gnus-internal-global-score-files
2617       (gnus-score-search-global-directories gnus-global-score-files)))
2618   ;; Fix the kill-file dir variable.
2619   (setq gnus-kill-files-directory
2620         (file-name-as-directory gnus-kill-files-directory))
2621   ;; If we can't read it, there are no score files.
2622   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2623       (setq gnus-score-file-list nil)
2624     (if (not (gnus-use-long-file-name 'not-score))
2625         ;; We do not use long file names, so we have to do some
2626         ;; directory traversing.
2627         (setq gnus-score-file-list
2628               (cons nil
2629                     (or gnus-short-name-score-file-cache
2630                         (prog2
2631                             (gnus-message 6 "Finding all score files...")
2632                             (setq gnus-short-name-score-file-cache
2633                                   (gnus-score-score-files-1
2634                                    gnus-kill-files-directory))
2635                           (gnus-message 6 "Finding all score files...done")))))
2636       ;; We want long file names.
2637       (when (or (not gnus-score-file-list)
2638                 (not (car gnus-score-file-list))
2639                 (gnus-file-newer-than gnus-kill-files-directory
2640                                       (car gnus-score-file-list)))
2641         (setq gnus-score-file-list
2642               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2643                     (nreverse
2644                      (directory-files
2645                       gnus-kill-files-directory t
2646                       (gnus-score-file-regexp)))))))
2647     (cdr gnus-score-file-list)))
2648
2649 (defun gnus-score-score-files-1 (dir)
2650   "Return all possible score files under DIR."
2651   (let ((files (list (expand-file-name dir)))
2652         (regexp (gnus-score-file-regexp))
2653         (case-fold-search nil)
2654         seen out file)
2655     (while (setq file (pop files))
2656       (cond
2657        ;; Ignore files that start with a dot.
2658        ((string-match "^\\." (file-name-nondirectory file))
2659         nil)
2660        ;; Add subtrees of directory to also be searched.
2661        ((and (file-directory-p file)
2662              (not (member (file-truename file) seen)))
2663         (push (file-truename file) seen)
2664         (setq files (nconc (directory-files file t nil t) files)))
2665        ;; Add files to the list of score files.
2666        ((string-match regexp file)
2667         (push file out))))
2668     (or out
2669         ;; Return a dummy value.
2670         (list (expand-file-name "this.file.does.not.exist.SCORE"
2671                                 gnus-kill-files-directory)))))
2672
2673 (defun gnus-score-file-regexp ()
2674   "Return a regexp that match all score files."
2675   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2676           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2677
2678 (defun gnus-score-find-bnews (group)
2679   "Return a list of score files for GROUP.
2680 The score files are those files in the ~/News/ directory which matches
2681 GROUP using BNews sys file syntax."
2682   (let* ((sfiles (append (gnus-score-score-files group)
2683                          gnus-internal-global-score-files))
2684          (kill-dir (file-name-as-directory
2685                     (expand-file-name gnus-kill-files-directory)))
2686          (klen (length kill-dir))
2687          (score-regexp (gnus-score-file-regexp))
2688          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2689          (group-trans (nnheader-translate-file-chars group t))
2690          ofiles not-match regexp)
2691     (with-current-buffer (gnus-get-buffer-create "*gnus score files*")
2692       (buffer-disable-undo)
2693       ;; Go through all score file names and create regexp with them
2694       ;; as the source.
2695       (while sfiles
2696         (erase-buffer)
2697         (insert (car sfiles))
2698         (goto-char (point-min))
2699         ;; First remove the suffix itself.
2700         (when (re-search-forward (concat "." score-regexp) nil t)
2701           (replace-match "" t t)
2702           (goto-char (point-min))
2703           (if (looking-at (regexp-quote kill-dir))
2704               ;; If the file name was just "SCORE", `klen' is one character
2705               ;; too much.
2706               (delete-char (min (1- (point-max)) klen))
2707             (goto-char (point-max))
2708             (if (re-search-backward gnus-directory-sep-char-regexp nil t)
2709                 (delete-region (1+ (point)) (point-min))
2710               (gnus-message 1 "Can't find directory separator in %s"
2711                             (car sfiles))))
2712           ;; If short file names were used, we have to translate slashes.
2713           (goto-char (point-min))
2714           (let ((regexp (concat
2715                          "[/:" (if trans (char-to-string trans)) "]")))
2716             (while (re-search-forward regexp nil t)
2717               (replace-match "." t t)))
2718           ;; Kludge to get rid of "nntp+" problems.
2719           (goto-char (point-min))
2720           (when (looking-at "nn[a-z]+\\+")
2721             (search-forward "+")
2722             (forward-char -1)
2723             (insert "\\")
2724             (forward-char 1))
2725           ;; Kludge to deal with "++".
2726           (while (search-forward "+" nil t)
2727             (replace-match "\\+" t t))
2728           ;; Translate "all" to ".*".
2729           (goto-char (point-min))
2730           (while (search-forward "all" nil t)
2731             (replace-match ".*" t t))
2732           (goto-char (point-min))
2733           ;; Deal with "not."s.
2734           (if (looking-at "not.")
2735               (progn
2736                 (setq not-match t)
2737                 (setq regexp
2738                       (concat "^" (buffer-substring 5 (point-max)) "$")))
2739             (setq regexp (concat "^" (buffer-substring 1 (point-max)) "$"))
2740             (setq not-match nil))
2741           ;; Finally - if this resulting regexp matches the group name,
2742           ;; we add this score file to the list of score files
2743           ;; applicable to this group.
2744           (when (or (and not-match
2745                          (ignore-errors
2746                            (not (string-match regexp group-trans))))
2747                     (and (not not-match)
2748                          (ignore-errors (string-match regexp group-trans))))
2749             (push (car sfiles) ofiles)))
2750         (setq sfiles (cdr sfiles)))
2751       (gnus-kill-buffer (current-buffer))
2752       ;; Slight kludge here - the last score file returned should be
2753       ;; the local score file, whether it exists or not.  This is so
2754       ;; that any score commands the user enters will go to the right
2755       ;; file, and not end up in some global score file.
2756       (let ((localscore (gnus-score-file-name group)))
2757         (setq ofiles (cons localscore (delete localscore ofiles))))
2758       (gnus-sort-score-files (nreverse ofiles)))))
2759
2760 (defun gnus-score-find-single (group)
2761   "Return list containing the score file for GROUP."
2762   (list (or gnus-newsgroup-adaptive-score-file
2763             (gnus-score-file-name group gnus-adaptive-file-suffix))
2764         (gnus-score-file-name group)))
2765
2766 (defun gnus-score-find-hierarchical (group)
2767   "Return list of score files for GROUP.
2768 This includes the score file for the group and all its parents."
2769   (let* ((prefix (gnus-group-real-prefix group))
2770          (all (list nil))
2771          (group (gnus-group-real-name group))
2772          (start 0))
2773     (while (string-match "\\." group (1+ start))
2774       (setq start (match-beginning 0))
2775       (push (substring group 0 start) all))
2776     (push group all)
2777     (setq all
2778           (nconc
2779            (mapcar (lambda (group)
2780                      (gnus-score-file-name group gnus-adaptive-file-suffix))
2781                    (setq all (nreverse all)))
2782            (mapcar 'gnus-score-file-name all)))
2783     (if (equal prefix "")
2784         all
2785       (mapcar
2786        (lambda (file)
2787          (nnheader-translate-file-chars
2788           (concat (file-name-directory file) prefix
2789                   (file-name-nondirectory file))))
2790        all))))
2791
2792 (defun gnus-score-file-rank (file)
2793   "Return a number that says how specific score FILE is.
2794 Destroys the current buffer."
2795   (if (member file gnus-internal-global-score-files)
2796       0
2797     (when (string-match
2798            (concat "^" (regexp-quote
2799                         (expand-file-name
2800                          (file-name-as-directory gnus-kill-files-directory))))
2801            file)
2802       (setq file (substring file (match-end 0))))
2803     (insert file)
2804     (goto-char (point-min))
2805     (let ((beg (point))
2806           elems)
2807       (while (re-search-forward "[./]" nil t)
2808         (push (buffer-substring beg (1- (point)))
2809               elems))
2810       (erase-buffer)
2811       (setq elems (delete "all" elems))
2812       (length elems))))
2813
2814 (defun gnus-sort-score-files (files)
2815   "Sort FILES so that the most general files come first."
2816   (with-temp-buffer
2817     (let ((alist
2818            (mapcar
2819             (lambda (file)
2820               (cons (inline (gnus-score-file-rank file)) file))
2821             files)))
2822       (mapcar 'cdr (sort alist 'car-less-than-car)))))
2823
2824 (defun gnus-score-find-alist (group)
2825   "Return list of score files for GROUP.
2826 The list is determined from the variable `gnus-score-file-alist'."
2827   (let ((alist gnus-score-file-multiple-match-alist)
2828         score-files)
2829     ;; if this group has been seen before, return the cached entry
2830     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2831         (cdr score-files)               ;ensures caching groups with no matches
2832       ;; handle the multiple match alist
2833       (while alist
2834         (when (string-match (caar alist) group)
2835           (setq score-files
2836                 (nconc score-files (copy-sequence (cdar alist)))))
2837         (setq alist (cdr alist)))
2838       (setq alist gnus-score-file-single-match-alist)
2839       ;; handle the single match alist
2840       (while alist
2841         (when (string-match (caar alist) group)
2842           ;; progn used just in case ("regexp") has no files
2843           ;; and score-files is still nil.  -sj
2844           ;; this can be construed as a "stop searching here" feature :>
2845           ;; and used to simplify regexps in the single-alist
2846           (setq score-files
2847                 (nconc score-files (copy-sequence (cdar alist))))
2848           (setq alist nil))
2849         (setq alist (cdr alist)))
2850       ;; cache the score files
2851       (push (cons group score-files) gnus-score-file-alist-cache)
2852       score-files)))
2853
2854 (defun gnus-all-score-files (&optional group)
2855   "Return a list of all score files for the current group."
2856   (let ((funcs gnus-score-find-score-files-function)
2857         (group (or group gnus-newsgroup-name))
2858         score-files)
2859     (when group
2860       ;; Make sure funcs is a list.
2861       (and funcs
2862            (not (listp funcs))
2863            (setq funcs (list funcs)))
2864       (when gnus-score-use-all-scores
2865         ;; Get the initial score files for this group.
2866         (when funcs
2867           (setq score-files (nreverse (gnus-score-find-alist group))))
2868         ;; Add any home adapt files.
2869         (let ((home (gnus-home-score-file group t)))
2870           (when home
2871             (push home score-files)
2872             (setq gnus-newsgroup-adaptive-score-file home)))
2873         ;; Check whether there is a `adapt-file' group parameter.
2874         (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2875           (when param-file
2876             (push param-file score-files)
2877             (setq gnus-newsgroup-adaptive-score-file param-file))))
2878       ;; Go through all the functions for finding score files (or actual
2879       ;; scores) and add them to a list.
2880       (while funcs
2881         (when (functionp (car funcs))
2882           (setq score-files
2883                 (append score-files
2884                         (nreverse (funcall (car funcs) group)))))
2885         (setq funcs (cdr funcs)))
2886       (when gnus-score-use-all-scores
2887         ;; Add any home score files.
2888         (let ((home (gnus-home-score-file group)))
2889           (when home
2890             (push home score-files)))
2891         ;; Check whether there is a `score-file' group parameter.
2892         (let ((param-file (gnus-group-find-parameter group 'score-file)))
2893           (when param-file
2894             (push param-file score-files))))
2895       ;; Expand all files names.
2896       (let ((files score-files))
2897         (while files
2898           (when (stringp (car files))
2899             (setcar files (expand-file-name
2900                            (car files) gnus-kill-files-directory)))
2901           (pop files)))
2902       (setq score-files (nreverse score-files))
2903       ;; Remove any duplicate score files.
2904       (while (and score-files
2905                   (member (car score-files) (cdr score-files)))
2906         (pop score-files))
2907       (let ((files score-files))
2908         (while (cdr files)
2909           (if (member (cadr files) (cddr files))
2910               (setcdr files (cddr files))
2911             (pop files))))
2912       ;; Do the scoring if there are any score files for this group.
2913       score-files)))
2914
2915 (defun gnus-possibly-score-headers (&optional trace)
2916   "Do scoring if scoring is required."
2917   (let ((score-files (gnus-all-score-files)))
2918     (when score-files
2919       (gnus-score-headers score-files trace))))
2920
2921 (defun gnus-score-file-name (newsgroup &optional suffix)
2922   "Return the name of a score file for NEWSGROUP."
2923   (let ((suffix (or suffix gnus-score-file-suffix)))
2924     (nnheader-translate-file-chars
2925      (cond
2926       ((or (null newsgroup)
2927            (string-equal newsgroup ""))
2928        ;; The global score file is placed at top of the directory.
2929        (expand-file-name suffix gnus-kill-files-directory))
2930       ((gnus-use-long-file-name 'not-score)
2931        ;; Append ".SCORE" to newsgroup name.
2932        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2933                                  "." suffix)
2934                          gnus-kill-files-directory))
2935       (t
2936        ;; Place "SCORE" under the hierarchical directory.
2937        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2938                                  "/" suffix)
2939                          gnus-kill-files-directory))))))
2940
2941 (defun gnus-score-search-global-directories (files)
2942   "Scan all global score directories for score files."
2943   ;; Set the variable `gnus-internal-global-score-files' to all
2944   ;; available global score files.
2945   (interactive (list gnus-global-score-files))
2946   (let (out)
2947     (while files
2948       ;; #### /$ Unix-specific?
2949       (if (file-directory-p (car files))
2950           (setq out (nconc (directory-files
2951                             (car files) t
2952                             (concat (gnus-score-file-regexp) "$"))))
2953         (push (car files) out))
2954       (setq files (cdr files)))
2955     (setq gnus-internal-global-score-files out)))
2956
2957 (defun gnus-score-default-fold-toggle ()
2958   "Toggle folding for new score file entries."
2959   (interactive)
2960   (setq gnus-score-default-fold (not gnus-score-default-fold))
2961   (if gnus-score-default-fold
2962       (gnus-message 1 "New score file entries will be case insensitive.")
2963     (gnus-message 1 "New score file entries will be case sensitive.")))
2964
2965 ;;; Home score file.
2966
2967 (defun gnus-home-score-file (group &optional adapt)
2968   "Return the home score file for GROUP.
2969 If ADAPT, return the home adaptive file instead."
2970   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2971         elem found)
2972     ;; Make sure we have a list.
2973     (unless (listp list)
2974       (setq list (list list)))
2975     ;; Go through the list and look for matches.
2976     (while (and (not found)
2977                 (setq elem (pop list)))
2978       (setq found
2979             (cond
2980              ;; Simple string.
2981              ((stringp elem)
2982               elem)
2983              ;; Function.
2984              ((functionp elem)
2985               (funcall elem group))
2986              ;; Regexp-file cons.
2987              ((consp elem)
2988               (when (string-match (gnus-globalify-regexp (car elem)) group)
2989                 (replace-match (cadr elem) t nil group))))))
2990     (when found
2991       (setq found (nnheader-translate-file-chars found))
2992       (if (file-name-absolute-p found)
2993           found
2994         (nnheader-concat gnus-kill-files-directory found)))))
2995
2996 (defun gnus-hierarchial-home-score-file (group)
2997   "Return the score file of the top-level hierarchy of GROUP."
2998   (if (string-match "^[^.]+\\." group)
2999       (concat (match-string 0 group) gnus-score-file-suffix)
3000     ;; Group name without any dots.
3001     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
3002             gnus-score-file-suffix)))
3003
3004 (defun gnus-hierarchial-home-adapt-file (group)
3005   "Return the adapt file of the top-level hierarchy of GROUP."
3006   (if (string-match "^[^.]+\\." group)
3007       (concat (match-string 0 group) gnus-adaptive-file-suffix)
3008     ;; Group name without any dots.
3009     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
3010             gnus-adaptive-file-suffix)))
3011
3012 (defun gnus-current-home-score-file (group)
3013   "Return the \"current\" regular score file."
3014   (car (nreverse (gnus-score-find-alist group))))
3015
3016 ;;;
3017 ;;; Score decays
3018 ;;;
3019
3020 (defun gnus-decay-score (score)
3021   "Decay SCORE according to `gnus-score-decay-constant' and `gnus-score-decay-scale'."
3022   (let ((n (- score
3023               (* (if (< score 0) -1 1)
3024                  (min (abs score)
3025                       (max gnus-score-decay-constant
3026                            (* (abs score)
3027                               gnus-score-decay-scale)))))))
3028     (if (and (featurep 'xemacs)
3029              ;; XEmacs' floor can handle only the floating point
3030              ;; number below the half of the maximum integer.
3031              (> (abs n) (lsh -1 -2)))
3032         (string-to-number
3033          (car (split-string (number-to-string n) "\\.")))
3034       (floor n))))
3035
3036 (defun gnus-decay-scores (alist day)
3037   "Decay non-permanent scores in ALIST."
3038   (let ((times (- (time-to-days (current-time)) day))
3039         kill entry updated score n)
3040     (unless (zerop times)               ;Done decays today already?
3041       (while (setq entry (pop alist))
3042         (when (stringp (car entry))
3043           (setq entry (cdr entry))
3044           (while (setq kill (pop entry))
3045             (when (nth 2 kill)
3046               (setq updated t)
3047               (setq score (or (nth 1 kill)
3048                               gnus-score-interactive-default-score)
3049                     n times)
3050               (while (natnump (decf n))
3051                 (setq score (funcall gnus-decay-score-function score)))
3052               (setcdr kill (cons score
3053                                  (cdr (cdr kill)))))))))
3054     ;; Return whether this score file needs to be saved.  By Je-haysuss!
3055     updated))
3056
3057 (defun gnus-score-regexp-bad-p (regexp)
3058   "Test whether REGEXP is safe for Gnus scoring.
3059 A regexp is unsafe if it matches newline or a buffer boundary.
3060
3061 If the regexp is good, return nil.  If the regexp is bad, return a
3062 cons cell (SYM . STRING), where the symbol SYM is `new' or `bad'.
3063 In the `new' case, the string is a safe replacement for REGEXP.
3064 In the `bad' case, the string is a unsafe subexpression of REGEXP,
3065 and we do not have a simple replacement to suggest.
3066
3067 See Info node `(gnus)Scoring Tips' for examples of good regular expressions."
3068   (let (case-fold-search)
3069     (and
3070      ;; First, try a relatively fast necessary condition.
3071      ;; Notice ranges (like [^:] or [\t-\r]), \s>, \Sw, \W, \', \`:
3072      (string-match "\n\\|\\\\[SsW`']\\|\\[\\^\\|[\0-\n]-" regexp)
3073      ;; Now break the regexp into tokens, and check each:
3074      (let ((tail regexp)                ; remaining regexp to check
3075            tok                          ; current token
3076            bad                          ; nil, or bad subexpression
3077            new                          ; nil, or replacement regexp so far
3078            end)                         ; length of current token
3079        (while (and (not bad)
3080                    (string-match
3081                     "\\`\\(\\\\[sS]?.\\|\\[\\^?]?[^]]*]\\|[^\\]\\)"
3082                     tail))
3083          (setq end (match-end 0)
3084                tok (substring tail 0 end)
3085                tail (substring tail end))
3086          (if;; Is token `bad' (matching newline or buffer ends)?
3087              (or (member tok '("\n" "\\W" "\\`" "\\'"))
3088                  ;; This next handles "[...]", "\\s.", and "\\S.":
3089                  (and (> end 2) (string-match tok "\n")))
3090              (let ((newtok
3091                     ;; Try to suggest a replacement for tok ...
3092                     (cond ((string-equal tok "\\`") "^") ; or "\\(^\\)"
3093                           ((string-equal tok "\\'") "$") ; or "\\($\\)"
3094                           ((string-match "\\[\\^" tok) ; very common
3095                            (concat (substring tok 0 -1) "\n]")))))
3096                (if newtok
3097                    (setq new
3098                          (concat
3099                           (or new
3100                               ;; good prefix so far:
3101                               (substring regexp 0 (- (+ (length tail) end))))
3102                           newtok))
3103                  ;; No replacement idea, so give up:
3104                  (setq bad tok)))
3105            ;; tok is good, may need to extend new
3106            (and new (setq new (concat new tok)))))
3107        ;; Now return a value:
3108        (cond
3109         (bad (cons 'bad bad))
3110         (new (cons 'new new))
3111         (t nil))))))
3112
3113 (provide 'gnus-score)
3114
3115 ;;; gnus-score.el ends here