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