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