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