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