Fix my last change.
[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   (if gnus-agent-fetching
1643       nil
1644     (save-excursion
1645       (setq gnus-scores-articles
1646             (sort gnus-scores-articles
1647                   (lambda (a1 a2)
1648                     (< (mail-header-number (car a1))
1649                        (mail-header-number (car a2))))))
1650       (set-buffer nntp-server-buffer)
1651       (save-restriction
1652         (let* ((buffer-read-only nil)
1653                (articles gnus-scores-articles)
1654                (all-scores scores)
1655                (request-func (cond ((string= "head" header)
1656                                     'gnus-request-head)
1657                                    ((string= "body" header)
1658                                     'gnus-request-body)
1659                                    (t 'gnus-request-article)))
1660                entries alist ofunc article last)
1661           (when articles
1662             (setq last (mail-header-number (caar (last articles))))
1663           ;; Not all backends support partial fetching.  In that case,
1664             ;; we just fetch the entire article.
1665             (unless (gnus-check-backend-function
1666                      (and (string-match "^gnus-" (symbol-name request-func))
1667                           (intern (substring (symbol-name request-func)
1668                                              (match-end 0))))
1669                      gnus-newsgroup-name)
1670               (setq ofunc request-func)
1671               (setq request-func 'gnus-request-article))
1672             (while articles
1673               (setq article (mail-header-number (caar articles)))
1674               (gnus-message 7 "Scoring article %s of %s..." article last)
1675               (widen)
1676               (when (funcall request-func article gnus-newsgroup-name)
1677                 (goto-char (point-min))
1678             ;; If just parts of the article is to be searched, but the
1679             ;; backend didn't support partial fetching, we just narrow
1680                 ;; to the relevant parts.
1681                 (when ofunc
1682                   (if (eq ofunc 'gnus-request-head)
1683                       (narrow-to-region
1684                        (point)
1685                        (or (search-forward "\n\n" nil t) (point-max)))
1686                     (narrow-to-region
1687                      (or (search-forward "\n\n" nil t) (point))
1688                      (point-max))))
1689                 (setq scores all-scores)
1690                 ;; Find matches.
1691                 (while scores
1692                   (setq alist (pop scores)
1693                         entries (assoc header alist))
1694                   (while (cdr entries) ;First entry is the header index.
1695                     (let* ((rest (cdr entries))
1696                            (kill (car rest))
1697                            (match (nth 0 kill))
1698                            (type (or (nth 3 kill) 's))
1699                            (score (or (nth 1 kill)
1700                                       gnus-score-interactive-default-score))
1701                            (date (nth 2 kill))
1702                            (found nil)
1703                            (case-fold-search
1704                             (not (or (eq type 'R) (eq type 'S)
1705                                      (eq type 'Regexp) (eq type 'String))))
1706                            (search-func
1707                             (cond ((or (eq type 'r) (eq type 'R)
1708                                        (eq type 'regexp) (eq type 'Regexp))
1709                                    're-search-forward)
1710                                   ((or (eq type 's) (eq type 'S)
1711                                        (eq type 'string) (eq type 'String))
1712                                    'search-forward)
1713                                   (t
1714                                    (error "Invalid match type: %s" type)))))
1715                       (goto-char (point-min))
1716                       (when (funcall search-func match nil t)
1717                         ;; Found a match, update scores.
1718                         (setcdr (car articles) (+ score (cdar articles)))
1719                         (setq found t)
1720                         (when trace
1721                           (push
1722                            (cons (car-safe (rassq alist gnus-score-cache)) kill)
1723                            gnus-score-trace)))
1724                       ;; Update expire date
1725                       (unless trace
1726                         (cond
1727                          ((null date))  ;Permanent entry.
1728                          ((and found gnus-update-score-entry-dates)
1729                           ;; Match, update date.
1730                           (gnus-score-set 'touched '(t) alist)
1731                           (setcar (nthcdr 2 kill) now))
1732                          ((and expire (< date expire)) ;Old entry, remove.
1733                           (gnus-score-set 'touched '(t) alist)
1734                           (setcdr entries (cdr rest))
1735                           (setq rest entries))))
1736                       (setq entries rest)))))
1737               (setq articles (cdr articles)))))))
1738     nil))
1739
1740 (defun gnus-score-thread (scores header now expire &optional trace)
1741   (gnus-score-followup scores header now expire trace t))
1742
1743 (defun gnus-score-followup (scores header now expire &optional trace thread)
1744   (if gnus-agent-fetching
1745       ;; FIXME: It seems doable in fetching mode.
1746       nil
1747     ;; Insert the unique article headers in the buffer.
1748     (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1749           (current-score-file gnus-current-score-file)
1750           (all-scores scores)
1751           ;; gnus-score-index is used as a free variable.
1752           alike last this art entries alist articles
1753           new news)
1754       
1755       ;; Change score file to the adaptive score file.  All entries that
1756       ;; this function makes will be put into this file.
1757       (save-excursion
1758         (set-buffer gnus-summary-buffer)
1759         (gnus-score-load-file
1760          (or gnus-newsgroup-adaptive-score-file
1761              (gnus-score-file-name
1762               gnus-newsgroup-name gnus-adaptive-file-suffix))))
1763
1764       (setq gnus-scores-articles (sort gnus-scores-articles 
1765                                        'gnus-score-string<)
1766             articles gnus-scores-articles)
1767
1768       (erase-buffer)
1769       (while articles
1770         (setq art (car articles)
1771               this (aref (car art) gnus-score-index)
1772               articles (cdr articles))
1773         (if (equal last this)
1774             (push art alike)
1775           (when last
1776             (insert last ?\n)
1777             (put-text-property (1- (point)) (point) 'articles alike))
1778           (setq alike (list art)
1779                 last this)))
1780       (when last ; Bwadr, duplicate code.
1781         (insert last ?\n)
1782         (put-text-property (1- (point)) (point) 'articles alike))
1783
1784       ;; Find matches.
1785       (while scores
1786         (setq alist (car scores)
1787               scores (cdr scores)
1788               entries (assoc header alist))
1789         (while (cdr entries) ;First entry is the header index.
1790           (let* ((rest (cdr entries))
1791                  (kill (car rest))
1792                  (match (nth 0 kill))
1793                  (type (or (nth 3 kill) 's))
1794                  (score (or (nth 1 kill) gnus-score-interactive-default-score))
1795                  (date (nth 2 kill))
1796                  (found nil)
1797                  (mt (aref (symbol-name type) 0))
1798                  (case-fold-search
1799                   (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1800                  (dmt (downcase mt))
1801                  (search-func
1802                   (cond ((= dmt ?r) 're-search-forward)
1803                         ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1804                         (t (error "Invalid match type: %s" type))))
1805                  arts art)
1806             (goto-char (point-min))
1807             (if (= dmt ?e)
1808                 (while (funcall search-func match nil t)
1809                   (and (= (progn (beginning-of-line) (point))
1810                           (match-beginning 0))
1811                        (= (progn (end-of-line) (point))
1812                           (match-end 0))
1813                        (progn
1814                          (setq found (setq arts (get-text-property
1815                                                  (point) 'articles)))
1816                          ;; Found a match, update scores.
1817                          (while arts
1818                            (setq art (car arts)
1819                                  arts (cdr arts))
1820                            (gnus-score-add-followups
1821                             (car art) score all-scores thread))))
1822                   (end-of-line))
1823               (while (funcall search-func match nil t)
1824                 (end-of-line)
1825                 (setq found (setq arts (get-text-property (point) 'articles)))
1826                 ;; Found a match, update scores.
1827                 (while (setq art (pop arts))
1828                   (when (setq new (gnus-score-add-followups
1829                                    (car art) score all-scores thread))
1830                     (push new news)))))
1831             ;; Update expire date
1832             (cond ((null date))         ;Permanent entry.
1833                   ((and found gnus-update-score-entry-dates) 
1834                                         ;Match, update date.
1835                    (gnus-score-set 'touched '(t) alist)
1836                    (setcar (nthcdr 2 kill) now))
1837                   ((and expire (< date expire)) ;Old entry, remove.
1838                    (gnus-score-set 'touched '(t) alist)
1839                    (setcdr entries (cdr rest))
1840                    (setq rest entries)))
1841             (setq entries rest))))
1842       ;; We change the score file back to the previous one.
1843       (save-excursion
1844         (set-buffer gnus-summary-buffer)
1845         (gnus-score-load-file current-score-file))
1846       (list (cons "references" news)))))
1847
1848 (defun gnus-score-add-followups (header score scores &optional thread)
1849   "Add a score entry to the adapt file."
1850   (save-excursion
1851     (set-buffer gnus-summary-buffer)
1852     (let* ((id (mail-header-id header))
1853            (scores (car scores))
1854            entry dont)
1855       ;; Don't enter a score if there already is one.
1856       (while (setq entry (pop scores))
1857         (and (equal "references" (car entry))
1858              (or (null (nth 3 (cadr entry)))
1859                  (eq 's (nth 3 (cadr entry))))
1860              (assoc id entry)
1861              (setq dont t)))
1862       (unless dont
1863         (gnus-summary-score-entry
1864          (if thread "thread" "references")
1865          id 's score (current-time-string) nil t)))))
1866
1867 (defun gnus-score-string (score-list header now expire &optional trace)
1868   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1869   ;; Update matching entries to NOW and remove unmatched entries older
1870   ;; than EXPIRE.
1871
1872   ;; Insert the unique article headers in the buffer.
1873   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1874         ;; gnus-score-index is used as a free variable.
1875         (simplify (and gnus-score-thread-simplify
1876                        (string= "subject" header)))
1877         alike last this art entries alist articles
1878         fuzzies arts words kill)
1879
1880     ;; Sorting the articles costs os O(N*log N) but will allow us to
1881     ;; only match with each unique header.  Thus the actual matching
1882     ;; will be O(M*U) where M is the number of strings to match with,
1883     ;; and U is the number of unique headers.  It is assumed (but
1884     ;; untested) this will be a net win because of the large constant
1885     ;; factor involved with string matching.
1886     (setq gnus-scores-articles
1887           ;; We cannot string-sort the extra headers list.  *sigh*
1888           (if (= gnus-score-index 9)
1889               gnus-scores-articles
1890             (sort gnus-scores-articles 'gnus-score-string<))
1891           articles gnus-scores-articles)
1892
1893     (erase-buffer)
1894     (while (setq art (pop articles))
1895       (setq this (aref (car art) gnus-score-index))
1896
1897       ;; If we're working with non-standard headers, we are stuck
1898       ;; with working on them as a group.  What a hassle.
1899       ;; Just wait 'til you see what horrors we commit against `match'...
1900       (if (= gnus-score-index 9)
1901           (setq this (prin1-to-string this))) ; ick.
1902
1903       (if simplify
1904           (setq this (gnus-map-function gnus-simplify-subject-functions this)))
1905       (if (equal last this)
1906           ;; O(N*H) cons-cells used here, where H is the number of
1907           ;; headers.
1908           (push art alike)
1909         (when last
1910           ;; Insert the line, with a text property on the
1911           ;; terminating newline referring to the articles with
1912           ;; this line.
1913           (insert last ?\n)
1914           (put-text-property (1- (point)) (point) 'articles alike))
1915         (setq alike (list art)
1916               last this)))
1917     (when last                          ; Bwadr, duplicate code.
1918       (insert last ?\n)
1919       (put-text-property (1- (point)) (point) 'articles alike))
1920
1921     ;; Go through all the score alists and pick out the entries
1922     ;; for this header.
1923     (while score-list
1924       (setq alist (pop score-list)
1925             ;; There's only one instance of this header for
1926             ;; each score alist.
1927             entries (assoc header alist))
1928       (while (cdr entries)              ;First entry is the header index.
1929         (let* ((kill (cadr entries))
1930                (type (or (nth 3 kill) 's))
1931                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1932                (date (nth 2 kill))
1933                (extra (nth 4 kill))     ; non-standard header; string.
1934                (found nil)
1935                (mt (aref (symbol-name type) 0))
1936                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
1937                (dmt (downcase mt))
1938                ;; Assume user already simplified regexp and fuzzies
1939                (match (if (and simplify (not (memq dmt '(?f ?r))))
1940                           (gnus-map-function
1941                            gnus-simplify-subject-functions
1942                            (nth 0 kill))
1943                         (nth 0 kill)))
1944                (search-func
1945                 (cond ((= dmt ?r) 're-search-forward)
1946                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1947                       ((= dmt ?w) nil)
1948                       (t (error "Invalid match type: %s" type)))))
1949
1950           ;; Evil hackery to make match usable in non-standard headers.
1951           (when extra
1952             (setq match (concat "[ (](" extra " \\. \"[^)]*"
1953                                 match "[^(]*\")[ )]")
1954                   search-func 're-search-forward)) ; XXX danger?!?
1955
1956           (cond
1957            ;; Fuzzy matches.  We save these for later.
1958            ((= dmt ?f)
1959             (push (cons entries alist) fuzzies)
1960             (setq entries (cdr entries)))
1961            ;; Word matches.  Save these for even later.
1962            ((= dmt ?w)
1963             (push (cons entries alist) words)
1964             (setq entries (cdr entries)))
1965            ;; Exact matches.
1966            ((= dmt ?e)
1967             ;; Do exact matching.
1968             (goto-char (point-min))
1969             (while (and (not (eobp))
1970                         (funcall search-func match nil t))
1971               ;; Is it really exact?
1972               (and (eolp)
1973                    (= (gnus-point-at-bol) (match-beginning 0))
1974                    ;; Yup.
1975                    (progn
1976                      (setq found (setq arts (get-text-property
1977                                              (point) 'articles)))
1978                      ;; Found a match, update scores.
1979                      (if trace
1980                          (while (setq art (pop arts))
1981                            (setcdr art (+ score (cdr art)))
1982                            (push
1983                             (cons
1984                              (car-safe (rassq alist gnus-score-cache))
1985                              kill)
1986                             gnus-score-trace))
1987                        (while (setq art (pop arts))
1988                          (setcdr art (+ score (cdr art)))))))
1989               (forward-line 1))
1990             ;; Update expiry date
1991             (if trace
1992                 (setq entries (cdr entries))
1993               (cond
1994                ;; Permanent entry.
1995                ((null date)
1996                 (setq entries (cdr entries)))
1997                ;; We have a match, so we update the date.
1998                ((and found gnus-update-score-entry-dates)
1999                 (gnus-score-set 'touched '(t) alist)
2000                 (setcar (nthcdr 2 kill) now)
2001                 (setq entries (cdr entries)))
2002                ;; This entry has expired, so we remove it.
2003                ((and expire (< date expire))
2004                 (gnus-score-set 'touched '(t) alist)
2005                 (setcdr entries (cddr entries)))
2006                ;; No match; go to next entry.
2007                (t
2008                 (setq entries (cdr entries))))))
2009            ;; Regexp and substring matching.
2010            (t
2011             (goto-char (point-min))
2012             (when (string= match "")
2013               (setq match "\n"))
2014             (while (and (not (eobp))
2015                         (funcall search-func match nil t))
2016               (goto-char (match-beginning 0))
2017               (end-of-line)
2018               (setq found (setq arts (get-text-property (point) 'articles)))
2019               ;; Found a match, update scores.
2020               (if trace
2021                   (while (setq art (pop arts))
2022                     (setcdr art (+ score (cdr art)))
2023                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
2024                           gnus-score-trace))
2025                 (while (setq art (pop arts))
2026                   (setcdr art (+ score (cdr art)))))
2027               (forward-line 1))
2028             ;; Update expiry date
2029             (if trace
2030                 (setq entries (cdr entries))
2031               (cond
2032                ;; Permanent entry.
2033                ((null date)
2034                 (setq entries (cdr entries)))
2035                ;; We have a match, so we update the date.
2036                ((and found gnus-update-score-entry-dates)
2037                 (gnus-score-set 'touched '(t) alist)
2038                 (setcar (nthcdr 2 kill) now)
2039                 (setq entries (cdr entries)))
2040                ;; This entry has expired, so we remove it.
2041                ((and expire (< date expire))
2042                 (gnus-score-set 'touched '(t) alist)
2043                 (setcdr entries (cddr entries)))
2044                ;; No match; go to next entry.
2045                (t
2046                 (setq entries (cdr entries))))))))))
2047
2048     ;; Find fuzzy matches.
2049     (when fuzzies
2050       ;; Simplify the entire buffer for easy matching.
2051       (gnus-simplify-buffer-fuzzy)
2052       (while (setq kill (cadaar fuzzies))
2053         (let* ((match (nth 0 kill))
2054                (type (nth 3 kill))
2055                (score (or (nth 1 kill) gnus-score-interactive-default-score))
2056                (date (nth 2 kill))
2057                (mt (aref (symbol-name type) 0))
2058                (case-fold-search (not (= mt ?F)))
2059                found)
2060           (goto-char (point-min))
2061           (while (and (not (eobp))
2062                       (search-forward match nil t))
2063             (when (and (= (gnus-point-at-bol) (match-beginning 0))
2064                        (eolp))
2065               (setq found (setq arts (get-text-property (point) 'articles)))
2066               (if trace
2067                   (while (setq art (pop arts))
2068                     (setcdr art (+ score (cdr art)))
2069                     (push (cons
2070                            (car-safe (rassq (cdar fuzzies) gnus-score-cache))
2071                            kill)
2072                           gnus-score-trace))
2073                 ;; Found a match, update scores.
2074                 (while (setq art (pop arts))
2075                   (setcdr art (+ score (cdr art))))))
2076             (forward-line 1))
2077           ;; Update expiry date
2078           (if (not trace)
2079               (cond
2080                ;; Permanent.
2081                ((null date)
2082                 ;; Do nothing.
2083                 )
2084                ;; Match, update date.
2085                ((and found gnus-update-score-entry-dates)
2086                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2087                 (setcar (nthcdr 2 kill) now))
2088                ;; Old entry, remove.
2089                ((and expire (< date expire))
2090                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2091                 (setcdr (caar fuzzies) (cddaar fuzzies)))))
2092           (setq fuzzies (cdr fuzzies)))))
2093
2094     (when words
2095       ;; Enter all words into the hashtb.
2096       (let ((hashtb (gnus-make-hashtable
2097                      (* 10 (count-lines (point-min) (point-max))))))
2098         (gnus-enter-score-words-into-hashtb hashtb)
2099         (while (setq kill (cadaar words))
2100           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
2101                  (date (nth 2 kill))
2102                  found)
2103             (when (setq arts (intern-soft (nth 0 kill) hashtb))
2104               (setq arts (symbol-value arts))
2105               (setq found t)
2106               (if trace
2107                   (while (setq art (pop arts))
2108                     (setcdr art (+ score (cdr art)))
2109                     (push (cons
2110                            (car-safe (rassq (cdar words) gnus-score-cache))
2111                            kill)
2112                           gnus-score-trace))
2113                 ;; Found a match, update scores.
2114                 (while (setq art (pop arts))
2115                   (setcdr art (+ score (cdr art))))))
2116             ;; Update expiry date
2117             (if (not trace)
2118                 (cond
2119                  ;; Permanent.
2120                  ((null date)
2121                   ;; Do nothing.
2122                   )
2123                  ;; Match, update date.
2124                  ((and found gnus-update-score-entry-dates)
2125                   (gnus-score-set 'touched '(t) (cdar words))
2126                   (setcar (nthcdr 2 kill) now))
2127                  ;; Old entry, remove.
2128                  ((and expire (< date expire))
2129                   (gnus-score-set 'touched '(t) (cdar words))
2130                   (setcdr (caar words) (cddaar words)))))
2131             (setq words (cdr words))))))
2132     nil))
2133
2134 (defun gnus-enter-score-words-into-hashtb (hashtb)
2135   ;; Find all the words in the buffer and enter them into
2136   ;; the hashtable.
2137   (let ((syntab (syntax-table))
2138         word val)
2139     (goto-char (point-min))
2140     (unwind-protect
2141         (progn
2142           (set-syntax-table gnus-adaptive-word-syntax-table)
2143           (while (re-search-forward "\\b\\w+\\b" nil t)
2144             (setq val
2145                   (gnus-gethash
2146                    (setq word (downcase (buffer-substring
2147                                          (match-beginning 0) (match-end 0))))
2148                    hashtb))
2149             (gnus-sethash
2150              word
2151              (append (get-text-property (gnus-point-at-eol) 'articles) val)
2152              hashtb)))
2153       (set-syntax-table syntab))
2154     ;; Make all the ignorable words ignored.
2155     (let ((ignored (append gnus-ignored-adaptive-words
2156                            (if gnus-adaptive-word-no-group-words
2157                                (message-tokenize-header
2158                                 (gnus-group-real-name gnus-newsgroup-name)
2159                                 "."))
2160                            gnus-default-ignored-adaptive-words)))
2161       (while ignored
2162         (gnus-sethash (pop ignored) nil hashtb)))))
2163
2164 (defun gnus-score-string< (a1 a2)
2165   ;; Compare headers in articles A2 and A2.
2166   ;; The header index used is the free variable `gnus-score-index'.
2167   (string-lessp (aref (car a1) gnus-score-index)
2168                 (aref (car a2) gnus-score-index)))
2169
2170 (defun gnus-current-score-file-nondirectory (&optional score-file)
2171   (let ((score-file (or score-file gnus-current-score-file)))
2172     (if score-file
2173         (gnus-short-group-name (file-name-nondirectory score-file))
2174       "none")))
2175
2176 (defun gnus-score-adaptive ()
2177   "Create adaptive score rules for this newsgroup."
2178   (when gnus-newsgroup-adaptive
2179     ;; We change the score file to the adaptive score file.
2180     (save-excursion
2181       (set-buffer gnus-summary-buffer)
2182       (gnus-score-load-file
2183        (or gnus-newsgroup-adaptive-score-file
2184            (gnus-home-score-file gnus-newsgroup-name t)
2185            (gnus-score-file-name
2186             gnus-newsgroup-name gnus-adaptive-file-suffix))))
2187     ;; Perform ordinary line scoring.
2188     (when (or (not (listp gnus-newsgroup-adaptive))
2189               (memq 'line gnus-newsgroup-adaptive))
2190       (save-excursion
2191         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
2192                (alist malist)
2193                (date (current-time-string))
2194                (data gnus-newsgroup-data)
2195                elem headers match func)
2196           ;; First we transform the adaptive rule alist into something
2197           ;; that's faster to process.
2198           (while malist
2199             (setq elem (car malist))
2200             (when (symbolp (car elem))
2201               (setcar elem (symbol-value (car elem))))
2202             (setq elem (cdr elem))
2203             (while elem
2204               (when (fboundp
2205                      (setq func
2206                            (intern
2207                             (concat "mail-header-"
2208                                     (if (eq (caar elem) 'followup)
2209                                         "message-id"
2210                                       (downcase (symbol-name (caar elem))))))))
2211                 (setcdr (car elem)
2212                         (cons (if (eq (caar elem) 'followup)
2213                                   "references"
2214                                 (symbol-name (caar elem)))
2215                               (cdar elem)))
2216                 (setcar (car elem)
2217                         `(lambda (h)
2218                            (,func h))))
2219               (setq elem (cdr elem)))
2220             (setq malist (cdr malist)))
2221           ;; Then we score away.
2222           (while data
2223             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2224             (if (or (not elem)
2225                     (gnus-data-pseudo-p (car data)))
2226                 ()
2227               (when (setq headers (gnus-data-header (car data)))
2228                 (while elem
2229                   (setq match (funcall (caar elem) headers))
2230                   (gnus-summary-score-entry
2231                    (nth 1 (car elem)) match
2232                    (cond
2233                     ((numberp match)
2234                      '=)
2235                     ((equal (nth 1 (car elem)) "date")
2236                      'a)
2237                     (t
2238                      ;; Whether we use substring or exact matches is
2239                      ;; controlled here.
2240                      (if (or (not gnus-score-exact-adapt-limit)
2241                              (< (length match) gnus-score-exact-adapt-limit))
2242                          'e
2243                        (if (equal (nth 1 (car elem)) "subject")
2244                            'f 's))))
2245                    (nth 2 (car elem)) date nil t)
2246                   (setq elem (cdr elem)))))
2247             (setq data (cdr data))))))
2248
2249     ;; Perform adaptive word scoring.
2250     (when (and (listp gnus-newsgroup-adaptive)
2251                (memq 'word gnus-newsgroup-adaptive))
2252       (with-temp-buffer
2253         (let* ((hashtb (gnus-make-hashtable 1000))
2254                (date (date-to-day (current-time-string)))
2255                (data gnus-newsgroup-data)
2256                (syntab (syntax-table))
2257                word d score val)
2258           (unwind-protect
2259               (progn
2260                 (set-syntax-table gnus-adaptive-word-syntax-table)
2261                 ;; Go through all articles.
2262                 (while (setq d (pop data))
2263                   (when (and
2264                          (not (gnus-data-pseudo-p d))
2265                          (setq score
2266                                (cdr (assq
2267                                      (gnus-data-mark d)
2268                                      gnus-adaptive-word-score-alist))))
2269                     ;; This article has a mark that should lead to
2270                     ;; adaptive word rules, so we insert the subject
2271                     ;; and find all words in that string.
2272                     (insert (mail-header-subject (gnus-data-header d)))
2273                     (downcase-region (point-min) (point-max))
2274                     (goto-char (point-min))
2275                     (while (re-search-forward "\\b\\w+\\b" nil t)
2276                       ;; Put the word and score into the hashtb.
2277                       (setq val (gnus-gethash (setq word (match-string 0))
2278                                               hashtb))
2279                       (setq val (+ score (or val 0)))
2280                       (if (and gnus-adaptive-word-minimum
2281                                (< val gnus-adaptive-word-minimum))
2282                           (setq val gnus-adaptive-word-minimum))
2283                       (gnus-sethash word val hashtb))
2284                     (erase-buffer))))
2285             (set-syntax-table syntab))
2286           ;; Make all the ignorable words ignored.
2287           (let ((ignored (append gnus-ignored-adaptive-words
2288                                  (if gnus-adaptive-word-no-group-words
2289                                      (message-tokenize-header
2290                                       (gnus-group-real-name
2291                                        gnus-newsgroup-name)
2292                                       "."))
2293                                  gnus-default-ignored-adaptive-words)))
2294             (while ignored
2295               (gnus-sethash (pop ignored) nil hashtb)))
2296           ;; Now we have all the words and scores, so we
2297           ;; add these rules to the ADAPT file.
2298           (set-buffer gnus-summary-buffer)
2299           (mapatoms
2300            (lambda (word)
2301              (when (symbol-value word)
2302                (gnus-summary-score-entry
2303                 "subject" (symbol-name word) 'w (symbol-value word)
2304                 date nil t)))
2305            hashtb))))))
2306
2307 (defun gnus-score-edit-done ()
2308   (let ((bufnam (buffer-file-name (current-buffer)))
2309         (winconf gnus-prev-winconf))
2310     (when winconf
2311       (set-window-configuration winconf))
2312     (gnus-score-remove-from-cache bufnam)
2313     (gnus-score-load-file bufnam)))
2314
2315 (defun gnus-score-find-trace ()
2316   "Find all score rules that applies to the current article."
2317   (interactive)
2318   (let ((old-scored gnus-newsgroup-scored))
2319     (let ((gnus-newsgroup-headers
2320            (list (gnus-summary-article-header)))
2321           (gnus-newsgroup-scored nil)
2322           trace)
2323       (save-excursion
2324         (nnheader-set-temp-buffer "*Score Trace*"))
2325       (setq gnus-score-trace nil)
2326       (gnus-possibly-score-headers 'trace)
2327       (if (not (setq trace gnus-score-trace))
2328           (gnus-error
2329            1 "No score rules apply to the current article (default score %d)."
2330            gnus-summary-default-score)
2331         (set-buffer "*Score Trace*")
2332         (setq truncate-lines t)
2333         (while trace
2334           (insert (format "%S  ->  %s\n" (cdar trace)
2335                           (or (caar trace) "(non-file rule)")))
2336           (setq trace (cdr trace)))
2337         (goto-char (point-min))
2338         (gnus-configure-windows 'score-trace)))
2339     (set-buffer gnus-summary-buffer)
2340     (setq gnus-newsgroup-scored old-scored)))
2341
2342 (defun gnus-score-find-favourite-words ()
2343   "List words used in scoring."
2344   (interactive)
2345   (let ((alists (gnus-score-load-files (gnus-all-score-files)))
2346         alist rule rules kill)
2347     ;; Go through all the score alists for this group
2348     ;; and find all `w' rules.
2349     (while (setq alist (pop alists))
2350       (while (setq rule (pop alist))
2351         (when (and (stringp (car rule))
2352                    (equal "subject" (downcase (pop rule))))
2353           (while (setq kill (pop rule))
2354             (when (memq (nth 3 kill) '(w W word Word))
2355               (push (cons (or (nth 1 kill)
2356                               gnus-score-interactive-default-score)
2357                           (car kill))
2358                     rules))))))
2359     (setq rules (sort rules (lambda (r1 r2)
2360                               (string-lessp (cdr r1) (cdr r2)))))
2361     ;; Add up words that have appeared several times.
2362     (let ((r rules))
2363       (while (cdr r)
2364         (if (equal (cdar r) (cdadr r))
2365             (progn
2366               (setcar (car r) (+ (caar r) (caadr r)))
2367               (setcdr r (cddr r)))
2368           (pop r))))
2369     ;; Insert the words.
2370     (nnheader-set-temp-buffer "*Score Words*")
2371     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2372         (gnus-error 3 "No word score rules")
2373       (while rules
2374         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2375         (pop rules))
2376       (goto-char (point-min))
2377       (gnus-configure-windows 'score-words))))
2378
2379 (defun gnus-summary-rescore ()
2380   "Redo the entire scoring process in the current summary."
2381   (interactive)
2382   (gnus-score-save)
2383   (setq gnus-score-cache nil)
2384   (setq gnus-newsgroup-scored nil)
2385   (gnus-possibly-score-headers)
2386   (gnus-score-update-all-lines))
2387
2388 (defun gnus-score-flush-cache ()
2389   "Flush the cache of score files."
2390   (interactive)
2391   (gnus-score-save)
2392   (setq gnus-score-cache nil
2393         gnus-score-alist nil
2394         gnus-short-name-score-file-cache nil)
2395   (gnus-message 6 "The score cache is now flushed"))
2396
2397 (gnus-add-shutdown 'gnus-score-close 'gnus)
2398
2399 (defvar gnus-score-file-alist-cache nil)
2400
2401 (defun gnus-score-close ()
2402   "Clear all internal score variables."
2403   (setq gnus-score-cache nil
2404         gnus-internal-global-score-files nil
2405         gnus-score-file-list nil
2406         gnus-score-file-alist-cache nil))
2407
2408 ;; Summary score marking commands.
2409
2410 (defun gnus-summary-raise-same-subject-and-select (score)
2411   "Raise articles which has the same subject with SCORE and select the next."
2412   (interactive "p")
2413   (let ((subject (gnus-summary-article-subject)))
2414     (gnus-summary-raise-score score)
2415     (while (gnus-summary-find-subject subject)
2416       (gnus-summary-raise-score score))
2417     (gnus-summary-next-article t)))
2418
2419 (defun gnus-summary-raise-same-subject (score)
2420   "Raise articles which has the same subject with SCORE."
2421   (interactive "p")
2422   (let ((subject (gnus-summary-article-subject)))
2423     (gnus-summary-raise-score score)
2424     (while (gnus-summary-find-subject subject)
2425       (gnus-summary-raise-score score))
2426     (gnus-summary-next-subject 1 t)))
2427
2428 (defun gnus-score-delta-default (level)
2429   (if level (prefix-numeric-value level)
2430     gnus-score-interactive-default-score))
2431
2432 (defun gnus-summary-raise-thread (&optional score)
2433   "Raise the score of the articles in the current thread with SCORE."
2434   (interactive "P")
2435   (setq score (gnus-score-delta-default score))
2436   (let (e)
2437     (save-excursion
2438       (let ((articles (gnus-summary-articles-in-thread)))
2439         (while articles
2440           (gnus-summary-goto-subject (car articles))
2441           (gnus-summary-raise-score score)
2442           (setq articles (cdr articles))))
2443       (setq e (point)))
2444     (let ((gnus-summary-check-current t))
2445       (unless (zerop (gnus-summary-next-subject 1 t))
2446         (goto-char e))))
2447   (gnus-summary-recenter)
2448   (gnus-summary-position-point)
2449   (gnus-set-mode-line 'summary))
2450
2451 (defun gnus-summary-lower-same-subject-and-select (score)
2452   "Raise articles which has the same subject with SCORE and select the next."
2453   (interactive "p")
2454   (gnus-summary-raise-same-subject-and-select (- score)))
2455
2456 (defun gnus-summary-lower-same-subject (score)
2457   "Raise articles which has the same subject with SCORE."
2458   (interactive "p")
2459   (gnus-summary-raise-same-subject (- score)))
2460
2461 (defun gnus-summary-lower-thread (&optional score)
2462   "Lower score of articles in the current thread with SCORE."
2463   (interactive "P")
2464   (gnus-summary-raise-thread (- (1- (gnus-score-delta-default score)))))
2465
2466 ;;; Finding score files.
2467
2468 (defun gnus-score-score-files (group)
2469   "Return a list of all possible score files."
2470   ;; Search and set any global score files.
2471   (when gnus-global-score-files
2472     (unless gnus-internal-global-score-files
2473       (gnus-score-search-global-directories gnus-global-score-files)))
2474   ;; Fix the kill-file dir variable.
2475   (setq gnus-kill-files-directory
2476         (file-name-as-directory gnus-kill-files-directory))
2477   ;; If we can't read it, there are no score files.
2478   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2479       (setq gnus-score-file-list nil)
2480     (if (not (gnus-use-long-file-name 'not-score))
2481         ;; We do not use long file names, so we have to do some
2482         ;; directory traversing.
2483         (setq gnus-score-file-list
2484               (cons nil
2485                     (or gnus-short-name-score-file-cache
2486                         (prog2
2487                             (gnus-message 6 "Finding all score files...")
2488                             (setq gnus-short-name-score-file-cache
2489                                   (gnus-score-score-files-1
2490                                    gnus-kill-files-directory))
2491                           (gnus-message 6 "Finding all score files...done")))))
2492       ;; We want long file names.
2493       (when (or (not gnus-score-file-list)
2494                 (not (car gnus-score-file-list))
2495                 (gnus-file-newer-than gnus-kill-files-directory
2496                                       (car gnus-score-file-list)))
2497         (setq gnus-score-file-list
2498               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2499                     (nreverse
2500                      (directory-files
2501                       gnus-kill-files-directory t
2502                       (gnus-score-file-regexp)))))))
2503     (cdr gnus-score-file-list)))
2504
2505 (defun gnus-score-score-files-1 (dir)
2506   "Return all possible score files under DIR."
2507   (let ((files (list (expand-file-name dir)))
2508         (regexp (gnus-score-file-regexp))
2509         (case-fold-search nil)
2510         seen out file)
2511     (while (setq file (pop files))
2512       (cond
2513        ;; Ignore files that start with a dot.
2514        ((string-match "^\\." (file-name-nondirectory file))
2515         nil)
2516        ;; Add subtrees of directory to also be searched.
2517        ((and (file-directory-p file)
2518              (not (member (file-truename file) seen)))
2519         (push (file-truename file) seen)
2520         (setq files (nconc (directory-files file t nil t) files)))
2521        ;; Add files to the list of score files.
2522        ((string-match regexp file)
2523         (push file out))))
2524     (or out
2525         ;; Return a dummy value.
2526         (list "~/News/this.file.does.not.exist.SCORE"))))
2527
2528 (defun gnus-score-file-regexp ()
2529   "Return a regexp that match all score files."
2530   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2531           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2532
2533 (defun gnus-score-find-bnews (group)
2534   "Return a list of score files for GROUP.
2535 The score files are those files in the ~/News/ directory which matches
2536 GROUP using BNews sys file syntax."
2537   (let* ((sfiles (append (gnus-score-score-files group)
2538                          gnus-internal-global-score-files))
2539          (kill-dir (file-name-as-directory
2540                     (expand-file-name gnus-kill-files-directory)))
2541          (klen (length kill-dir))
2542          (score-regexp (gnus-score-file-regexp))
2543          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2544          (group-trans (nnheader-translate-file-chars group t))
2545          ofiles not-match regexp)
2546     (save-excursion
2547       (set-buffer (gnus-get-buffer-create "*gnus score files*"))
2548       (buffer-disable-undo)
2549       ;; Go through all score file names and create regexp with them
2550       ;; as the source.
2551       (while sfiles
2552         (erase-buffer)
2553         (insert (car sfiles))
2554         (goto-char (point-min))
2555         ;; First remove the suffix itself.
2556         (when (re-search-forward (concat "." score-regexp) nil t)
2557           (replace-match "" t t)
2558           (goto-char (point-min))
2559           (if (looking-at (regexp-quote kill-dir))
2560               ;; If the file name was just "SCORE", `klen' is one character
2561               ;; too much.
2562               (delete-char (min (1- (point-max)) klen))
2563             (goto-char (point-max))
2564             (search-backward (string directory-sep-char))
2565             (delete-region (1+ (point)) (point-min)))
2566           ;; If short file names were used, we have to translate slashes.
2567           (goto-char (point-min))
2568           (let ((regexp (concat
2569                          "[/:" (if trans (char-to-string trans) "") "]")))
2570             (while (re-search-forward regexp nil t)
2571               (replace-match "." t t)))
2572           ;; Kludge to get rid of "nntp+" problems.
2573           (goto-char (point-min))
2574           (when (looking-at "nn[a-z]+\\+")
2575             (search-forward "+")
2576             (forward-char -1)
2577             (insert "\\")
2578             (forward-char 1))
2579           ;; Kludge to deal with "++".
2580           (while (search-forward "+" nil t)
2581             (replace-match "\\+" t t))
2582           ;; Translate "all" to ".*".
2583           (goto-char (point-min))
2584           (while (search-forward "all" nil t)
2585             (replace-match ".*" t t))
2586           (goto-char (point-min))
2587           ;; Deal with "not."s.
2588           (if (looking-at "not.")
2589               (progn
2590                 (setq not-match t)
2591                 (setq regexp
2592                       (concat "^" (buffer-substring 5 (point-max)) "$")))
2593             (setq regexp (concat "^" (buffer-substring 1 (point-max)) "$"))
2594             (setq not-match nil))
2595           ;; Finally - if this resulting regexp matches the group name,
2596           ;; we add this score file to the list of score files
2597           ;; applicable to this group.
2598           (when (or (and not-match
2599                          (ignore-errors
2600                            (not (string-match regexp group-trans))))
2601                     (and (not not-match)
2602                          (ignore-errors (string-match regexp group-trans))))
2603             (push (car sfiles) ofiles)))
2604         (setq sfiles (cdr sfiles)))
2605       (kill-buffer (current-buffer))
2606       ;; Slight kludge here - the last score file returned should be
2607       ;; the local score file, whether it exists or not.  This is so
2608       ;; that any score commands the user enters will go to the right
2609       ;; file, and not end up in some global score file.
2610       (let ((localscore (gnus-score-file-name group)))
2611         (setq ofiles (cons localscore (delete localscore ofiles))))
2612       (gnus-sort-score-files (nreverse ofiles)))))
2613
2614 (defun gnus-score-find-single (group)
2615   "Return list containing the score file for GROUP."
2616   (list (or gnus-newsgroup-adaptive-score-file
2617             (gnus-score-file-name group gnus-adaptive-file-suffix))
2618         (gnus-score-file-name group)))
2619
2620 (defun gnus-score-find-hierarchical (group)
2621   "Return list of score files for GROUP.
2622 This includes the score file for the group and all its parents."
2623   (let* ((prefix (gnus-group-real-prefix group))
2624          (all (list nil))
2625          (group (gnus-group-real-name group))
2626          (start 0))
2627     (while (string-match "\\." group (1+ start))
2628       (setq start (match-beginning 0))
2629       (push (substring group 0 start) all))
2630     (push group all)
2631     (setq all
2632           (nconc
2633            (mapcar (lambda (group)
2634                      (gnus-score-file-name group gnus-adaptive-file-suffix))
2635                    (setq all (nreverse all)))
2636            (mapcar 'gnus-score-file-name all)))
2637     (if (equal prefix "")
2638         all
2639       (mapcar
2640        (lambda (file)
2641          (nnheader-translate-file-chars
2642           (concat (file-name-directory file) prefix
2643                   (file-name-nondirectory file))))
2644        all))))
2645
2646 (defun gnus-score-file-rank (file)
2647   "Return a number that says how specific score FILE is.
2648 Destroys the current buffer."
2649   (if (member file gnus-internal-global-score-files)
2650       0
2651     (when (string-match
2652            (concat "^" (regexp-quote
2653                         (expand-file-name
2654                          (file-name-as-directory gnus-kill-files-directory))))
2655            file)
2656       (setq file (substring file (match-end 0))))
2657     (insert file)
2658     (goto-char (point-min))
2659     (let ((beg (point))
2660           elems)
2661       (while (re-search-forward "[./]" nil t)
2662         (push (buffer-substring beg (1- (point)))
2663               elems))
2664       (erase-buffer)
2665       (setq elems (delete "all" elems))
2666       (length elems))))
2667
2668 (defun gnus-sort-score-files (files)
2669   "Sort FILES so that the most general files come first."
2670   (with-temp-buffer
2671     (let ((alist
2672            (mapcar
2673             (lambda (file)
2674               (cons (inline (gnus-score-file-rank file)) file))
2675             files)))
2676       (mapcar
2677        (lambda (f) (cdr f))
2678        (sort alist 'car-less-than-car)))))
2679
2680 (defun gnus-score-find-alist (group)
2681   "Return list of score files for GROUP.
2682 The list is determined from the variable gnus-score-file-alist."
2683   (let ((alist gnus-score-file-multiple-match-alist)
2684         score-files)
2685     ;; if this group has been seen before, return the cached entry
2686     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2687         (cdr score-files)               ;ensures caching groups with no matches
2688       ;; handle the multiple match alist
2689       (while alist
2690         (when (string-match (caar alist) group)
2691           (setq score-files
2692                 (nconc score-files (copy-sequence (cdar alist)))))
2693         (setq alist (cdr alist)))
2694       (setq alist gnus-score-file-single-match-alist)
2695       ;; handle the single match alist
2696       (while alist
2697         (when (string-match (caar alist) group)
2698           ;; progn used just in case ("regexp") has no files
2699           ;; and score-files is still nil.  -sj
2700           ;; this can be construed as a "stop searching here" feature :>
2701           ;; and used to simplify regexps in the single-alist
2702           (setq score-files
2703                 (nconc score-files (copy-sequence (cdar alist))))
2704           (setq alist nil))
2705         (setq alist (cdr alist)))
2706       ;; cache the score files
2707       (push (cons group score-files) gnus-score-file-alist-cache)
2708       score-files)))
2709
2710 (defun gnus-all-score-files (&optional group)
2711   "Return a list of all score files for the current group."
2712   (let ((funcs gnus-score-find-score-files-function)
2713         (group (or group gnus-newsgroup-name))
2714         score-files)
2715     (when group
2716       ;; Make sure funcs is a list.
2717       (and funcs
2718            (not (listp funcs))
2719            (setq funcs (list funcs)))
2720       (when gnus-score-use-all-scores
2721         ;; Get the initial score files for this group.
2722         (when funcs
2723           (setq score-files (nreverse (gnus-score-find-alist group))))
2724         ;; Add any home adapt files.
2725         (let ((home (gnus-home-score-file group t)))
2726           (when home
2727             (push home score-files)
2728             (setq gnus-newsgroup-adaptive-score-file home)))
2729         ;; Check whether there is a `adapt-file' group parameter.
2730         (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2731           (when param-file
2732             (push param-file score-files)
2733             (setq gnus-newsgroup-adaptive-score-file param-file))))
2734       ;; Go through all the functions for finding score files (or actual
2735       ;; scores) and add them to a list.
2736       (while funcs
2737         (when (gnus-functionp (car funcs))
2738           (setq score-files
2739                 (nconc score-files (nreverse (funcall (car funcs) group)))))
2740         (setq funcs (cdr funcs)))
2741       (when gnus-score-use-all-scores
2742         ;; Add any home score files.
2743         (let ((home (gnus-home-score-file group)))
2744           (when home
2745             (push home score-files)))
2746         ;; Check whether there is a `score-file' group parameter.
2747         (let ((param-file (gnus-group-find-parameter group 'score-file)))
2748           (when param-file
2749             (push param-file score-files))))
2750       ;; Expand all files names.
2751       (let ((files score-files))
2752         (while files
2753           (when (stringp (car files))
2754             (setcar files (expand-file-name
2755                            (car files) gnus-kill-files-directory)))
2756           (pop files)))
2757       (setq score-files (nreverse score-files))
2758       ;; Remove any duplicate score files.
2759       (while (and score-files
2760                   (member (car score-files) (cdr score-files)))
2761         (pop score-files))
2762       (let ((files score-files))
2763         (while (cdr files)
2764           (if (member (cadr files) (cddr files))
2765               (setcdr files (cddr files))
2766             (pop files))))
2767       ;; Do the scoring if there are any score files for this group.
2768       score-files)))
2769
2770 (defun gnus-possibly-score-headers (&optional trace)
2771   "Do scoring if scoring is required."
2772   (let ((score-files (gnus-all-score-files)))
2773     (when score-files
2774       (gnus-score-headers score-files trace))))
2775
2776 (defun gnus-score-file-name (newsgroup &optional suffix)
2777   "Return the name of a score file for NEWSGROUP."
2778   (let ((suffix (or suffix gnus-score-file-suffix)))
2779     (nnheader-translate-file-chars
2780      (cond
2781       ((or (null newsgroup)
2782            (string-equal newsgroup ""))
2783        ;; The global score file is placed at top of the directory.
2784        (expand-file-name suffix gnus-kill-files-directory))
2785       ((gnus-use-long-file-name 'not-score)
2786        ;; Append ".SCORE" to newsgroup name.
2787        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2788                                  "." suffix)
2789                          gnus-kill-files-directory))
2790       (t
2791        ;; Place "SCORE" under the hierarchical directory.
2792        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2793                                  "/" suffix)
2794                          gnus-kill-files-directory))))))
2795
2796 (defun gnus-score-search-global-directories (files)
2797   "Scan all global score directories for score files."
2798   ;; Set the variable `gnus-internal-global-score-files' to all
2799   ;; available global score files.
2800   (interactive (list gnus-global-score-files))
2801   (let (out)
2802     (while files
2803       ;; #### /$ Unix-specific?
2804       (if (string-match "/$" (car files))
2805           (setq out (nconc (directory-files
2806                             (car files) t
2807                             (concat (gnus-score-file-regexp) "$"))))
2808         (push (car files) out))
2809       (setq files (cdr files)))
2810     (setq gnus-internal-global-score-files out)))
2811
2812 (defun gnus-score-default-fold-toggle ()
2813   "Toggle folding for new score file entries."
2814   (interactive)
2815   (setq gnus-score-default-fold (not gnus-score-default-fold))
2816   (if gnus-score-default-fold
2817       (gnus-message 1 "New score file entries will be case insensitive.")
2818     (gnus-message 1 "New score file entries will be case sensitive.")))
2819
2820 ;;; Home score file.
2821
2822 (defun gnus-home-score-file (group &optional adapt)
2823   "Return the home score file for GROUP.
2824 If ADAPT, return the home adaptive file instead."
2825   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2826         elem found)
2827     ;; Make sure we have a list.
2828     (unless (listp list)
2829       (setq list (list list)))
2830     ;; Go through the list and look for matches.
2831     (while (and (not found)
2832                 (setq elem (pop list)))
2833       (setq found
2834             (cond
2835              ;; Simple string.
2836              ((stringp elem)
2837               elem)
2838              ;; Function.
2839              ((gnus-functionp elem)
2840               (funcall elem group))
2841              ;; Regexp-file cons.
2842              ((consp elem)
2843               (when (string-match (gnus-globalify-regexp (car elem)) group)
2844                 (replace-match (cadr elem) t nil group))))))
2845     (when found
2846       (if (file-name-absolute-p found)
2847           found
2848         (nnheader-concat gnus-kill-files-directory found)))))
2849
2850 (defun gnus-hierarchial-home-score-file (group)
2851   "Return the score file of the top-level hierarchy of GROUP."
2852   (if (string-match "^[^.]+\\." group)
2853       (concat (match-string 0 group) gnus-score-file-suffix)
2854     ;; Group name without any dots.
2855     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2856             gnus-score-file-suffix)))
2857
2858 (defun gnus-hierarchial-home-adapt-file (group)
2859   "Return the adapt file of the top-level hierarchy of GROUP."
2860   (if (string-match "^[^.]+\\." group)
2861       (concat (match-string 0 group) gnus-adaptive-file-suffix)
2862     ;; Group name without any dots.
2863     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2864             gnus-adaptive-file-suffix)))
2865
2866 (defun gnus-current-home-score-file (group)
2867   "Return the \"current\" regular score file."
2868   (car (nreverse (gnus-score-find-alist group))))
2869
2870 ;;;
2871 ;;; Score decays
2872 ;;;
2873
2874 (defun gnus-decay-score (score)
2875   "Decay SCORE according to `gnus-score-decay-constant' and `gnus-score-decay-scale'."
2876   (floor
2877    (- score
2878       (* (if (< score 0) -1 1)
2879          (min (abs score)
2880               (max gnus-score-decay-constant
2881                    (* (abs score)
2882                       gnus-score-decay-scale)))))))
2883
2884 (defun gnus-decay-scores (alist day)
2885   "Decay non-permanent scores in ALIST."
2886   (let ((times (- (time-to-days (current-time)) day))
2887         kill entry updated score n)
2888     (unless (zerop times)               ;Done decays today already?
2889       (while (setq entry (pop alist))
2890         (when (stringp (car entry))
2891           (setq entry (cdr entry))
2892           (while (setq kill (pop entry))
2893             (when (nth 2 kill)
2894               (setq updated t)
2895               (setq score (or (nth 1 kill)
2896                               gnus-score-interactive-default-score)
2897                     n times)
2898               (while (natnump (decf n))
2899                 (setq score (funcall gnus-decay-score-function score)))
2900               (setcdr kill (cons score
2901                                  (cdr (cdr kill)))))))))
2902     ;; Return whether this score file needs to be saved.  By Je-haysuss!
2903     updated))
2904
2905 (defun gnus-score-regexp-bad-p (regexp)
2906   "Test whether REGEXP is safe for Gnus scoring.
2907 A regexp is unsafe if it matches newline or a buffer boundary.
2908
2909 If the regexp is good, return nil.  If the regexp is bad, return a
2910 cons cell (SYM . STRING), where the symbol SYM is `new' or `bad'.
2911 In the `new' case, the string is a safe replacement for REGEXP.
2912 In the `bad' case, the string is a unsafe subexpression of REGEXP,
2913 and we do not have a simple replacement to suggest.
2914
2915 See `(Gnus)Scoring Tips' for examples of good regular expressions."
2916   (let (case-fold-search)
2917     (and
2918      ;; First, try a relatively fast necessary condition.
2919      ;; Notice ranges (like [^:] or [\t-\r]), \s>, \Sw, \W, \', \`:
2920      (string-match "\n\\|\\\\[SsW`']\\|\\[\\^\\|[\0-\n]-" regexp)
2921      ;; Now break the regexp into tokens, and check each:
2922      (let ((tail regexp)                ; remaining regexp to check
2923            tok                          ; current token
2924            bad                          ; nil, or bad subexpression
2925            new                          ; nil, or replacement regexp so far
2926            end)                         ; length of current token
2927        (while (and (not bad)
2928                    (string-match
2929                     "\\`\\(\\\\[sS]?.\\|\\[\\^?]?[^]]*]\\|[^\\]\\)"
2930                     tail))
2931          (setq end (match-end 0)
2932                tok (substring tail 0 end)
2933                tail (substring tail end))
2934          (if;; Is token `bad' (matching newline or buffer ends)?
2935              (or (member tok '("\n" "\\W" "\\`" "\\'"))
2936                  ;; This next handles "[...]", "\\s.", and "\\S.":
2937                  (and (> end 2) (string-match tok "\n")))
2938              (let ((newtok
2939                     ;; Try to suggest a replacement for tok ...
2940                     (cond ((string-equal tok "\\`") "^") ; or "\\(^\\)"
2941                           ((string-equal tok "\\'") "$") ; or "\\($\\)"
2942                           ((string-match "\\[\\^" tok) ; very common
2943                            (concat (substring tok 0 -1) "\n]")))))
2944                (if newtok
2945                    (setq new
2946                          (concat
2947                           (or new
2948                               ;; good prefix so far:
2949                               (substring regexp 0 (- (+ (length tail) end))))
2950                           newtok))
2951                  ;; No replacement idea, so give up:
2952                  (setq bad tok)))
2953            ;; tok is good, may need to extend new
2954            (and new (setq new (concat new tok)))))
2955        ;; Now return a value:
2956        (cond
2957         (bad (cons 'bad bad))
2958         (new (cons 'new new))
2959         (t nil))))))
2960
2961 (provide 'gnus-score)
2962
2963 ;;; gnus-score.el ends here