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