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