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