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