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