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