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