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