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