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