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