(gnus-group-expire-articles-1): Make sure server is open.
[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             (when (gnus-buffer-live-p gnus-summary-buffer)
1466               (let ((scored gnus-newsgroup-scored))
1467                 (with-current-buffer gnus-summary-buffer
1468                   (setq gnus-newsgroup-scored scored))))
1469             ;; Remove the buffer.
1470             (kill-buffer (current-buffer)))
1471
1472           ;; Add articles to `gnus-newsgroup-scored'.
1473           (while gnus-scores-articles
1474             (when (or (/= gnus-summary-default-score
1475                           (cdar gnus-scores-articles))
1476                       gnus-save-score)
1477               (push (cons (mail-header-number (caar gnus-scores-articles))
1478                           (cdar gnus-scores-articles))
1479                     gnus-newsgroup-scored))
1480             (setq gnus-scores-articles (cdr gnus-scores-articles)))
1481
1482           (let (score)
1483             (while (setq score (pop scores))
1484               (while score
1485                 (when (consp (caar score))
1486                   (gnus-score-advanced (car score) trace))
1487                 (pop score))))
1488
1489           (gnus-message 5 "Scoring...done"))))))
1490
1491 (defun gnus-score-lower-thread (thread score-adjust)
1492   "Lower the socre on THREAD with SCORE-ADJUST.
1493 THREAD is expected to contain a list of the form `(PARENT [CHILD1
1494 CHILD2 ...])' where PARENT is a header array and each CHILD is a list
1495 of the same form as THREAD.  The empty list `nil' is valid.  For each
1496 article in the tree, the score of the corresponding entry in
1497 GNUS-NEWSGROUP-SCORED is adjusted by SCORE-ADJUST."
1498   (while thread
1499     (let ((head (car thread)))
1500       (if (listp head)
1501           ;; handle a child and its descendants
1502           (gnus-score-lower-thread head score-adjust)
1503         ;; handle the parent
1504         (let* ((article (mail-header-number head))
1505                (score (assq article gnus-newsgroup-scored)))
1506           (if score (setcdr score (+ (cdr score) score-adjust))
1507             (push (cons article score-adjust) gnus-newsgroup-scored)))))
1508     (setq thread (cdr thread))))
1509
1510 (defun gnus-score-orphans (score)
1511   "Score orphans.
1512 A root is an article with no references.  An orphan is an article
1513 which has references, but is not connected via its references to a
1514 root article.  This function finds all the orphans, and adjusts their
1515 score in GNUS-NEWSGROUP-SCORED by SCORE."
1516   (let ((threads (gnus-make-threads)))
1517     ;; gnus-make-threads produces a list, where each entry is a "thread"
1518     ;; as described in the gnus-score-lower-thread docs.  This function
1519     ;; will be called again (after limiting has been done) if the display
1520     ;; is threaded.  It would be nice to somehow save this info and use
1521     ;; it later.
1522     (while threads
1523       (let* ((thread (car threads))
1524              (id (aref (car thread) gnus-score-index)))
1525         ;; If the parent of the thread is not a root, lower the score of
1526         ;; it and its descendants.  Note that some roots seem to satisfy
1527         ;; (eq id nil) and some (eq id "");  not sure why.
1528         (if (and id (not (string= id "")))
1529             (gnus-score-lower-thread thread score)))
1530       (setq threads (cdr threads)))))
1531
1532 (defun gnus-score-integer (scores header now expire &optional trace)
1533   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1534         entries alist)
1535     ;; Find matches.
1536     (while scores
1537       (setq alist (car scores)
1538             scores (cdr scores)
1539             entries (assoc header alist))
1540       (while (cdr entries)              ;First entry is the header index.
1541         (let* ((rest (cdr entries))
1542                (kill (car rest))
1543                (match (nth 0 kill))
1544                (type (or (nth 3 kill) '>))
1545                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1546                (date (nth 2 kill))
1547                (found nil)
1548                (match-func (if (or (eq type '>) (eq type '<) (eq type '<=)
1549                                    (eq type '>=) (eq type '=))
1550                                type
1551                              (error "Invalid match type: %s" type)))
1552                (articles gnus-scores-articles))
1553           ;; Instead of doing all the clever stuff that
1554           ;; `gnus-score-string' does to minimize searches and stuff,
1555           ;; I will assume that people generally will put so few
1556           ;; matches on numbers that any cleverness will take more
1557           ;; time than one would gain.
1558           (while articles
1559             (when (funcall match-func
1560                            (or (aref (caar articles) gnus-score-index) 0)
1561                            match)
1562               (when trace
1563                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1564                       gnus-score-trace))
1565               (setq found t)
1566               (setcdr (car articles) (+ score (cdar articles))))
1567             (setq articles (cdr articles)))
1568           ;; Update expire date
1569           (cond ((null date))           ;Permanent entry.
1570                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1571                  (gnus-score-set 'touched '(t) alist)
1572                  (setcar (nthcdr 2 kill) now))
1573                 ((and expire (< date expire)) ;Old entry, remove.
1574                  (gnus-score-set 'touched '(t) alist)
1575                  (setcdr entries (cdr rest))
1576                  (setq rest entries)))
1577           (setq entries rest)))))
1578   nil)
1579
1580 (defun gnus-score-date (scores header now expire &optional trace)
1581   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1582         entries alist match match-func article)
1583     ;; Find matches.
1584     (while scores
1585       (setq alist (car scores)
1586             scores (cdr scores)
1587             entries (assoc header alist))
1588       (while (cdr entries)              ;First entry is the header index.
1589         (let* ((rest (cdr entries))
1590                (kill (car rest))
1591                (type (or (nth 3 kill) 'before))
1592                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1593                (date (nth 2 kill))
1594                (found nil)
1595                (articles gnus-scores-articles)
1596                l)
1597           (cond
1598            ((eq type 'after)
1599             (setq match-func 'string<
1600                   match (gnus-date-iso8601 (nth 0 kill))))
1601            ((eq type 'before)
1602             (setq match-func 'gnus-string>
1603                   match (gnus-date-iso8601 (nth 0 kill))))
1604            ((eq type 'at)
1605             (setq match-func 'string=
1606                   match (gnus-date-iso8601 (nth 0 kill))))
1607            ((eq type 'regexp)
1608             (setq match-func 'string-match
1609                   match (nth 0 kill)))
1610            (t (error "Invalid match type: %s" type)))
1611           ;; Instead of doing all the clever stuff that
1612           ;; `gnus-score-string' does to minimize searches and stuff,
1613           ;; I will assume that people generally will put so few
1614           ;; matches on numbers that any cleverness will take more
1615           ;; time than one would gain.
1616           (while (setq article (pop articles))
1617             (when (and
1618                    (setq l (aref (car article) gnus-score-index))
1619                    (funcall match-func match (gnus-date-iso8601 l)))
1620               (when trace
1621                 (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
1622                       gnus-score-trace))
1623               (setq found t)
1624               (setcdr article (+ score (cdr article)))))
1625           ;; Update expire date
1626           (cond ((null date))           ;Permanent entry.
1627                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1628                  (gnus-score-set 'touched '(t) alist)
1629                  (setcar (nthcdr 2 kill) now))
1630                 ((and expire (< date expire)) ;Old entry, remove.
1631                  (gnus-score-set 'touched '(t) alist)
1632                  (setcdr entries (cdr rest))
1633                  (setq rest entries)))
1634           (setq entries rest)))))
1635   nil)
1636
1637 (defun gnus-score-body (scores header now expire &optional trace)
1638   (save-excursion
1639     (setq gnus-scores-articles
1640           (sort gnus-scores-articles
1641                 (lambda (a1 a2)
1642                   (< (mail-header-number (car a1))
1643                      (mail-header-number (car a2))))))
1644     (set-buffer nntp-server-buffer)
1645     (save-restriction
1646       (let* ((buffer-read-only nil)
1647              (articles gnus-scores-articles)
1648              (all-scores scores)
1649              (request-func (cond ((string= "head" header)
1650                                   'gnus-request-head)
1651                                  ((string= "body" header)
1652                                   'gnus-request-body)
1653                                  (t 'gnus-request-article)))
1654              entries alist ofunc article last)
1655         (when articles
1656           (setq last (mail-header-number (caar (last articles))))
1657           ;; Not all backends support partial fetching.  In that case,
1658           ;; we just fetch the entire article.
1659           (unless (gnus-check-backend-function
1660                    (and (string-match "^gnus-" (symbol-name request-func))
1661                         (intern (substring (symbol-name request-func)
1662                                            (match-end 0))))
1663                    gnus-newsgroup-name)
1664             (setq ofunc request-func)
1665             (setq request-func 'gnus-request-article))
1666           (while articles
1667             (setq article (mail-header-number (caar articles)))
1668             (gnus-message 7 "Scoring article %s of %s..." article last)
1669             (widen)
1670             (when (funcall request-func article gnus-newsgroup-name)
1671               (goto-char (point-min))
1672               ;; If just parts of the article is to be searched, but the
1673               ;; backend didn't support partial fetching, we just narrow
1674               ;; to the relevant parts.
1675               (when ofunc
1676                 (if (eq ofunc 'gnus-request-head)
1677                     (narrow-to-region
1678                      (point)
1679                      (or (search-forward "\n\n" nil t) (point-max)))
1680                   (narrow-to-region
1681                    (or (search-forward "\n\n" nil t) (point))
1682                    (point-max))))
1683               (setq scores all-scores)
1684               ;; Find matches.
1685               (while scores
1686                 (setq alist (pop scores)
1687                       entries (assoc header alist))
1688                 (while (cdr entries)    ;First entry is the header index.
1689                   (let* ((rest (cdr entries))
1690                          (kill (car rest))
1691                          (match (nth 0 kill))
1692                          (type (or (nth 3 kill) 's))
1693                          (score (or (nth 1 kill)
1694                                     gnus-score-interactive-default-score))
1695                          (date (nth 2 kill))
1696                          (found nil)
1697                          (case-fold-search
1698                           (not (or (eq type 'R) (eq type 'S)
1699                                    (eq type 'Regexp) (eq type 'String))))
1700                          (search-func
1701                           (cond ((or (eq type 'r) (eq type 'R)
1702                                      (eq type 'regexp) (eq type 'Regexp))
1703                                  're-search-forward)
1704                                 ((or (eq type 's) (eq type 'S)
1705                                      (eq type 'string) (eq type 'String))
1706                                  'search-forward)
1707                                 (t
1708                                  (error "Invalid match type: %s" type)))))
1709                     (goto-char (point-min))
1710                     (when (funcall search-func match nil t)
1711                       ;; Found a match, update scores.
1712                       (setcdr (car articles) (+ score (cdar articles)))
1713                       (setq found t)
1714                       (when trace
1715                         (push
1716                          (cons (car-safe (rassq alist gnus-score-cache)) kill)
1717                          gnus-score-trace)))
1718                     ;; Update expire date
1719                     (unless trace
1720                       (cond
1721                        ((null date))    ;Permanent entry.
1722                        ((and found gnus-update-score-entry-dates)
1723                         ;; Match, update date.
1724                         (gnus-score-set 'touched '(t) alist)
1725                         (setcar (nthcdr 2 kill) now))
1726                        ((and expire (< date expire)) ;Old entry, remove.
1727                         (gnus-score-set 'touched '(t) alist)
1728                         (setcdr entries (cdr rest))
1729                         (setq rest entries))))
1730                     (setq entries rest)))))
1731             (setq articles (cdr articles)))))))
1732   nil)
1733
1734 (defun gnus-score-thread (scores header now expire &optional trace)
1735   (gnus-score-followup scores header now expire trace t))
1736
1737 (defun gnus-score-followup (scores header now expire &optional trace thread)
1738   ;; Insert the unique article headers in the buffer.
1739   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1740         (current-score-file gnus-current-score-file)
1741         (all-scores scores)
1742         ;; gnus-score-index is used as a free variable.
1743         alike last this art entries alist articles
1744         new news)
1745
1746     ;; Change score file to the adaptive score file.  All entries that
1747     ;; this function makes will be put into this file.
1748     (save-excursion
1749       (set-buffer gnus-summary-buffer)
1750       (gnus-score-load-file
1751        (or gnus-newsgroup-adaptive-score-file
1752            (gnus-score-file-name
1753             gnus-newsgroup-name gnus-adaptive-file-suffix))))
1754
1755     (setq gnus-scores-articles (sort gnus-scores-articles 'gnus-score-string<)
1756           articles gnus-scores-articles)
1757
1758     (erase-buffer)
1759     (while articles
1760       (setq art (car articles)
1761             this (aref (car art) gnus-score-index)
1762             articles (cdr articles))
1763       (if (equal last this)
1764           (push art alike)
1765         (when last
1766           (insert last ?\n)
1767           (put-text-property (1- (point)) (point) 'articles alike))
1768         (setq alike (list art)
1769               last this)))
1770     (when last                          ; Bwadr, duplicate code.
1771       (insert last ?\n)
1772       (put-text-property (1- (point)) (point) 'articles alike))
1773
1774     ;; Find matches.
1775     (while scores
1776       (setq alist (car scores)
1777             scores (cdr scores)
1778             entries (assoc header alist))
1779       (while (cdr entries)              ;First entry is the header index.
1780         (let* ((rest (cdr entries))
1781                (kill (car rest))
1782                (match (nth 0 kill))
1783                (type (or (nth 3 kill) 's))
1784                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1785                (date (nth 2 kill))
1786                (found nil)
1787                (mt (aref (symbol-name type) 0))
1788                (case-fold-search
1789                 (not (or (= mt ?R) (= mt ?S) (= mt ?E) (= mt ?F))))
1790                (dmt (downcase mt))
1791                (search-func
1792                 (cond ((= dmt ?r) 're-search-forward)
1793                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1794                       (t (error "Invalid match type: %s" type))))
1795                arts art)
1796           (goto-char (point-min))
1797           (if (= dmt ?e)
1798               (while (funcall search-func match nil t)
1799                 (and (= (progn (beginning-of-line) (point))
1800                         (match-beginning 0))
1801                      (= (progn (end-of-line) (point))
1802                         (match-end 0))
1803                      (progn
1804                        (setq found (setq arts (get-text-property
1805                                                (point) 'articles)))
1806                        ;; Found a match, update scores.
1807                        (while arts
1808                          (setq art (car arts)
1809                                arts (cdr arts))
1810                          (gnus-score-add-followups
1811                           (car art) score all-scores thread))))
1812                 (end-of-line))
1813             (while (funcall search-func match nil t)
1814               (end-of-line)
1815               (setq found (setq arts (get-text-property (point) 'articles)))
1816               ;; Found a match, update scores.
1817               (while (setq art (pop arts))
1818                 (when (setq new (gnus-score-add-followups
1819                                  (car art) score all-scores thread))
1820                   (push new news)))))
1821           ;; Update expire date
1822           (cond ((null date))           ;Permanent entry.
1823                 ((and found gnus-update-score-entry-dates) ;Match, update date.
1824                  (gnus-score-set 'touched '(t) alist)
1825                  (setcar (nthcdr 2 kill) now))
1826                 ((and expire (< date expire)) ;Old entry, remove.
1827                  (gnus-score-set 'touched '(t) alist)
1828                  (setcdr entries (cdr rest))
1829                  (setq rest entries)))
1830           (setq entries rest))))
1831     ;; We change the score file back to the previous one.
1832     (save-excursion
1833       (set-buffer gnus-summary-buffer)
1834       (gnus-score-load-file current-score-file))
1835     (list (cons "references" news))))
1836
1837 (defun gnus-score-add-followups (header score scores &optional thread)
1838   "Add a score entry to the adapt file."
1839   (save-excursion
1840     (set-buffer gnus-summary-buffer)
1841     (let* ((id (mail-header-id header))
1842            (scores (car scores))
1843            entry dont)
1844       ;; Don't enter a score if there already is one.
1845       (while (setq entry (pop scores))
1846         (and (equal "references" (car entry))
1847              (or (null (nth 3 (cadr entry)))
1848                  (eq 's (nth 3 (cadr entry))))
1849              (assoc id entry)
1850              (setq dont t)))
1851       (unless dont
1852         (gnus-summary-score-entry
1853          (if thread "thread" "references")
1854          id 's score (current-time-string) nil t)))))
1855
1856 (defun gnus-score-string (score-list header now expire &optional trace)
1857   ;; Score ARTICLES according to HEADER in SCORE-LIST.
1858   ;; Update matching entries to NOW and remove unmatched entries older
1859   ;; than EXPIRE.
1860
1861   ;; Insert the unique article headers in the buffer.
1862   (let ((gnus-score-index (nth 1 (assoc header gnus-header-index)))
1863         ;; gnus-score-index is used as a free variable.
1864         (simplify (and gnus-score-thread-simplify
1865                        (string= "subject" header)))
1866         alike last this art entries alist articles
1867         fuzzies arts words kill)
1868
1869     ;; Sorting the articles costs os O(N*log N) but will allow us to
1870     ;; only match with each unique header.  Thus the actual matching
1871     ;; will be O(M*U) where M is the number of strings to match with,
1872     ;; and U is the number of unique headers.  It is assumed (but
1873     ;; untested) this will be a net win because of the large constant
1874     ;; factor involved with string matching.
1875     (setq gnus-scores-articles
1876           ;; We cannot string-sort the extra headers list.  *sigh*
1877           (if (= gnus-score-index 9)
1878               gnus-scores-articles
1879             (sort gnus-scores-articles 'gnus-score-string<))
1880           articles gnus-scores-articles)
1881
1882     (erase-buffer)
1883     (while (setq art (pop articles))
1884       (setq this (aref (car art) gnus-score-index))
1885
1886       ;; If we're working with non-standard headers, we are stuck
1887       ;; with working on them as a group.  What a hassle.
1888       ;; Just wait 'til you see what horrors we commit against `match'...
1889       (if (= gnus-score-index 9)
1890           (setq this (prin1-to-string this))) ; ick.
1891
1892       (if simplify
1893           (setq this (gnus-map-function gnus-simplify-subject-functions this)))
1894       (if (equal last this)
1895           ;; O(N*H) cons-cells used here, where H is the number of
1896           ;; headers.
1897           (push art alike)
1898         (when last
1899           ;; Insert the line, with a text property on the
1900           ;; terminating newline referring to the articles with
1901           ;; this line.
1902           (insert last ?\n)
1903           (put-text-property (1- (point)) (point) 'articles alike))
1904         (setq alike (list art)
1905               last this)))
1906     (when last                          ; Bwadr, duplicate code.
1907       (insert last ?\n)
1908       (put-text-property (1- (point)) (point) 'articles alike))
1909
1910     ;; Go through all the score alists and pick out the entries
1911     ;; for this header.
1912     (while score-list
1913       (setq alist (pop score-list)
1914             ;; There's only one instance of this header for
1915             ;; each score alist.
1916             entries (assoc header alist))
1917       (while (cdr entries)              ;First entry is the header index.
1918         (let* ((kill (cadr entries))
1919                (type (or (nth 3 kill) 's))
1920                (score (or (nth 1 kill) gnus-score-interactive-default-score))
1921                (date (nth 2 kill))
1922                (extra (nth 4 kill))     ; non-standard header; string.
1923                (found nil)
1924                (mt (aref (symbol-name type) 0))
1925                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
1926                (dmt (downcase mt))
1927                ;; Assume user already simplified regexp and fuzzies
1928                (match (if (and simplify (not (memq dmt '(?f ?r))))
1929                           (gnus-map-function
1930                            gnus-simplify-subject-functions
1931                            (nth 0 kill))
1932                         (nth 0 kill)))
1933                (search-func
1934                 (cond ((= dmt ?r) 're-search-forward)
1935                       ((or (= dmt ?e) (= dmt ?s) (= dmt ?f)) 'search-forward)
1936                       ((= dmt ?w) nil)
1937                       (t (error "Invalid match type: %s" type)))))
1938
1939           ;; Evil hackery to make match usable in non-standard headers.
1940           (when extra
1941             (setq match (concat "[ (](" extra " \\. \"[^)]*"
1942                                 match "[^(]*\")[ )]")
1943                   search-func 're-search-forward)) ; XXX danger?!?
1944
1945           (cond
1946            ;; Fuzzy matches.  We save these for later.
1947            ((= dmt ?f)
1948             (push (cons entries alist) fuzzies)
1949             (setq entries (cdr entries)))
1950            ;; Word matches.  Save these for even later.
1951            ((= dmt ?w)
1952             (push (cons entries alist) words)
1953             (setq entries (cdr entries)))
1954            ;; Exact matches.
1955            ((= dmt ?e)
1956             ;; Do exact matching.
1957             (goto-char (point-min))
1958             (while (and (not (eobp))
1959                         (funcall search-func match nil t))
1960               ;; Is it really exact?
1961               (and (eolp)
1962                    (= (gnus-point-at-bol) (match-beginning 0))
1963                    ;; Yup.
1964                    (progn
1965                      (setq found (setq arts (get-text-property
1966                                              (point) 'articles)))
1967                      ;; Found a match, update scores.
1968                      (if trace
1969                          (while (setq art (pop arts))
1970                            (setcdr art (+ score (cdr art)))
1971                            (push
1972                             (cons
1973                              (car-safe (rassq alist gnus-score-cache))
1974                              kill)
1975                             gnus-score-trace))
1976                        (while (setq art (pop arts))
1977                          (setcdr art (+ score (cdr art)))))))
1978               (forward-line 1))
1979             ;; Update expiry date
1980             (if trace
1981                 (setq entries (cdr entries))
1982               (cond
1983                ;; Permanent entry.
1984                ((null date)
1985                 (setq entries (cdr entries)))
1986                ;; We have a match, so we update the date.
1987                ((and found gnus-update-score-entry-dates)
1988                 (gnus-score-set 'touched '(t) alist)
1989                 (setcar (nthcdr 2 kill) now)
1990                 (setq entries (cdr entries)))
1991                ;; This entry has expired, so we remove it.
1992                ((and expire (< date expire))
1993                 (gnus-score-set 'touched '(t) alist)
1994                 (setcdr entries (cddr entries)))
1995                ;; No match; go to next entry.
1996                (t
1997                 (setq entries (cdr entries))))))
1998            ;; Regexp and substring matching.
1999            (t
2000             (goto-char (point-min))
2001             (when (string= match "")
2002               (setq match "\n"))
2003             (while (and (not (eobp))
2004                         (funcall search-func match nil t))
2005               (goto-char (match-beginning 0))
2006               (end-of-line)
2007               (setq found (setq arts (get-text-property (point) 'articles)))
2008               ;; Found a match, update scores.
2009               (if trace
2010                   (while (setq art (pop arts))
2011                     (setcdr art (+ score (cdr art)))
2012                     (push (cons (car-safe (rassq alist gnus-score-cache)) kill)
2013                           gnus-score-trace))
2014                 (while (setq art (pop arts))
2015                   (setcdr art (+ score (cdr art)))))
2016               (forward-line 1))
2017             ;; Update expiry date
2018             (if trace
2019                 (setq entries (cdr entries))
2020               (cond
2021                ;; Permanent entry.
2022                ((null date)
2023                 (setq entries (cdr entries)))
2024                ;; We have a match, so we update the date.
2025                ((and found gnus-update-score-entry-dates)
2026                 (gnus-score-set 'touched '(t) alist)
2027                 (setcar (nthcdr 2 kill) now)
2028                 (setq entries (cdr entries)))
2029                ;; This entry has expired, so we remove it.
2030                ((and expire (< date expire))
2031                 (gnus-score-set 'touched '(t) alist)
2032                 (setcdr entries (cddr entries)))
2033                ;; No match; go to next entry.
2034                (t
2035                 (setq entries (cdr entries))))))))))
2036
2037     ;; Find fuzzy matches.
2038     (when fuzzies
2039       ;; Simplify the entire buffer for easy matching.
2040       (gnus-simplify-buffer-fuzzy)
2041       (while (setq kill (cadaar fuzzies))
2042         (let* ((match (nth 0 kill))
2043                (type (nth 3 kill))
2044                (score (or (nth 1 kill) gnus-score-interactive-default-score))
2045                (date (nth 2 kill))
2046                (mt (aref (symbol-name type) 0))
2047                (case-fold-search (not (= mt ?F)))
2048                found)
2049           (goto-char (point-min))
2050           (while (and (not (eobp))
2051                       (search-forward match nil t))
2052             (when (and (= (gnus-point-at-bol) (match-beginning 0))
2053                        (eolp))
2054               (setq found (setq arts (get-text-property (point) 'articles)))
2055               (if trace
2056                   (while (setq art (pop arts))
2057                     (setcdr art (+ score (cdr art)))
2058                     (push (cons
2059                            (car-safe (rassq (cdar fuzzies) gnus-score-cache))
2060                            kill)
2061                           gnus-score-trace))
2062                 ;; Found a match, update scores.
2063                 (while (setq art (pop arts))
2064                   (setcdr art (+ score (cdr art))))))
2065             (forward-line 1))
2066           ;; Update expiry date
2067           (if (not trace)
2068               (cond
2069                ;; Permanent.
2070                ((null date)
2071                 ;; Do nothing.
2072                 )
2073                ;; Match, update date.
2074                ((and found gnus-update-score-entry-dates)
2075                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2076                 (setcar (nthcdr 2 kill) now))
2077                ;; Old entry, remove.
2078                ((and expire (< date expire))
2079                 (gnus-score-set 'touched '(t) (cdar fuzzies))
2080                 (setcdr (caar fuzzies) (cddaar fuzzies)))))
2081           (setq fuzzies (cdr fuzzies)))))
2082
2083     (when words
2084       ;; Enter all words into the hashtb.
2085       (let ((hashtb (gnus-make-hashtable
2086                      (* 10 (count-lines (point-min) (point-max))))))
2087         (gnus-enter-score-words-into-hashtb hashtb)
2088         (while (setq kill (cadaar words))
2089           (let* ((score (or (nth 1 kill) gnus-score-interactive-default-score))
2090                  (date (nth 2 kill))
2091                  found)
2092             (when (setq arts (intern-soft (nth 0 kill) hashtb))
2093               (setq arts (symbol-value arts))
2094               (setq found t)
2095               (if trace
2096                   (while (setq art (pop arts))
2097                     (setcdr art (+ score (cdr art)))
2098                     (push (cons
2099                            (car-safe (rassq (cdar words) gnus-score-cache))
2100                            kill)
2101                           gnus-score-trace))
2102                 ;; Found a match, update scores.
2103                 (while (setq art (pop arts))
2104                   (setcdr art (+ score (cdr art))))))
2105             ;; Update expiry date
2106             (if (not trace)
2107                 (cond
2108                  ;; Permanent.
2109                  ((null date)
2110                   ;; Do nothing.
2111                   )
2112                  ;; Match, update date.
2113                  ((and found gnus-update-score-entry-dates)
2114                   (gnus-score-set 'touched '(t) (cdar words))
2115                   (setcar (nthcdr 2 kill) now))
2116                  ;; Old entry, remove.
2117                  ((and expire (< date expire))
2118                   (gnus-score-set 'touched '(t) (cdar words))
2119                   (setcdr (caar words) (cddaar words)))))
2120             (setq words (cdr words))))))
2121     nil))
2122
2123 (defun gnus-enter-score-words-into-hashtb (hashtb)
2124   ;; Find all the words in the buffer and enter them into
2125   ;; the hashtable.
2126   (let ((syntab (syntax-table))
2127         word val)
2128     (goto-char (point-min))
2129     (unwind-protect
2130         (progn
2131           (set-syntax-table gnus-adaptive-word-syntax-table)
2132           (while (re-search-forward "\\b\\w+\\b" nil t)
2133             (setq val
2134                   (gnus-gethash
2135                    (setq word (downcase (buffer-substring
2136                                          (match-beginning 0) (match-end 0))))
2137                    hashtb))
2138             (gnus-sethash
2139              word
2140              (append (get-text-property (gnus-point-at-eol) 'articles) val)
2141              hashtb)))
2142       (set-syntax-table syntab))
2143     ;; Make all the ignorable words ignored.
2144     (let ((ignored (append gnus-ignored-adaptive-words
2145                            (if gnus-adaptive-word-no-group-words
2146                                (message-tokenize-header
2147                                 (gnus-group-real-name gnus-newsgroup-name)
2148                                 "."))
2149                            gnus-default-ignored-adaptive-words)))
2150       (while ignored
2151         (gnus-sethash (pop ignored) nil hashtb)))))
2152
2153 (defun gnus-score-string< (a1 a2)
2154   ;; Compare headers in articles A2 and A2.
2155   ;; The header index used is the free variable `gnus-score-index'.
2156   (string-lessp (aref (car a1) gnus-score-index)
2157                 (aref (car a2) gnus-score-index)))
2158
2159 (defun gnus-current-score-file-nondirectory (&optional score-file)
2160   (let ((score-file (or score-file gnus-current-score-file)))
2161     (if score-file
2162         (gnus-short-group-name (file-name-nondirectory score-file))
2163       "none")))
2164
2165 (defun gnus-score-adaptive ()
2166   "Create adaptive score rules for this newsgroup."
2167   (when gnus-newsgroup-adaptive
2168     ;; We change the score file to the adaptive score file.
2169     (save-excursion
2170       (set-buffer gnus-summary-buffer)
2171       (gnus-score-load-file
2172        (or gnus-newsgroup-adaptive-score-file
2173            (gnus-home-score-file gnus-newsgroup-name t)
2174            (gnus-score-file-name
2175             gnus-newsgroup-name gnus-adaptive-file-suffix))))
2176     ;; Perform ordinary line scoring.
2177     (when (or (not (listp gnus-newsgroup-adaptive))
2178               (memq 'line gnus-newsgroup-adaptive))
2179       (save-excursion
2180         (let* ((malist (gnus-copy-sequence gnus-adaptive-score-alist))
2181                (alist malist)
2182                (date (current-time-string))
2183                (data gnus-newsgroup-data)
2184                elem headers match func)
2185           ;; First we transform the adaptive rule alist into something
2186           ;; that's faster to process.
2187           (while malist
2188             (setq elem (car malist))
2189             (when (symbolp (car elem))
2190               (setcar elem (symbol-value (car elem))))
2191             (setq elem (cdr elem))
2192             (while elem
2193               (when (fboundp
2194                      (setq func
2195                            (intern
2196                             (concat "mail-header-"
2197                                     (if (eq (caar elem) 'followup)
2198                                         "message-id"
2199                                       (downcase (symbol-name (caar elem))))))))
2200                 (setcdr (car elem)
2201                         (cons (if (eq (caar elem) 'followup)
2202                                   "references"
2203                                 (symbol-name (caar elem)))
2204                               (cdar elem)))
2205                 (setcar (car elem)
2206                         `(lambda (h)
2207                            (,func h))))
2208               (setq elem (cdr elem)))
2209             (setq malist (cdr malist)))
2210           ;; Then we score away.
2211           (while data
2212             (setq elem (cdr (assq (gnus-data-mark (car data)) alist)))
2213             (if (or (not elem)
2214                     (gnus-data-pseudo-p (car data)))
2215                 ()
2216               (when (setq headers (gnus-data-header (car data)))
2217                 (while elem
2218                   (setq match (funcall (caar elem) headers))
2219                   (gnus-summary-score-entry
2220                    (nth 1 (car elem)) match
2221                    (cond
2222                     ((numberp match)
2223                      '=)
2224                     ((equal (nth 1 (car elem)) "date")
2225                      'a)
2226                     (t
2227                      ;; Whether we use substring or exact matches is
2228                      ;; controlled here.
2229                      (if (or (not gnus-score-exact-adapt-limit)
2230                              (< (length match) gnus-score-exact-adapt-limit))
2231                          'e
2232                        (if (equal (nth 1 (car elem)) "subject")
2233                            'f 's))))
2234                    (nth 2 (car elem)) date nil t)
2235                   (setq elem (cdr elem)))))
2236             (setq data (cdr data))))))
2237
2238     ;; Perform adaptive word scoring.
2239     (when (and (listp gnus-newsgroup-adaptive)
2240                (memq 'word gnus-newsgroup-adaptive))
2241       (with-temp-buffer
2242         (let* ((hashtb (gnus-make-hashtable 1000))
2243                (date (date-to-day (current-time-string)))
2244                (data gnus-newsgroup-data)
2245                (syntab (syntax-table))
2246                word d score val)
2247           (unwind-protect
2248               (progn
2249                 (set-syntax-table gnus-adaptive-word-syntax-table)
2250                 ;; Go through all articles.
2251                 (while (setq d (pop data))
2252                   (when (and
2253                          (not (gnus-data-pseudo-p d))
2254                          (setq score
2255                                (cdr (assq
2256                                      (gnus-data-mark d)
2257                                      gnus-adaptive-word-score-alist))))
2258                     ;; This article has a mark that should lead to
2259                     ;; adaptive word rules, so we insert the subject
2260                     ;; and find all words in that string.
2261                     (insert (mail-header-subject (gnus-data-header d)))
2262                     (downcase-region (point-min) (point-max))
2263                     (goto-char (point-min))
2264                     (while (re-search-forward "\\b\\w+\\b" nil t)
2265                       ;; Put the word and score into the hashtb.
2266                       (setq val (gnus-gethash (setq word (match-string 0))
2267                                               hashtb))
2268                       (setq val (+ score (or val 0)))
2269                       (if (and gnus-adaptive-word-minimum
2270                                (< val gnus-adaptive-word-minimum))
2271                           (setq val gnus-adaptive-word-minimum))
2272                       (gnus-sethash word val hashtb))
2273                     (erase-buffer))))
2274             (set-syntax-table syntab))
2275           ;; Make all the ignorable words ignored.
2276           (let ((ignored (append gnus-ignored-adaptive-words
2277                                  (if gnus-adaptive-word-no-group-words
2278                                      (message-tokenize-header
2279                                       (gnus-group-real-name
2280                                        gnus-newsgroup-name)
2281                                       "."))
2282                                  gnus-default-ignored-adaptive-words)))
2283             (while ignored
2284               (gnus-sethash (pop ignored) nil hashtb)))
2285           ;; Now we have all the words and scores, so we
2286           ;; add these rules to the ADAPT file.
2287           (set-buffer gnus-summary-buffer)
2288           (mapatoms
2289            (lambda (word)
2290              (when (symbol-value word)
2291                (gnus-summary-score-entry
2292                 "subject" (symbol-name word) 'w (symbol-value word)
2293                 date nil t)))
2294            hashtb))))))
2295
2296 (defun gnus-score-edit-done ()
2297   (let ((bufnam (buffer-file-name (current-buffer)))
2298         (winconf gnus-prev-winconf))
2299     (when winconf
2300       (set-window-configuration winconf))
2301     (gnus-score-remove-from-cache bufnam)
2302     (gnus-score-load-file bufnam)))
2303
2304 (defun gnus-score-find-trace ()
2305   "Find all score rules that applies to the current article."
2306   (interactive)
2307   (let ((old-scored gnus-newsgroup-scored))
2308     (let ((gnus-newsgroup-headers
2309            (list (gnus-summary-article-header)))
2310           (gnus-newsgroup-scored nil)
2311           trace)
2312       (save-excursion
2313         (nnheader-set-temp-buffer "*Score Trace*"))
2314       (setq gnus-score-trace nil)
2315       (gnus-possibly-score-headers 'trace)
2316       (if (not (setq trace gnus-score-trace))
2317           (gnus-error
2318            1 "No score rules apply to the current article (default score %d)."
2319            gnus-summary-default-score)
2320         (set-buffer "*Score Trace*")
2321         (setq truncate-lines t)
2322         (while trace
2323           (insert (format "%S  ->  %s\n" (cdar trace)
2324                           (or (caar trace) "(non-file rule)")))
2325           (setq trace (cdr trace)))
2326         (goto-char (point-min))
2327         (gnus-configure-windows 'score-trace)))
2328     (set-buffer gnus-summary-buffer)
2329     (setq gnus-newsgroup-scored old-scored)))
2330
2331 (defun gnus-score-find-favourite-words ()
2332   "List words used in scoring."
2333   (interactive)
2334   (let ((alists (gnus-score-load-files (gnus-all-score-files)))
2335         alist rule rules kill)
2336     ;; Go through all the score alists for this group
2337     ;; and find all `w' rules.
2338     (while (setq alist (pop alists))
2339       (while (setq rule (pop alist))
2340         (when (and (stringp (car rule))
2341                    (equal "subject" (downcase (pop rule))))
2342           (while (setq kill (pop rule))
2343             (when (memq (nth 3 kill) '(w W word Word))
2344               (push (cons (or (nth 1 kill)
2345                               gnus-score-interactive-default-score)
2346                           (car kill))
2347                     rules))))))
2348     (setq rules (sort rules (lambda (r1 r2)
2349                               (string-lessp (cdr r1) (cdr r2)))))
2350     ;; Add up words that have appeared several times.
2351     (let ((r rules))
2352       (while (cdr r)
2353         (if (equal (cdar r) (cdadr r))
2354             (progn
2355               (setcar (car r) (+ (caar r) (caadr r)))
2356               (setcdr r (cddr r)))
2357           (pop r))))
2358     ;; Insert the words.
2359     (nnheader-set-temp-buffer "*Score Words*")
2360     (if (not (setq rules (sort rules (lambda (r1 r2) (> (car r1) (car r2))))))
2361         (gnus-error 3 "No word score rules")
2362       (while rules
2363         (insert (format "%-5d: %s\n" (caar rules) (cdar rules)))
2364         (pop rules))
2365       (goto-char (point-min))
2366       (gnus-configure-windows 'score-words))))
2367
2368 (defun gnus-summary-rescore ()
2369   "Redo the entire scoring process in the current summary."
2370   (interactive)
2371   (gnus-score-save)
2372   (setq gnus-score-cache nil)
2373   (setq gnus-newsgroup-scored nil)
2374   (gnus-possibly-score-headers)
2375   (gnus-score-update-all-lines))
2376
2377 (defun gnus-score-flush-cache ()
2378   "Flush the cache of score files."
2379   (interactive)
2380   (gnus-score-save)
2381   (setq gnus-score-cache nil
2382         gnus-score-alist nil
2383         gnus-short-name-score-file-cache nil)
2384   (gnus-message 6 "The score cache is now flushed"))
2385
2386 (gnus-add-shutdown 'gnus-score-close 'gnus)
2387
2388 (defvar gnus-score-file-alist-cache nil)
2389
2390 (defun gnus-score-close ()
2391   "Clear all internal score variables."
2392   (setq gnus-score-cache nil
2393         gnus-internal-global-score-files nil
2394         gnus-score-file-list nil
2395         gnus-score-file-alist-cache nil))
2396
2397 ;; Summary score marking commands.
2398
2399 (defun gnus-summary-raise-same-subject-and-select (score)
2400   "Raise articles which has the same subject with SCORE and select the next."
2401   (interactive "p")
2402   (let ((subject (gnus-summary-article-subject)))
2403     (gnus-summary-raise-score score)
2404     (while (gnus-summary-find-subject subject)
2405       (gnus-summary-raise-score score))
2406     (gnus-summary-next-article t)))
2407
2408 (defun gnus-summary-raise-same-subject (score)
2409   "Raise articles which has the same subject with SCORE."
2410   (interactive "p")
2411   (let ((subject (gnus-summary-article-subject)))
2412     (gnus-summary-raise-score score)
2413     (while (gnus-summary-find-subject subject)
2414       (gnus-summary-raise-score score))
2415     (gnus-summary-next-subject 1 t)))
2416
2417 (defun gnus-score-delta-default (level)
2418   (if level (prefix-numeric-value level)
2419     gnus-score-interactive-default-score))
2420
2421 (defun gnus-summary-raise-thread (&optional score)
2422   "Raise the score of the articles in the current thread with SCORE."
2423   (interactive "P")
2424   (setq score (gnus-score-delta-default score))
2425   (let (e)
2426     (save-excursion
2427       (let ((articles (gnus-summary-articles-in-thread)))
2428         (while articles
2429           (gnus-summary-goto-subject (car articles))
2430           (gnus-summary-raise-score score)
2431           (setq articles (cdr articles))))
2432       (setq e (point)))
2433     (let ((gnus-summary-check-current t))
2434       (unless (zerop (gnus-summary-next-subject 1 t))
2435         (goto-char e))))
2436   (gnus-summary-recenter)
2437   (gnus-summary-position-point)
2438   (gnus-set-mode-line 'summary))
2439
2440 (defun gnus-summary-lower-same-subject-and-select (score)
2441   "Raise articles which has the same subject with SCORE and select the next."
2442   (interactive "p")
2443   (gnus-summary-raise-same-subject-and-select (- score)))
2444
2445 (defun gnus-summary-lower-same-subject (score)
2446   "Raise articles which has the same subject with SCORE."
2447   (interactive "p")
2448   (gnus-summary-raise-same-subject (- score)))
2449
2450 (defun gnus-summary-lower-thread (&optional score)
2451   "Lower score of articles in the current thread with SCORE."
2452   (interactive "P")
2453   (gnus-summary-raise-thread (- (1- (gnus-score-delta-default score)))))
2454
2455 ;;; Finding score files.
2456
2457 (defun gnus-score-score-files (group)
2458   "Return a list of all possible score files."
2459   ;; Search and set any global score files.
2460   (when gnus-global-score-files
2461     (unless gnus-internal-global-score-files
2462       (gnus-score-search-global-directories gnus-global-score-files)))
2463   ;; Fix the kill-file dir variable.
2464   (setq gnus-kill-files-directory
2465         (file-name-as-directory gnus-kill-files-directory))
2466   ;; If we can't read it, there are no score files.
2467   (if (not (file-exists-p (expand-file-name gnus-kill-files-directory)))
2468       (setq gnus-score-file-list nil)
2469     (if (not (gnus-use-long-file-name 'not-score))
2470         ;; We do not use long file names, so we have to do some
2471         ;; directory traversing.
2472         (setq gnus-score-file-list
2473               (cons nil
2474                     (or gnus-short-name-score-file-cache
2475                         (prog2
2476                             (gnus-message 6 "Finding all score files...")
2477                             (setq gnus-short-name-score-file-cache
2478                                   (gnus-score-score-files-1
2479                                    gnus-kill-files-directory))
2480                           (gnus-message 6 "Finding all score files...done")))))
2481       ;; We want long file names.
2482       (when (or (not gnus-score-file-list)
2483                 (not (car gnus-score-file-list))
2484                 (gnus-file-newer-than gnus-kill-files-directory
2485                                       (car gnus-score-file-list)))
2486         (setq gnus-score-file-list
2487               (cons (nth 5 (file-attributes gnus-kill-files-directory))
2488                     (nreverse
2489                      (directory-files
2490                       gnus-kill-files-directory t
2491                       (gnus-score-file-regexp)))))))
2492     (cdr gnus-score-file-list)))
2493
2494 (defun gnus-score-score-files-1 (dir)
2495   "Return all possible score files under DIR."
2496   (let ((files (list (expand-file-name dir)))
2497         (regexp (gnus-score-file-regexp))
2498         (case-fold-search nil)
2499         seen out file)
2500     (while (setq file (pop files))
2501       (cond
2502        ;; Ignore files that start with a dot.
2503        ((string-match "^\\." (file-name-nondirectory file))
2504         nil)
2505        ;; Add subtrees of directory to also be searched.
2506        ((and (file-directory-p file)
2507              (not (member (file-truename file) seen)))
2508         (push (file-truename file) seen)
2509         (setq files (nconc (directory-files file t nil t) files)))
2510        ;; Add files to the list of score files.
2511        ((string-match regexp file)
2512         (push file out))))
2513     (or out
2514         ;; Return a dummy value.
2515         (list "~/News/this.file.does.not.exist.SCORE"))))
2516
2517 (defun gnus-score-file-regexp ()
2518   "Return a regexp that match all score files."
2519   (concat "\\(" (regexp-quote gnus-score-file-suffix )
2520           "\\|" (regexp-quote gnus-adaptive-file-suffix) "\\)\\'"))
2521
2522 (defun gnus-score-find-bnews (group)
2523   "Return a list of score files for GROUP.
2524 The score files are those files in the ~/News/ directory which matches
2525 GROUP using BNews sys file syntax."
2526   (let* ((sfiles (append (gnus-score-score-files group)
2527                          gnus-internal-global-score-files))
2528          (kill-dir (file-name-as-directory
2529                     (expand-file-name gnus-kill-files-directory)))
2530          (klen (length kill-dir))
2531          (score-regexp (gnus-score-file-regexp))
2532          (trans (cdr (assq ?: nnheader-file-name-translation-alist)))
2533          (group-trans (nnheader-translate-file-chars group t))
2534          ofiles not-match regexp)
2535     (save-excursion
2536       (set-buffer (gnus-get-buffer-create "*gnus score files*"))
2537       (buffer-disable-undo)
2538       ;; Go through all score file names and create regexp with them
2539       ;; as the source.
2540       (while sfiles
2541         (erase-buffer)
2542         (insert (car sfiles))
2543         (goto-char (point-min))
2544         ;; First remove the suffix itself.
2545         (when (re-search-forward (concat "." score-regexp) nil t)
2546           (replace-match "" t t)
2547           (goto-char (point-min))
2548           (if (looking-at (regexp-quote kill-dir))
2549               ;; If the file name was just "SCORE", `klen' is one character
2550               ;; too much.
2551               (delete-char (min (1- (point-max)) klen))
2552             (goto-char (point-max))
2553             (search-backward "/")
2554             (delete-region (1+ (point)) (point-min)))
2555           ;; If short file names were used, we have to translate slashes.
2556           (goto-char (point-min))
2557           (let ((regexp (concat
2558                          "[/:" (if trans (char-to-string trans) "") "]")))
2559             (while (re-search-forward regexp nil t)
2560               (replace-match "." t t)))
2561           ;; Kludge to get rid of "nntp+" problems.
2562           (goto-char (point-min))
2563           (when (looking-at "nn[a-z]+\\+")
2564             (search-forward "+")
2565             (forward-char -1)
2566             (insert "\\")
2567             (forward-char 1))
2568           ;; Kludge to deal with "++".
2569           (while (search-forward "+" nil t)
2570             (replace-match "\\+" t t))
2571           ;; Translate "all" to ".*".
2572           (goto-char (point-min))
2573           (while (search-forward "all" nil t)
2574             (replace-match ".*" t t))
2575           (goto-char (point-min))
2576           ;; Deal with "not."s.
2577           (if (looking-at "not.")
2578               (progn
2579                 (setq not-match t)
2580                 (setq regexp
2581                       (concat "^" (buffer-substring 5 (point-max)) "$")))
2582             (setq regexp (concat "^" (buffer-substring 1 (point-max)) "$"))
2583             (setq not-match nil))
2584           ;; Finally - if this resulting regexp matches the group name,
2585           ;; we add this score file to the list of score files
2586           ;; applicable to this group.
2587           (when (or (and not-match
2588                          (ignore-errors
2589                            (not (string-match regexp group-trans))))
2590                     (and (not not-match)
2591                          (ignore-errors (string-match regexp group-trans))))
2592             (push (car sfiles) ofiles)))
2593         (setq sfiles (cdr sfiles)))
2594       (kill-buffer (current-buffer))
2595       ;; Slight kludge here - the last score file returned should be
2596       ;; the local score file, whether it exists or not.  This is so
2597       ;; that any score commands the user enters will go to the right
2598       ;; file, and not end up in some global score file.
2599       (let ((localscore (gnus-score-file-name group)))
2600         (setq ofiles (cons localscore (delete localscore ofiles))))
2601       (gnus-sort-score-files (nreverse ofiles)))))
2602
2603 (defun gnus-score-find-single (group)
2604   "Return list containing the score file for GROUP."
2605   (list (or gnus-newsgroup-adaptive-score-file
2606             (gnus-score-file-name group gnus-adaptive-file-suffix))
2607         (gnus-score-file-name group)))
2608
2609 (defun gnus-score-find-hierarchical (group)
2610   "Return list of score files for GROUP.
2611 This includes the score file for the group and all its parents."
2612   (let* ((prefix (gnus-group-real-prefix group))
2613          (all (list nil))
2614          (group (gnus-group-real-name group))
2615          (start 0))
2616     (while (string-match "\\." group (1+ start))
2617       (setq start (match-beginning 0))
2618       (push (substring group 0 start) all))
2619     (push group all)
2620     (setq all
2621           (nconc
2622            (mapcar (lambda (group)
2623                      (gnus-score-file-name group gnus-adaptive-file-suffix))
2624                    (setq all (nreverse all)))
2625            (mapcar 'gnus-score-file-name all)))
2626     (if (equal prefix "")
2627         all
2628       (mapcar
2629        (lambda (file)
2630          (nnheader-translate-file-chars
2631           (concat (file-name-directory file) prefix
2632                   (file-name-nondirectory file))))
2633        all))))
2634
2635 (defun gnus-score-file-rank (file)
2636   "Return a number that says how specific score FILE is.
2637 Destroys the current buffer."
2638   (if (member file gnus-internal-global-score-files)
2639       0
2640     (when (string-match
2641            (concat "^" (regexp-quote
2642                         (expand-file-name
2643                          (file-name-as-directory gnus-kill-files-directory))))
2644            file)
2645       (setq file (substring file (match-end 0))))
2646     (insert file)
2647     (goto-char (point-min))
2648     (let ((beg (point))
2649           elems)
2650       (while (re-search-forward "[./]" nil t)
2651         (push (buffer-substring beg (1- (point)))
2652               elems))
2653       (erase-buffer)
2654       (setq elems (delete "all" elems))
2655       (length elems))))
2656
2657 (defun gnus-sort-score-files (files)
2658   "Sort FILES so that the most general files come first."
2659   (with-temp-buffer
2660     (let ((alist
2661            (mapcar
2662             (lambda (file)
2663               (cons (inline (gnus-score-file-rank file)) file))
2664             files)))
2665       (mapcar
2666        (lambda (f) (cdr f))
2667        (sort alist 'car-less-than-car)))))
2668
2669 (defun gnus-score-find-alist (group)
2670   "Return list of score files for GROUP.
2671 The list is determined from the variable gnus-score-file-alist."
2672   (let ((alist gnus-score-file-multiple-match-alist)
2673         score-files)
2674     ;; if this group has been seen before, return the cached entry
2675     (if (setq score-files (assoc group gnus-score-file-alist-cache))
2676         (cdr score-files)               ;ensures caching groups with no matches
2677       ;; handle the multiple match alist
2678       (while alist
2679         (when (string-match (caar alist) group)
2680           (setq score-files
2681                 (nconc score-files (copy-sequence (cdar alist)))))
2682         (setq alist (cdr alist)))
2683       (setq alist gnus-score-file-single-match-alist)
2684       ;; handle the single match alist
2685       (while alist
2686         (when (string-match (caar alist) group)
2687           ;; progn used just in case ("regexp") has no files
2688           ;; and score-files is still nil.  -sj
2689           ;; this can be construed as a "stop searching here" feature :>
2690           ;; and used to simplify regexps in the single-alist
2691           (setq score-files
2692                 (nconc score-files (copy-sequence (cdar alist))))
2693           (setq alist nil))
2694         (setq alist (cdr alist)))
2695       ;; cache the score files
2696       (push (cons group score-files) gnus-score-file-alist-cache)
2697       score-files)))
2698
2699 (defun gnus-all-score-files (&optional group)
2700   "Return a list of all score files for the current group."
2701   (let ((funcs gnus-score-find-score-files-function)
2702         (group (or group gnus-newsgroup-name))
2703         score-files)
2704     (when group
2705       ;; Make sure funcs is a list.
2706       (and funcs
2707            (not (listp funcs))
2708            (setq funcs (list funcs)))
2709       ;; Get the initial score files for this group.
2710       (when funcs
2711         (setq score-files (nreverse (gnus-score-find-alist group))))
2712       ;; Add any home adapt files.
2713       (let ((home (gnus-home-score-file group t)))
2714         (when home
2715           (push home score-files)
2716           (setq gnus-newsgroup-adaptive-score-file home)))
2717       ;; Check whether there is a `adapt-file' group parameter.
2718       (let ((param-file (gnus-group-find-parameter group 'adapt-file)))
2719         (when param-file
2720           (push param-file score-files)
2721           (setq gnus-newsgroup-adaptive-score-file param-file)))
2722       ;; Go through all the functions for finding score files (or actual
2723       ;; scores) and add them to a list.
2724       (while funcs
2725         (when (gnus-functionp (car funcs))
2726           (setq score-files
2727                 (nconc score-files (nreverse (funcall (car funcs) group)))))
2728         (setq funcs (cdr funcs)))
2729       ;; Add any home score files.
2730       (let ((home (gnus-home-score-file group)))
2731         (when home
2732           (push home score-files)))
2733       ;; Check whether there is a `score-file' group parameter.
2734       (let ((param-file (gnus-group-find-parameter group 'score-file)))
2735         (when param-file
2736           (push param-file score-files)))
2737       ;; Expand all files names.
2738       (let ((files score-files))
2739         (while files
2740           (when (stringp (car files))
2741             (setcar files (expand-file-name
2742                            (car files) gnus-kill-files-directory)))
2743           (pop files)))
2744       (setq score-files (nreverse score-files))
2745       ;; Remove any duplicate score files.
2746       (while (and score-files
2747                   (member (car score-files) (cdr score-files)))
2748         (pop score-files))
2749       (let ((files score-files))
2750         (while (cdr files)
2751           (if (member (cadr files) (cddr files))
2752               (setcdr files (cddr files))
2753             (pop files))))
2754       ;; Do the scoring if there are any score files for this group.
2755       score-files)))
2756
2757 (defun gnus-possibly-score-headers (&optional trace)
2758   "Do scoring if scoring is required."
2759   (let ((score-files (gnus-all-score-files)))
2760     (when score-files
2761       (gnus-score-headers score-files trace))))
2762
2763 (defun gnus-score-file-name (newsgroup &optional suffix)
2764   "Return the name of a score file for NEWSGROUP."
2765   (let ((suffix (or suffix gnus-score-file-suffix)))
2766     (nnheader-translate-file-chars
2767      (cond
2768       ((or (null newsgroup)
2769            (string-equal newsgroup ""))
2770        ;; The global score file is placed at top of the directory.
2771        (expand-file-name suffix gnus-kill-files-directory))
2772       ((gnus-use-long-file-name 'not-score)
2773        ;; Append ".SCORE" to newsgroup name.
2774        (expand-file-name (concat (gnus-newsgroup-savable-name newsgroup)
2775                                  "." suffix)
2776                          gnus-kill-files-directory))
2777       (t
2778        ;; Place "SCORE" under the hierarchical directory.
2779        (expand-file-name (concat (gnus-newsgroup-directory-form newsgroup)
2780                                  "/" suffix)
2781                          gnus-kill-files-directory))))))
2782
2783 (defun gnus-score-search-global-directories (files)
2784   "Scan all global score directories for score files."
2785   ;; Set the variable `gnus-internal-global-score-files' to all
2786   ;; available global score files.
2787   (interactive (list gnus-global-score-files))
2788   (let (out)
2789     (while files
2790       ;; #### /$ Unix-specific?
2791       (if (string-match "/$" (car files))
2792           (setq out (nconc (directory-files
2793                             (car files) t
2794                             (concat (gnus-score-file-regexp) "$"))))
2795         (push (car files) out))
2796       (setq files (cdr files)))
2797     (setq gnus-internal-global-score-files out)))
2798
2799 (defun gnus-score-default-fold-toggle ()
2800   "Toggle folding for new score file entries."
2801   (interactive)
2802   (setq gnus-score-default-fold (not gnus-score-default-fold))
2803   (if gnus-score-default-fold
2804       (gnus-message 1 "New score file entries will be case insensitive.")
2805     (gnus-message 1 "New score file entries will be case sensitive.")))
2806
2807 ;;; Home score file.
2808
2809 (defun gnus-home-score-file (group &optional adapt)
2810   "Return the home score file for GROUP.
2811 If ADAPT, return the home adaptive file instead."
2812   (let ((list (if adapt gnus-home-adapt-file gnus-home-score-file))
2813         elem found)
2814     ;; Make sure we have a list.
2815     (unless (listp list)
2816       (setq list (list list)))
2817     ;; Go through the list and look for matches.
2818     (while (and (not found)
2819                 (setq elem (pop list)))
2820       (setq found
2821             (cond
2822              ;; Simple string.
2823              ((stringp elem)
2824               elem)
2825              ;; Function.
2826              ((gnus-functionp elem)
2827               (funcall elem group))
2828              ;; Regexp-file cons.
2829              ((consp elem)
2830               (when (string-match (gnus-globalify-regexp (car elem)) group)
2831                 (replace-match (cadr elem) t nil group))))))
2832     (when found
2833       (if (file-name-absolute-p found)
2834           found
2835         (nnheader-concat gnus-kill-files-directory found)))))
2836
2837 (defun gnus-hierarchial-home-score-file (group)
2838   "Return the score file of the top-level hierarchy of GROUP."
2839   (if (string-match "^[^.]+\\." group)
2840       (concat (match-string 0 group) gnus-score-file-suffix)
2841     ;; Group name without any dots.
2842     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2843             gnus-score-file-suffix)))
2844
2845 (defun gnus-hierarchial-home-adapt-file (group)
2846   "Return the adapt file of the top-level hierarchy of GROUP."
2847   (if (string-match "^[^.]+\\." group)
2848       (concat (match-string 0 group) gnus-adaptive-file-suffix)
2849     ;; Group name without any dots.
2850     (concat group (if (gnus-use-long-file-name 'not-score) "." "/")
2851             gnus-adaptive-file-suffix)))
2852
2853 (defun gnus-current-home-score-file (group)
2854   "Return the \"current\" regular score file."
2855   (car (nreverse (gnus-score-find-alist group))))
2856
2857 ;;;
2858 ;;; Score decays
2859 ;;;
2860
2861 (defun gnus-decay-score (score)
2862   "Decay SCORE according to `gnus-score-decay-constant' and `gnus-score-decay-scale'."
2863   (floor
2864    (- score
2865       (* (if (< score 0) -1 1)
2866          (min (abs score)
2867               (max gnus-score-decay-constant
2868                    (* (abs score)
2869                       gnus-score-decay-scale)))))))
2870
2871 (defun gnus-decay-scores (alist day)
2872   "Decay non-permanent scores in ALIST."
2873   (let ((times (- (time-to-days (current-time)) day))
2874         kill entry updated score n)
2875     (unless (zerop times)               ;Done decays today already?
2876       (while (setq entry (pop alist))
2877         (when (stringp (car entry))
2878           (setq entry (cdr entry))
2879           (while (setq kill (pop entry))
2880             (when (nth 2 kill)
2881               (setq updated t)
2882               (setq score (or (nth 1 kill)
2883                               gnus-score-interactive-default-score)
2884                     n times)
2885               (while (natnump (decf n))
2886                 (setq score (funcall gnus-decay-score-function score)))
2887               (setcdr kill (cons score
2888                                  (cdr (cdr kill)))))))))
2889     ;; Return whether this score file needs to be saved.  By Je-haysuss!
2890     updated))
2891
2892 (defun gnus-score-regexp-bad-p (regexp)
2893   "Test whether REGEXP is safe for Gnus scoring.
2894 A regexp is unsafe if it matches newline or a buffer boundary.
2895
2896 If the regexp is good, return nil.  If the regexp is bad, return a
2897 cons cell (SYM . STRING), where the symbol SYM is `new' or `bad'.
2898 In the `new' case, the string is a safe replacement for REGEXP.
2899 In the `bad' case, the string is a unsafe subexpression of REGEXP,
2900 and we do not have a simple replacement to suggest.
2901
2902 See `(Gnus)Scoring Tips' for examples of good regular expressions."
2903   (let (case-fold-search)
2904     (and
2905      ;; First, try a relatively fast necessary condition.
2906      ;; Notice ranges (like [^:] or [\t-\r]), \s>, \Sw, \W, \', \`:
2907      (string-match "\n\\|\\\\[SsW`']\\|\\[\\^\\|[\0-\n]-" regexp)
2908      ;; Now break the regexp into tokens, and check each:
2909      (let ((tail regexp)                ; remaining regexp to check
2910            tok                          ; current token
2911            bad                          ; nil, or bad subexpression
2912            new                          ; nil, or replacement regexp so far
2913            end)                         ; length of current token
2914        (while (and (not bad)
2915                    (string-match
2916                     "\\`\\(\\\\[sS]?.\\|\\[\\^?]?[^]]*]\\|[^\\]\\)"
2917                     tail))
2918          (setq end (match-end 0)
2919                tok (substring tail 0 end)
2920                tail (substring tail end))
2921          (if;; Is token `bad' (matching newline or buffer ends)?
2922              (or (member tok '("\n" "\\W" "\\`" "\\'"))
2923                  ;; This next handles "[...]", "\\s.", and "\\S.":
2924                  (and (> end 2) (string-match tok "\n")))
2925              (let ((newtok
2926                     ;; Try to suggest a replacement for tok ...
2927                     (cond ((string-equal tok "\\`") "^") ; or "\\(^\\)"
2928                           ((string-equal tok "\\'") "$") ; or "\\($\\)"
2929                           ((string-match "\\[\\^" tok) ; very common
2930                            (concat (substring tok 0 -1) "\n]")))))
2931                (if newtok
2932                    (setq new
2933                          (concat
2934                           (or new
2935                               ;; good prefix so far:
2936                               (substring regexp 0 (- (+ (length tail) end))))
2937                           newtok))
2938                  ;; No replacement idea, so give up:
2939                  (setq bad tok)))
2940            ;; tok is good, may need to extend new
2941            (and new (setq new (concat new tok)))))
2942        ;; Now return a value:
2943        (cond
2944         (bad (cons 'bad bad))
2945         (new (cons 'new new))
2946         (t nil))))))
2947
2948 (provide 'gnus-score)
2949
2950 ;;; gnus-score.el ends here