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