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