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