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