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