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