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