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