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