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