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