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