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