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