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