* wl-score.el (wl-score-save): Bind print-length and print-level.
[elisp/wanderlust.git] / wl / wl-score.el
1 ;;; wl-score.el --- Scoring in Wanderlust.
2
3 ;; Copyright (C) 1998,1999,2000 Masahiro MURATA <muse@ba2.so-net.ne.jp>
4 ;; Copyright (C) 1998,1999,2000 Yuuichi Teranishi <teranisi@gohome.org>
5
6 ;; Author: Masahiro MURATA <muse@ba2.so-net.ne.jp>
7 ;; Keywords: mail, net news
8
9 ;; This file is part of Wanderlust (Yet Another Message Interface on Emacsen).
10
11 ;; This program 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 ;; This program 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
27 ;;; Commentary:
28 ;; Original codes are gnus-score.el and score-mode.el
29
30 ;;; Code:
31 ;;
32
33
34 (require 'wl-vars)
35 (require 'wl-util)
36 (eval-when-compile
37   (require 'elmo-msgdb))                ; for inline functions
38
39 (defvar wl-score-edit-header-char
40   '((?a "from" nil string)
41     (?s "subject" nil string)
42     (?i "message-id" nil string)
43     (?r "references" "message-id" string)
44     (?x "xref" nil string)
45     (?e "extra" nil string)
46     (?l "lines" nil number)
47     (?d "date" nil date)
48     (?f "followup" nil string)
49     (?t "thread" "message-id" string)))
50
51 (defvar wl-score-edit-type-char
52   '((?s s "substring" string)
53     (?e e "exact string" string)
54     (?f f "fuzzy string" string)
55     (?r r "regexp string" string)
56     (?b before "before date" date)
57     (?a after "after date" date)
58     (?n at "this date" date)
59     (?< < "less than number" number)
60     (?> > "greater than number" number)
61     (?= = "equal to number" number)))
62
63 (defvar wl-score-edit-perm-char
64   '((?t temp "temporary")
65     (?p perm "permanent")
66     (?i now "immediate")))
67
68 ;;; Global Variable
69
70 (defconst wl-score-header-index
71   ;; Name to function alist.
72   '(("number"     wl-score-integer  elmo-msgdb-overview-entity-get-number) ;;0
73     ("subject"    wl-score-string   3 charset)
74     ("from"       wl-score-string   2 charset)
75     ("date"       wl-score-date     elmo-msgdb-overview-entity-get-date) ;;4
76     ("message-id" wl-score-string   elmo-msgdb-overview-entity-get-id)
77     ("references" wl-score-string   1)
78     ("to"         wl-score-string   5)
79     ("cc"         wl-score-string   6)
80     ("chars"      wl-score-integer  elmo-msgdb-overview-entity-get-size) ;;7
81     ("lines"      wl-score-integer  wl-score-overview-entity-get-lines)
82     ("xref"       wl-score-string   wl-score-overview-entity-get-xref)
83     ("extra"      wl-score-extra    wl-score-overview-entity-get-extra mime)
84     ("followup"   wl-score-followup 2 charset)
85     ("thread"     wl-score-thread   1)))
86
87 (defvar wl-score-auto-make-followup-entry nil)
88 (defvar wl-score-debug nil)
89 (defvar wl-score-trace nil)
90
91 (defvar wl-score-alist nil)
92 (defvar wl-score-index nil)
93 (defvar wl-score-cache nil)
94 (defvar wl-scores-messages nil)
95 (defvar wl-current-score-file nil)
96 (defvar wl-score-make-followup nil)
97 (defvar wl-score-stop-add-entry nil)
98
99 (defvar wl-prev-winconf nil)
100 (defvar wl-score-help-winconf nil)
101 (defvar wl-score-header-buffer-list nil)
102 (defvar wl-score-alike-hashtb nil)
103
104 (defvar wl-score-edit-exit-function nil
105   "Function run on exit from the score buffer.")
106
107 (make-variable-buffer-local 'wl-current-score-file)
108 (make-variable-buffer-local 'wl-score-alist)
109
110 ;; Utility functions
111
112 (defun wl-score-simplify-buffer-fuzzy ()
113   "Simplify string in the buffer fuzzily.
114 The string in the accessible portion of the current buffer is simplified.
115 It is assumed to be a single-line subject.
116 Whitespace is generally cleaned up, and miscellaneous leading/trailing
117 matter is removed.  Additional things can be deleted by setting
118 `wl-score-simplify-fuzzy-regexp'."
119   (let ((regexp
120          (if (listp wl-score-simplify-fuzzy-regexp)
121              (mapconcat (function identity) wl-score-simplify-fuzzy-regexp
122                         "\\|")
123            wl-score-simplify-fuzzy-regexp))
124         (case-fold-search t)
125         modified-tick)
126     (elmo-buffer-replace "\t" " ")
127     (while (not (eq modified-tick (buffer-modified-tick)))
128       (setq modified-tick (buffer-modified-tick))
129       (elmo-buffer-replace regexp)
130       (elmo-buffer-replace "^ *\\[[-+?*!][-+?*!]\\] *")
131       (elmo-buffer-replace
132        "^ *\\(re\\|fw\\|fwd\\|forward\\)[[{(^0-9]*[])}]?[:;] *")
133       (elmo-buffer-replace "^[[].*:\\( .*\\)[]]$" "\\1"))
134     (elmo-buffer-replace " *[[{(][^()\n]*[]})] *$")
135     (elmo-buffer-replace "  +" " ")
136     (elmo-buffer-replace " $")
137     (elmo-buffer-replace "^ +")))
138
139 (defun wl-score-simplify-string-fuzzy (string)
140   "Simplify a STRING fuzzily.
141 See `wl-score-simplify-buffer-fuzzy' for details."
142   (elmo-set-work-buf
143    (let ((case-fold-search t))
144      (insert string)
145      (wl-score-simplify-buffer-fuzzy)
146      (buffer-string))))
147
148 (defun wl-score-simplify-subject (subject)
149   "Simplify a SUBJECT fuzzily.
150 Remove Re, Was, Fwd etc."
151   (elmo-set-work-buf
152    (let ((regexp
153           (if (listp wl-score-simplify-fuzzy-regexp)
154               (mapconcat (function identity) wl-score-simplify-fuzzy-regexp
155                          "\\|")
156             wl-score-simplify-fuzzy-regexp))
157          (case-fold-search t))
158      (insert subject)
159      (elmo-buffer-replace regexp)
160      (elmo-buffer-replace
161       "^[ \t]*\\(re\\|was\\|fw\\|fwd\\|forward\\)[:;][ \t]*")
162      (buffer-string))))
163
164 ;;
165
166 (defun wl-score-overview-entity-get-lines (entity)
167   (let ((lines
168          (elmo-msgdb-overview-entity-get-extra-field entity "lines")))
169     (and lines
170          (string-to-int lines))))
171
172 (defun wl-score-overview-entity-get-xref (entity)
173   (or (elmo-msgdb-overview-entity-get-extra-field entity "xref")
174       ""))
175
176 (defun wl-score-overview-entity-get-extra (entity header &optional decode)
177   (let ((extra (elmo-msgdb-overview-entity-get-extra-field entity header)))
178     (if (and extra decode)
179         (eword-decode-string
180          (decode-mime-charset-string extra elmo-mime-charset))
181       (or extra ""))))
182
183 (defun wl-string> (s1 s2)
184   (not (or (string< s1 s2)
185            (string= s1 s2))))
186
187 (defmacro wl-score-ov-entity-get-by-index (entity index)
188   (` (aref (cdr (, entity)) (, index))))
189
190 (defsubst wl-score-ov-entity-get (entity index &optional extra decode)
191   (let ((str (cond ((integerp index)
192                     (wl-score-ov-entity-get-by-index entity index))
193                    (extra
194                     (funcall index entity extra decode))
195                    (t
196                     (funcall index entity)))))
197     (if (and decode (not extra))
198         (decode-mime-charset-string str elmo-mime-charset)
199       str)))
200
201 (defun wl-score-string-index< (a1 a2)
202   (string-lessp (wl-score-ov-entity-get-by-index (car a1) wl-score-index)
203                 (wl-score-ov-entity-get-by-index (car a2) wl-score-index)))
204
205 (defun wl-score-string-func< (a1 a2)
206   (string-lessp (funcall wl-score-index (car a1))
207                 (funcall wl-score-index (car a2))))
208
209 (defun wl-score-string-sort (messages index)
210   (let ((func (cond ((integerp index)
211                      'wl-score-string-index<)
212                     (t
213                      'wl-score-string-func<))))
214     (sort messages func)))
215
216 (defsubst wl-score-get (symbol &optional alist)
217   "Get SYMBOL's definition in ALIST."
218   ;; Get SYMBOL's definition in ALIST.
219   (cdr (assoc symbol
220               (or alist
221                   wl-score-alist))))
222
223 (defun wl-score-set (symbol value &optional alist warn)
224   "Set SYMBOL to VALUE in ALIST."
225   ;; Set SYMBOL to VALUE in ALIST.
226   (let* ((alist (or alist wl-score-alist))
227          (entry (assoc symbol alist)))
228     (cond ((wl-score-get 'read-only alist)
229            ;; This is a read-only score file, so we do nothing.
230            (when warn
231              (message "Note: read-only score file; entry discarded")))
232           (entry
233            (setcdr entry value))
234           ((null alist)
235            (error "Empty alist"))
236           (t
237            (setcdr alist
238                    (cons (cons symbol value) (cdr alist)))))))
239
240 (defun wl-score-cache-clean ()
241   "Cleaning score cache.
242 Set `wl-score-cache' nil."
243   (interactive)
244   (setq wl-score-cache nil))
245
246 (defun wl-score-load-score-alist (file)
247   "Read score FILE."
248   (let (alist)
249     (if (not (file-readable-p file))
250         (setq wl-score-alist nil)
251       (with-temp-buffer
252         (wl-as-mime-charset wl-score-mode-mime-charset
253           (insert-file-contents file))
254         (goto-char (point-min))
255         ;; Only do the loading if the score file isn't empty.
256         (when (save-excursion (re-search-forward "[()0-9a-zA-Z]" nil t))
257           (setq alist
258                 (condition-case ()
259                     (read (current-buffer))
260                   (error "Problem with score file %s" file))))
261         (cond
262          ((and alist
263                (atom alist))
264           (error "Invalid syntax with score file %s" file))
265          (t
266           (setq wl-score-alist alist)))))))
267
268 (defun wl-score-save ()
269   "Save all score information."
270   ;; Save all score information.
271   (let ((cache wl-score-cache)
272         entry score file dir)
273     (with-temp-buffer
274       (setq wl-score-alist nil)
275       (while cache
276         (setq entry (pop cache)
277               file (car entry)
278               score (cdr entry))
279         (unless (or (not (equal (wl-score-get 'touched score) '(t)))
280                     (wl-score-get 'read-only score)
281                     (and (file-exists-p file)
282                          (not (file-writable-p file))))
283           (setq score (setcdr entry (wl-delete-alist 'touched score)))
284           (erase-buffer)
285           (let (emacs-lisp-mode-hook
286                 (lisp-mode-syntax-table wl-score-mode-syntax-table)
287                 print-length print-level)
288             (pp score (current-buffer)))
289           (setq dir (file-name-directory file))
290           (if (file-directory-p dir)
291               (); ok.
292             (if (file-exists-p dir)
293                 (error "File %s already exists" dir)
294               (elmo-make-directory dir)))
295           ;; If the score file is empty, we delete it.
296           (if (zerop (buffer-size))
297               (when (file-exists-p file) ; added by teranisi.
298                 (delete-file file))
299             ;; There are scores, so we write the file.
300             (when (file-writable-p file)
301               (wl-as-mime-charset wl-score-mode-mime-charset
302                 (write-region (point-min) (point-max)
303                               file nil 'no-msg)))))))))
304
305 (defun wl-score-remove-from-cache (file)
306   (setq wl-score-cache
307         (delq (assoc file wl-score-cache) wl-score-cache)))
308
309 (defun wl-score-load-file (file)
310   (let* ((file (expand-file-name
311                 (or (and (string-match
312                           (concat "^" (regexp-quote
313                                        (expand-file-name
314                                         wl-score-files-directory)))
315                           (expand-file-name file))
316                          file)
317                     (expand-file-name
318                      file
319                      (file-name-as-directory wl-score-files-directory)))))
320          (cached (assoc file wl-score-cache))
321          alist)
322     (if cached
323         ;; The score file was already loaded.
324         (setq alist (cdr cached))
325       ;; We load the score file.
326       (setq wl-score-alist nil)
327       (setq alist (wl-score-load-score-alist file))
328       (unless (assq 'touched alist)
329         (wl-push (list 'touched nil) alist))
330       (wl-push (cons file alist) wl-score-cache))
331     (let ((a alist))
332       (while a
333         ;; Downcase all header names.
334         (cond
335          ((stringp (caar a))
336           (setcar (car a) (downcase (caar a)))))
337         (pop a)))
338     (setq wl-current-score-file file)
339     (setq wl-score-alist alist)))
340
341 (defun wl-score-get-score-files (score-alist folder)
342   (let ((files (wl-get-assoc-list-value
343                 score-alist folder
344                 (if (not wl-score-folder-alist-matchone) 'all-list)))
345         fl f)
346     (while (setq f (wl-pop files))
347       (wl-append
348        fl
349        (cond ((functionp f)
350               (funcall f  folder))
351              (t
352               (list f)))))
353     fl))
354
355 (defun wl-score-get-score-alist (&optional folder)
356   (interactive)
357   (let* ((fld (or folder (wl-summary-buffer-folder-name)))
358          (score-alist (reverse
359                        (wl-score-get-score-files wl-score-folder-alist fld)))
360          alist scores)
361     (setq wl-current-score-file nil)
362     (unless (and wl-score-default-file
363                  (member wl-score-default-file score-alist))
364       (wl-push wl-score-default-file score-alist))
365     (while score-alist
366       (setq alist
367             (cond ((stringp (car score-alist))  ;; file
368                    (wl-score-load-file (car score-alist)))
369                   ((consp (car score-alist))    ;; alist
370                    (car score-alist))
371                   ((boundp (car score-alist))   ;; variable
372                    (symbol-value (car score-alist)))
373                   (t
374                    (error "Void variable: %s" (car score-alist)))))
375       (let ((mark (car (wl-score-get 'mark alist)))
376             (expunge (car (wl-score-get 'expunge alist)))
377             (mark-and-expunge (car (wl-score-get 'mark-and-expunge alist)))
378             (temp (car (wl-score-get 'temp alist))) ; obsolate
379             (target (car (wl-score-get 'target alist)))
380             (important (car (wl-score-get 'important alist))))
381         (setq wl-summary-important-above
382               (or important wl-summary-important-above))
383         (setq wl-summary-target-above
384               (or target temp wl-summary-target-above))
385         (setq wl-summary-mark-below
386               (or mark mark-and-expunge wl-summary-mark-below))
387         (setq wl-summary-expunge-below
388               (or expunge mark-and-expunge wl-summary-expunge-below)))
389       (wl-append scores (list alist))
390       (setq score-alist (cdr score-alist)))
391     scores))
392
393 (defun wl-score-headers (scores &optional msgdb force-msgs not-add)
394   (let* ((elmo-mime-charset wl-summary-buffer-mime-charset)
395          (now (wl-day-number (current-time-string)))
396          (expire (and wl-score-expiry-days
397                       (- now wl-score-expiry-days)))
398          (overview (elmo-msgdb-get-overview
399                     (or msgdb (wl-summary-buffer-msgdb))))
400          (mark-alist (elmo-msgdb-get-mark-alist
401                       (or msgdb (wl-summary-buffer-msgdb))))
402          (wl-score-stop-add-entry not-add)
403          entries
404          news new num entry ov header)
405     (setq wl-scores-messages nil)
406     (message "Scoring...")
407
408     ;; Create messages, an alist of the form `(OVERVIEW . SCORE)'.
409     (while (setq ov (pop overview))
410       (when (and (not (assq
411                        (setq num
412                              (elmo-msgdb-overview-entity-get-number ov))
413                        wl-summary-scored))
414                  (or (memq num force-msgs)
415                      (member (cadr (assq num mark-alist))
416                              wl-summary-score-marks)))
417         (setq wl-scores-messages
418               (cons (cons ov (or wl-summary-default-score 0))
419                     wl-scores-messages))))
420
421     (save-excursion
422       (setq news scores)
423       (while news
424         (setq scores news
425               news nil)
426         ;; Run each header through the score process.
427         (setq entries wl-score-header-index)
428         (while entries
429           (setq entry (pop entries)
430                 header (car entry))
431           (if (> (length wl-scores-messages) 500)
432               (message "Scoring...\"%s\"" header))
433           (when (< 0 (apply 'max (mapcar
434                                   (lambda (score)
435                                     (length (wl-score-get header score)))
436                                   scores)))
437             ;; Call the scoring function for this type of "header".
438             (when (setq new (funcall (nth 1 entry) scores header now expire))
439               (wl-push new news))))))
440
441     ;; Add messages to `wl-summary-scored'.
442     (let (entry num score)
443       (while wl-scores-messages
444         (when (or (/= wl-summary-default-score
445                       (cdar wl-scores-messages)))
446           (setq num (elmo-msgdb-overview-entity-get-number
447                      (caar wl-scores-messages))
448                 score (cdar wl-scores-messages))
449           (if (setq entry (assq num wl-summary-scored))
450               (setcdr entry (+ score (cdr entry)))
451             (wl-push (cons num score)
452                   wl-summary-scored)))
453         (setq wl-scores-messages (cdr wl-scores-messages))))
454     (message "Scoring...done")
455     ;; Remove buffers.
456     (while wl-score-header-buffer-list
457       (elmo-kill-buffer (pop wl-score-header-buffer-list)))))
458
459 (defun wl-score-integer (scores header now expire)
460   (let ((wl-score-index (nth 2 (assoc header wl-score-header-index)))
461         entries alist)
462
463     ;; Find matches.
464     (while scores
465       (setq alist (car scores)
466             scores (cdr scores)
467             entries (assoc header alist))
468       (while (cdr entries)              ;First entry is the header index.
469         (let* ((rest (cdr entries))
470                (kill (car rest))
471                (match (nth 0 kill))
472                (type (or (nth 3 kill) '>))
473                (score (or (nth 1 kill) wl-score-interactive-default-score))
474                (date (nth 2 kill))
475                (found nil)
476                (match-func (if (memq type '(> < <= >= =))
477                                type
478                              (error "Invalid match type: %s" type)))
479                (messages wl-scores-messages))
480           (while messages
481             (when (funcall match-func
482                            (or (wl-score-ov-entity-get
483                                 (caar messages) wl-score-index)
484                                0)
485                            match)
486               (setq found t)
487               (setcdr (car messages) (+ score (cdar messages))))
488             (setq messages (cdr messages)))
489           ;; Update expire date
490           (cond ((null date))           ;Permanent entry.
491                 ((and found wl-score-update-entry-dates) ;Match, update date.
492                  (wl-score-set 'touched '(t) alist)
493                  (setcar (nthcdr 2 kill) now))
494                 ((and expire (< date expire)) ;Old entry, remove.
495                  (wl-score-set 'touched '(t) alist)
496                  (setcdr entries (cdr rest))
497                  (setq rest entries)))
498           (setq entries rest)))))
499   nil)
500
501 (defun wl-score-date (scores header now expire)
502   (let ((wl-score-index (nth 2 (assoc header wl-score-header-index)))
503         entries alist match match-func message)
504     ;; Find matches.
505     (while scores
506       (setq alist (car scores)
507             scores (cdr scores)
508             entries (assoc header alist))
509       (while (cdr entries)              ;First entry is the header index.
510         (let* ((rest (cdr entries))
511                (kill (car rest))
512                (type (or (nth 3 kill) 'before))
513                (score (or (nth 1 kill) wl-score-interactive-default-score))
514                (date (nth 2 kill))
515                (found nil)
516                (messages wl-scores-messages)
517                l)
518           (cond
519            ((eq type 'after)
520             (setq match-func 'string<
521                   match (wl-date-iso8601 (nth 0 kill))))
522            ((eq type 'before)
523             (setq match-func 'wl-string>
524                   match (wl-date-iso8601 (nth 0 kill))))
525            ((eq type 'at)
526             (setq match-func 'string=
527                   match (wl-date-iso8601 (nth 0 kill))))
528            ((eq type 'regexp)
529             (setq match-func 'string-match
530                   match (nth 0 kill)))
531            (t (error "Invalid match type: %s" type)))
532           (while (setq message (pop messages))
533             (when (and
534                    (setq l (wl-score-ov-entity-get
535                             (car message) wl-score-index))
536                    (funcall match-func match (wl-date-iso8601 l)))
537               (setq found t)
538               (setcdr message (+ score (cdr message)))))
539           ;; Update expire date
540           (cond ((null date))           ;Permanent entry.
541                 ((and found wl-score-update-entry-dates) ;Match, update date.
542                  (wl-score-set 'touched '(t) alist)
543                  (setcar (nthcdr 2 kill) now))
544                 ((and expire (< date expire)) ;Old entry, remove.
545                  (wl-score-set 'touched '(t) alist)
546                  (setcdr entries (cdr rest))
547                  (setq rest entries)))
548           (setq entries rest)))))
549   nil)
550
551 (defun wl-score-extra (scores header now expire)
552   (let ((score-list scores)
553         entries alist extra extras)
554     (while score-list
555       (setq alist (pop score-list)
556             entries (assoc header alist))
557       (while (cdr entries)
558         (setq extra (nth 4 (cadr entries)))
559         (unless (member extra extras)
560           (wl-push extra extras))
561         (setq entries (cdr entries))))
562     (while extras
563       (wl-score-string scores header now expire (car extras))
564       (setq extras (cdr extras)))
565     nil))
566
567 (defmacro wl-score-put-alike ()
568   (` (elmo-set-hash-val (format "#%d" (wl-count-lines))
569                         alike
570                         wl-score-alike-hashtb)))
571
572 (defmacro wl-score-get-alike ()
573   (` (elmo-get-hash-val (format "#%d" (wl-count-lines))
574                         wl-score-alike-hashtb)))
575
576 (defun wl-score-insert-header (header messages &optional extra-header)
577   (let ((mime-decode (nth 3 (assoc header wl-score-header-index)))
578         (buffer-name (concat "*Score-Headers-" header
579                              (if extra-header
580                                  (concat "-" extra-header)
581                                "")
582                              "*"))
583         buf)
584     (if (setq buf (get-buffer buffer-name))
585         (set-buffer buf)
586       (set-buffer (setq buf (get-buffer-create buffer-name)))
587       (wl-append wl-score-header-buffer-list (list buf))
588       (buffer-disable-undo (current-buffer))
589       (make-local-variable 'wl-score-alike-hashtb)
590       (setq wl-score-alike-hashtb (elmo-make-hash (* (length messages) 2)))
591       (when mime-decode
592         (elmo-set-buffer-multibyte default-enable-multibyte-characters))
593       (let (art last this alike)
594         (while (setq art (pop messages))
595           (setq this (wl-score-ov-entity-get (car art)
596                                              wl-score-index
597                                              extra-header))
598           (and this (setq this (std11-unfold-string this)))
599           (if (equal last this)
600               ;; O(N*H) cons-cells used here, where H is the number of
601               ;; headers.
602               (wl-push art alike)
603             (when last
604               (wl-score-put-alike)
605               (insert last ?\n))
606             (setq alike (list art)
607                   last this)))
608         (when last
609           (wl-score-put-alike)
610           (insert last ?\n))
611         (when mime-decode
612           (decode-mime-charset-region (point-min) (point-max)
613                                       elmo-mime-charset)
614           (when (eq mime-decode 'mime)
615             (eword-decode-region (point-min) (point-max))))))))
616
617 (defun wl-score-string (scores header now expire &optional extra-header)
618   "Insert the unique message headers in the buffer."
619   ;; Insert the unique message headers in the buffer.
620   (let ((wl-score-index (nth 2 (assoc header wl-score-header-index)))
621         entries alist messages
622         fuzzies kill)
623     (when (integerp wl-score-index)
624       (setq wl-scores-messages
625             (wl-score-string-sort wl-scores-messages wl-score-index)))
626     (setq messages wl-scores-messages)
627
628     (wl-score-insert-header header messages extra-header)
629
630     ;; Go through all the score alists and pick out the entries
631     ;; for this header.
632     (while scores
633       (setq alist (pop scores)
634             entries (assoc header alist))
635       (while (cdr entries)              ;First entry is the header index.
636         (let* ((kill (cadr entries))
637                (type (or (nth 3 kill) 's))
638                (score (or (nth 1 kill) wl-score-interactive-default-score))
639                (date (nth 2 kill))
640                (extra (nth 4 kill))     ; non-standard header; string.
641                (mt (aref (symbol-name type) 0))
642                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
643                (dmt (downcase mt))
644                (match (nth 0 kill))
645                (search-func
646                 (cond ((= dmt ?r) 're-search-forward)
647                       ((memq dmt '(?e ?s ?f)) 'search-forward)
648                       ((= dmt ?w) nil)
649                       (t (error "Invalid match type: %s" type))))
650                arts art found)
651           (if (and extra-header
652                    (or (not extra)
653                        (not (string= extra-header extra))))
654               (setq entries (cdr entries))
655             (cond
656              ;; Fuzzy matches.  We save these for later.
657              ((= dmt ?f)
658               (wl-push (cons entries alist) fuzzies)
659               (setq entries (cdr entries)))
660              (t
661               ;; Regexp, substring and exact matching.
662               (goto-char (point-min))
663               (when (and (not (= dmt ?e))
664                          (string= match ""))
665                 (setq match "\n"))
666               (while (and (not (eobp))
667                           (funcall search-func match nil t))
668                 (when (or (not (= dmt ?e))
669                           ;; Is it really exact?
670                           (and (eolp)
671                                (= (save-excursion (forward-line 0) (point))
672                                   (match-beginning 0))))
673 ;;;               (end-of-line)
674                   (setq found (setq arts (wl-score-get-alike)))
675                   ;; Found a match, update scores.
676                   (while (setq art (pop arts))
677                     (setcdr art (+ score (cdr art)))))
678                 (forward-line 1))
679               ;; Update expiry date
680               (cond
681                ;; Permanent entry.
682                ((null date)
683                 (setq entries (cdr entries)))
684                ;; We have a match, so we update the date.
685                ((and found wl-score-update-entry-dates)
686                 (wl-score-set 'touched '(t) alist)
687                 (setcar (nthcdr 2 kill) now)
688                 (setq entries (cdr entries)))
689                ;; This entry has expired, so we remove it.
690                ((and expire (< date expire))
691                 (wl-score-set 'touched '(t) alist)
692                 (setcdr entries (cddr entries)))
693                ;; No match; go to next entry.
694                (t
695                 (setq entries (cdr entries))))))))))
696
697     ;; Find fuzzy matches.
698     (when fuzzies
699       ;; Simplify the entire buffer for easy matching.
700       (wl-score-simplify-buffer-fuzzy)
701       (while (setq kill (cadaar fuzzies))
702         (let* ((match (nth 0 kill))
703                (type (nth 3 kill))
704                (score (or (nth 1 kill) wl-score-interactive-default-score))
705                (date (nth 2 kill))
706                (mt (aref (symbol-name type) 0))
707                (case-fold-search (not (= mt ?F)))
708                arts art found)
709           (goto-char (point-min))
710           (while (and (not (eobp))
711                       (search-forward match nil t))
712             (when (and (eolp)
713                        (= (save-excursion (forward-line 0) (point))
714                           (match-beginning 0)))
715               (setq found (setq arts (wl-score-get-alike)))
716               (while (setq art (pop arts))
717                 (setcdr art (+ score (cdr art)))))
718             (forward-line 1))
719           ;; Update expiry date
720           (cond
721            ;; Permanent.
722            ((null date))
723            ;; Match, update date.
724            ((and found wl-score-update-entry-dates)
725             (wl-score-set 'touched '(t) (cdar fuzzies))
726             (setcar (nthcdr 2 kill) now))
727            ;; Old entry, remove.
728            ((and expire (< date expire))
729             (wl-score-set 'touched '(t) (cdar fuzzies))
730             (setcdr (caar fuzzies) (cddaar fuzzies))))
731           (setq fuzzies (cdr fuzzies)))))
732     nil))
733
734 (defun wl-score-thread (scores header now expire)
735   (wl-score-followup scores header now expire t))
736
737 (defun wl-score-followup (scores header now expire &optional thread)
738   "Insert the unique message headers in the buffer."
739   ;; Insert the unique message headers in the buffer.
740   (let ((wl-score-index (nth 2 (assoc header wl-score-header-index)))
741         (all-scores scores)
742         entries alist messages
743         new news)
744     (when (integerp wl-score-index)
745       (setq wl-scores-messages
746             (wl-score-string-sort wl-scores-messages wl-score-index)))
747     (setq messages wl-scores-messages)
748
749     (wl-score-insert-header (if thread "references" "from") messages)
750
751     ;; Find matches.
752     (while scores
753       (setq alist (car scores)
754             scores (cdr scores)
755             entries (assoc header alist))
756       (while (cdr entries)              ;First entry is the header index.
757         (let* ((rest (cdr entries))
758                (kill (car rest))
759                (match (nth 0 kill))
760                (type (or (nth 3 kill) 's))
761                (score (or (nth 1 kill) wl-score-interactive-default-score))
762                (date (nth 2 kill))
763                (found nil)
764                (mt (aref (symbol-name type) 0))
765                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
766                (dmt (downcase mt))
767                (search-func
768                 (cond ((= dmt ?r) 're-search-forward)
769                       ((memq dmt '(?e ?s ?f)) 'search-forward)
770                       (t (error "Invalid match type: %s" type))))
771                arts art day)
772           (goto-char (point-min))
773           (while (funcall search-func match nil t)
774             (when (or (not (= dmt ?e))
775                       (and (eolp)
776                            (= (progn (beginning-of-line) (point))
777                               (match-beginning 0))))
778 ;;;           (end-of-line)
779               (setq found (setq arts (wl-score-get-alike)))
780               ;; Found a match, update scores.
781               (while (setq art (pop arts))
782                 (setq day nil)
783                 (when (or (not wl-score-make-followup)
784                           (and wl-score-update-entry-dates
785                                expire
786                                (< expire
787                                   (setq day
788                                         (wl-day-number
789                                          (elmo-msgdb-overview-entity-get-date
790                                           (car art)))))))
791                   (when (setq new (wl-score-add-followups
792                                    (car art) score all-scores alist thread
793                                    day))
794                     (when thread
795                       (unless wl-score-stop-add-entry
796                         (wl-append rest (list new)))
797                       (setcdr art (+ score (cdr art))))
798                     (wl-push new news))))
799               (forward-line 1)))
800           ;; Update expire date
801           (cond ((null date))           ;Permanent entry.
802                 ((and found wl-score-update-entry-dates) ;Match, update date.
803                  (wl-score-set 'touched '(t) alist)
804                  (setcar (nthcdr 2 kill) now))
805                 ((and expire (< date expire)) ;Old entry, remove.
806                  (wl-score-set 'touched '(t) alist)
807                  (setcdr entries (cdr rest))
808                  (setq rest entries)))
809           (setq entries rest))))
810     (when (and news (not thread))
811       (list (cons "references" news)))))
812
813 (defun wl-score-add-followups (header score scores alist &optional thread day)
814   (let* ((id (car header))
815          (scores (car scores))
816          entry dont)
817     (when id
818       ;; Don't enter a score if there already is one.
819       (while (setq entry (pop scores))
820         (and (member (car entry) '("thread" "references"))
821              (memq (nth 3 (cadr entry)) '(s nil))
822              (assoc id entry)
823              (setq dont t)))
824       (unless dont
825         (let ((entry (list id score
826                            (or day (wl-day-number (current-time-string))) 's)))
827           (unless (or thread wl-score-stop-add-entry)
828             (wl-score-update-score-entry "references" entry alist))
829           (wl-score-set 'touched '(t) alist)
830           entry)))))
831
832 (defun wl-score-flush-cache ()
833   "Flush the cache of score files."
834   (interactive)
835   (wl-score-save)
836   (setq wl-score-cache nil
837         wl-score-alist nil)
838   (message "The score cache is now flushed"))
839
840 (defun wl-score-set-mark-below (score)
841   "Automatically mark messages with score below SCORE as read."
842   (interactive
843    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
844              (string-to-int (read-string "Mark below: ")))))
845   (setq score (or score wl-summary-default-score 0))
846   (wl-score-set 'mark (list score))
847   (wl-score-set 'touched '(t))
848   (setq wl-summary-mark-below score)
849   (wl-summary-score-update-all-lines t))
850
851 (defun wl-score-set-expunge-below (score)
852   "Automatically expunge messages with score below SCORE."
853   (interactive
854    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
855              (string-to-int (read-string "Expunge below: ")))))
856   (setq score (or score wl-summary-default-score 0))
857   (wl-score-set 'expunge (list score))
858   (wl-score-set 'touched '(t)))
859
860 (defun wl-score-change-score-file (file)
861   "Change current score alist."
862   (interactive
863    (list (read-file-name "Change to score file: " wl-score-files-directory)))
864   (wl-score-load-file file))
865
866 (defun wl-score-default (level)
867   (if level (prefix-numeric-value level)
868     wl-score-interactive-default-score))
869
870 (defun wl-summary-lower-score (&optional score)
871   (interactive "P")
872   (wl-summary-increase-score score t))
873
874 (defun wl-summary-increase-score (&optional score lower)
875   (interactive "P")
876   (if (wl-summary-message-number)
877   (let* ((rscore (if lower
878                      (- (wl-score-default score))
879                    (wl-score-default score)))
880          (increase (> rscore 0))
881          lscore entry list match type)
882     (setq entry (wl-score-get-header-entry nil rscore))
883     (setq list (nth 1 entry))
884     (setq match (car list))
885     (setq type (nth 3 list))
886     (cond ((memq type '(r R s S nil))
887            (when (and match (string= (car entry) "subject"))
888              (setq match (wl-score-simplify-subject match))))
889           ((memq type '(f F))
890            (setq match (wl-score-simplify-string-fuzzy match))))
891     (setq match (read-string
892                  (format "Match on %s, %s: "
893                          (car entry)
894                          (if increase "raise" "lower"))
895                  (if (numberp match)
896                      (int-to-string match)
897                    match)))
898     ;; transform from string to int.
899     (when (eq (nth 1 (assoc (car entry) wl-score-header-index))
900               'wl-score-integer)
901       (setq match (string-to-int match)))
902     ;; set score
903     (if score
904         (setq lscore rscore)
905       (setq lscore (nth 1 list))
906       (setq lscore
907             (abs (if lscore
908                      lscore
909                    wl-score-interactive-default-score)))
910       (setq lscore (if lower (- lscore) lscore)))
911     (setcar (cdr list)
912             (if (eq lscore wl-score-interactive-default-score)
913                 nil
914               lscore))
915     ;; update score file
916     (setcar list match)
917     (unless (eq (nth 2 list) 'now)
918       (let ((alist (if wl-current-score-file
919                        (cdr (assoc wl-current-score-file wl-score-cache))
920                      wl-score-alist)))
921         (wl-score-update-score-entry (car entry) list alist)
922         (wl-score-set 'touched '(t) alist)))
923     (wl-summary-score-effect (car entry) list (eq (nth 2 list) 'now)))))
924
925 (defun wl-score-get-latest-msgs ()
926   (let* ((now (wl-day-number (current-time-string)))
927          (expire (and wl-score-expiry-days
928                       (- now wl-score-expiry-days)))
929          (roverview (reverse (elmo-msgdb-get-overview
930                               (wl-summary-buffer-msgdb))))
931          msgs)
932     (if (not expire)
933         (mapcar 'car (elmo-msgdb-get-number-alist
934                       (wl-summary-buffer-msgdb))) ;; all messages
935       (catch 'break
936         (while roverview
937           (if (< (wl-day-number
938                   (elmo-msgdb-overview-entity-get-date (car roverview)))
939                  expire)
940               (throw 'break t))
941           (wl-push (elmo-msgdb-overview-entity-get-number (car roverview))
942                 msgs)
943           (setq roverview (cdr roverview))))
944       msgs)))
945
946 (defsubst wl-score-get-overview ()
947   (let ((num (wl-summary-message-number)))
948     (if num
949         (assoc (cdr (assq num (elmo-msgdb-get-number-alist
950                                (wl-summary-buffer-msgdb))))
951                (elmo-msgdb-get-overview (wl-summary-buffer-msgdb))))))
952
953 (defun wl-score-get-header (header &optional extra)
954   (let ((index (nth 2 (assoc header wl-score-header-index)))
955         (decode (nth 3 (assoc header wl-score-header-index))))
956     (if index
957         (wl-score-ov-entity-get (wl-score-get-overview) index extra decode))))
958
959 (defun wl-score-kill-help-buffer ()
960   (when (get-buffer "*Score Help*")
961     (kill-buffer "*Score Help*")
962     (when wl-score-help-winconf
963       (set-window-configuration wl-score-help-winconf))))
964
965 (defun wl-score-insert-help (string alist idx)
966   (setq wl-score-help-winconf (current-window-configuration))
967   (let ((cur-win (selected-window))
968         mes-win)
969     (save-excursion
970       (set-buffer (get-buffer-create "*Score Help*"))
971       (buffer-disable-undo (current-buffer))
972       (delete-windows-on (current-buffer))
973       (erase-buffer)
974       (insert string ":\n\n")
975       (let ((max -1)
976             (list alist)
977             (i 0)
978             n width pad format)
979         ;; find the longest string to display
980         (while list
981           (setq n (length (nth idx (car list))))
982           (unless (> max n)
983             (setq max n))
984           (setq list (cdr list)))
985         (setq max (+ max 4))            ; %c, `:', SPACE, a SPACE at end
986         (setq n (/ (1- (window-width)) max)) ; items per line
987         (setq width (/ (1- (window-width)) n)) ; width of each item
988         ;; insert `n' items, each in a field of width `width'
989         (while alist
990           (unless (< i n)
991             (setq i 0)
992             (delete-char -1)            ; the `\n' takes a char
993             (insert "\n"))
994           (setq pad (- width 3))
995           (setq format (concat "%c: %-" (int-to-string pad) "s"))
996           (insert (format format (caar alist) (nth idx (car alist))))
997           (setq alist (cdr alist))
998           (setq i (1+ i)))
999         (set-buffer-modified-p nil)))
1000     (when (and wl-message-buffer
1001                (get-buffer wl-message-buffer)
1002                (setq mes-win (get-buffer-window
1003                               (get-buffer wl-message-buffer))))
1004       (select-window mes-win)
1005       (unless (eq (next-window) cur-win)
1006         (delete-window (next-window))))
1007     (split-window)
1008     (pop-to-buffer "*Score Help*")
1009     (let ((window-min-height 1))
1010       (shrink-window-if-larger-than-buffer))
1011     (select-window cur-win)))
1012
1013 (defun wl-score-get-header-entry (&optional match-func increase)
1014   (let (hchar tchar pchar
1015         header score perm type extra hentry entry)
1016     (unwind-protect
1017         (progn
1018           ;; read the header to score.
1019           (while (not hchar)
1020             (message "%s header (%s?): "
1021                      (if increase
1022                          (if (> increase 0) "Increase" "Lower")
1023                        "Set")
1024                      (mapconcat (lambda (s) (char-to-string (car s)))
1025                                 wl-score-edit-header-char ""))
1026             (setq hchar (read-char))
1027             (when (or (= hchar ??) (= hchar ?\C-h))
1028               (setq hchar nil)
1029               (wl-score-insert-help "Match on header"
1030                                     wl-score-edit-header-char 1)))
1031           (wl-score-kill-help-buffer)
1032           (unless (setq hentry (assq (downcase hchar)
1033                                      wl-score-edit-header-char))
1034             (error "Invalid header type"))
1035
1036           (message "")
1037           (setq entry (assoc (setq header (nth 1 hentry))
1038                              wl-score-header-default-entry))
1039           (setq score (nth 1 entry)
1040                 perm (nth 2 entry)
1041                 type (nth 3 entry))
1042
1043           ;; read extra header.
1044           (when (equal header "extra")
1045             (setq extra
1046                   (completing-read
1047                    "Set extra header: "
1048                    (mapcar 'list
1049                            elmo-msgdb-extra-fields))))
1050
1051           ;; read the type.
1052           (unless type
1053             (let ((valid-types
1054                    (delq nil
1055                          (mapcar (lambda (s)
1056                                    (if (eq (nth 3 hentry)
1057                                            (nth 3 s))
1058                                        s nil))
1059                                  (copy-sequence
1060                                   wl-score-edit-type-char)))))
1061               (while (not tchar)
1062                 (message "Set header '%s' with match type (%s?): "
1063                          header
1064                          (mapconcat (lambda (s) (char-to-string (car s)))
1065                                     valid-types ""))
1066                 (setq tchar (read-char))
1067                 (when (or (= tchar ??) (= tchar ?\C-h))
1068                   (setq tchar nil)
1069                   (wl-score-insert-help "Match type" valid-types 2)))
1070               (wl-score-kill-help-buffer)
1071               (unless (setq type (nth 1 (assq (downcase tchar) valid-types)))
1072                 (error "Invalid match type"))
1073               (message "")))
1074
1075           ;; read the permanence.
1076           (unless perm
1077             (while (not pchar)
1078               (message "Set permanence (%s?): "
1079                        (mapconcat (lambda (s) (char-to-string (car s)))
1080                                   wl-score-edit-perm-char ""))
1081               (setq pchar (read-char))
1082               (when (or (= pchar ??) (= pchar ?\C-h))
1083                 (setq pchar nil)
1084                 (wl-score-insert-help "Match permanence"
1085                                       wl-score-edit-perm-char 2)))
1086             (wl-score-kill-help-buffer)
1087             (unless (setq perm (nth 1 (assq (downcase pchar)
1088                                             wl-score-edit-perm-char)))
1089               (error "Invalid match duration"))
1090             (message ""))
1091
1092           ;; read the score.
1093           (unless (or score increase)
1094             (setq score (string-to-int (read-string "Set score: ")))))
1095       (message "")
1096       (wl-score-kill-help-buffer))
1097
1098     (let* ((match-header (or (nth 2 hentry) header))
1099            (match (if match-func
1100                       (funcall match-func match-header extra)
1101                     (wl-score-get-header match-header extra)))
1102            (match (cond ((memq type '(r R regexp Regexp))
1103                          (regexp-quote match))
1104                         ((eq (nth 1 (assoc (car entry) wl-score-header-index))
1105                              'wl-score-integer)
1106                          match)
1107                         (t
1108                          (or match ""))))
1109            (perm (cond ((eq perm 'perm)
1110                         nil)
1111                        ((eq perm 'temp)
1112                         (wl-day-number (current-time-string)))
1113                        ((eq perm 'now)
1114                         perm)))
1115            (new (list match score perm type extra)))
1116       (list header new))))
1117
1118 (defun wl-score-update-score-entries (header entries &optional alist)
1119   (while entries
1120     (wl-score-update-score-entry header (car entries) alist)
1121     (setq entries (cdr entries)))
1122   (wl-score-set 'touched '(t) alist))
1123
1124 (defun wl-score-update-score-entry (header new &optional alist)
1125   (let ((old (wl-score-get header alist))
1126         (match (nth 0 new))
1127         elem)
1128     (if (and old
1129              (setq elem (assoc match old))
1130              (eq (nth 3 elem) (nth 3 new))
1131              (or (and (numberp (nth 2 elem)) (numberp (nth 2 new)))
1132                  (and (not (nth 2 elem)) (not (nth 2 new)))))
1133         (setcar (cdr elem) (+ (or (nth 1 elem)
1134                                   wl-score-interactive-default-score)
1135                               (or (nth 1 new)
1136                                   wl-score-interactive-default-score)))
1137       (wl-score-set header (if old (cons new old) (list new)) alist t))))
1138
1139 ;; functions for summary mode
1140
1141 (defun wl-summary-score-effect (header entry &optional now)
1142   (let ((scores (list (list (list header entry)))))
1143     (setq wl-summary-scored nil)
1144     (cond ((string= header "followup")
1145            (if wl-score-auto-make-followup-entry
1146                (let ((wl-score-make-followup t))
1147                  (wl-score-headers scores nil (wl-score-get-latest-msgs)))
1148              (wl-score-headers scores nil
1149                                (if (eq wl-summary-buffer-view 'thread)
1150                                    (wl-thread-get-children-msgs
1151                                     (wl-summary-message-number))
1152                                  (list (wl-summary-message-number)))))
1153            (unless now
1154              (wl-score-update-score-entries
1155               "references"
1156               (cdr (assoc "references" (car scores))))))
1157           ((string= header "thread")
1158            (wl-score-headers scores nil
1159                              (if (eq wl-summary-buffer-view 'thread)
1160                                  (wl-thread-get-children-msgs
1161                                   (wl-summary-message-number))
1162                                (list (wl-summary-message-number))))
1163            (unless now
1164              (wl-score-update-score-entries header
1165                                             ;; remove parent
1166                                             (cdr (cdaar scores)))))
1167           (t
1168            (wl-score-headers scores nil
1169                              (list (wl-summary-message-number)))))
1170     (wl-summary-score-update-all-lines t)))
1171
1172 (defun wl-summary-rescore-msgs (number-alist)
1173   (mapcar
1174    'car
1175    (nthcdr
1176     (max (- (length number-alist)
1177             wl-summary-rescore-partial-threshold)
1178          0)
1179     number-alist)))
1180
1181 (defun wl-summary-rescore (&optional arg)
1182   "Redo the entire scoring process in the current summary."
1183   (interactive "P")
1184   (let (number-alist expunged)
1185     (wl-score-save)
1186     (setq wl-score-cache nil)
1187     (setq wl-summary-scored nil)
1188     (setq number-alist (elmo-msgdb-get-number-alist (wl-summary-buffer-msgdb)))
1189     (wl-summary-score-headers nil (wl-summary-buffer-msgdb)
1190                               (unless arg
1191                                 (wl-summary-rescore-msgs number-alist)))
1192     (setq expunged (wl-summary-score-update-all-lines t))
1193     (if expunged
1194         (message "%d message(s) are expunged by scoring." (length expunged)))
1195     (set-buffer-modified-p nil)))
1196
1197 ;; optional argument force-msgs is added by teranisi.
1198 (defun wl-summary-score-headers (&optional folder msgdb force-msgs not-add)
1199   "Do scoring if scoring is required."
1200   (let ((scores (wl-score-get-score-alist
1201                  (or folder (wl-summary-buffer-folder-name)))))
1202     (when scores
1203       (wl-score-headers scores msgdb force-msgs not-add))))
1204
1205 (defun wl-summary-score-update-all-lines (&optional update)
1206   (let* ((alist wl-summary-scored)
1207          (count (length alist))
1208          (i 0)
1209          (update-unread nil)
1210          wl-summary-unread-message-hook
1211          num score dels visible score-mark mark-alist)
1212     (save-excursion
1213       (message "Updating score...")
1214       (while alist
1215         (setq num (caar alist)
1216               score (cdar alist))
1217         (when wl-score-debug
1218           (message "Scored %d with %d" score num)
1219           (wl-push (list (elmo-string (wl-summary-buffer-folder-name)) num score)
1220                 wl-score-trace))
1221         (setq score-mark (wl-summary-get-score-mark num))
1222         (and (setq visible (wl-summary-jump-to-msg num))
1223              (wl-summary-set-score-mark score-mark))
1224         (cond ((and wl-summary-expunge-below
1225                     (< score wl-summary-expunge-below))
1226                (wl-push num dels))
1227               ((< score wl-summary-mark-below)
1228                (if visible
1229                    (wl-summary-mark-as-read num); opened
1230                  (setq update-unread t)
1231                  (wl-summary-mark-as-read num))) ; closed
1232               ((and wl-summary-important-above
1233                     (> score wl-summary-important-above))
1234                (if (wl-thread-jump-to-msg num);; force open
1235                    (wl-summary-mark-as-important num " ")))
1236               ((and wl-summary-target-above
1237                     (> score wl-summary-target-above))
1238                (if visible
1239                    (wl-summary-mark-line "*"))
1240                (setq wl-summary-buffer-target-mark-list
1241                      (cons num wl-summary-buffer-target-mark-list))))
1242         (setq alist (cdr alist))
1243         (when (> count elmo-display-progress-threshold)
1244           (setq i (1+ i))
1245           (elmo-display-progress
1246            'wl-summary-score-update-all-lines "Updating score..."
1247            (/ (* i 100) count))))
1248       (when dels
1249         (let ((marks dels))
1250           (while marks
1251             (elmo-msgdb-set-mark (wl-summary-buffer-msgdb)
1252                                  (pop marks) nil)))
1253         (elmo-folder-mark-as-read wl-summary-buffer-elmo-folder
1254                                   dels)
1255         (wl-summary-delete-messages-on-buffer dels))
1256       (when (and update update-unread)
1257         (let ((num-db (elmo-msgdb-get-number-alist
1258                        (wl-summary-buffer-msgdb)))
1259               (mark-alist (elmo-msgdb-get-mark-alist
1260                            (wl-summary-buffer-msgdb))))
1261           ;; Update Folder mode
1262           (wl-folder-set-folder-updated (wl-summary-buffer-folder-name)
1263                                         (list 
1264                                          0
1265                                          (let ((pair
1266                                                 (wl-summary-count-unread)))
1267                                            (+ (car pair) (cdr pair)))
1268                                          (length num-db)))
1269           (wl-summary-update-modeline)))
1270       (message "Updating score...done")
1271       dels)))
1272
1273 (defun wl-score-edit-done ()
1274   (let ((bufnam (buffer-file-name (current-buffer)))
1275         (winconf wl-prev-winconf))
1276     (when winconf
1277       (set-window-configuration winconf))
1278     (wl-score-remove-from-cache bufnam)
1279     (wl-score-load-file bufnam)))
1280
1281 (defun wl-score-edit-current-scores (file)
1282   "Edit the current score alist."
1283   (interactive (list wl-current-score-file))
1284   (if file
1285       (wl-score-edit-file file)
1286     (call-interactively 'wl-score-edit-file)))
1287
1288 (defun wl-score-edit-file (file)
1289   "Edit a score FILE."
1290   (interactive
1291    (list (read-file-name "Edit score file: " wl-score-files-directory)))
1292   (when (wl-collect-summary)
1293     (wl-score-save))
1294   (let ((winconf (current-window-configuration))
1295         (edit-buffer (wl-as-mime-charset wl-score-mode-mime-charset
1296                        (find-file-noselect file)))
1297         (sum-buf (current-buffer)))
1298     (if (string-match (concat "^" wl-summary-buffer-name) (buffer-name))
1299         (let ((cur-buf (current-buffer)))
1300           (when wl-message-buffer
1301             (wl-message-select-buffer wl-message-buffer)
1302             (delete-window)
1303             (select-window (get-buffer-window cur-buf)))
1304           (wl-message-select-buffer edit-buffer))
1305       (switch-to-buffer edit-buffer))
1306     (wl-score-mode)
1307     (setq wl-score-edit-exit-function 'wl-score-edit-done)
1308     (setq wl-score-edit-summary-buffer sum-buf)
1309     (make-local-variable 'wl-prev-winconf)
1310     (setq wl-prev-winconf winconf))
1311   (message
1312    (substitute-command-keys
1313     "\\<wl-score-mode-map>\\[wl-score-edit-exit] to save edits")))
1314
1315 ;; score-mode
1316
1317 (defvar wl-score-edit-summary-buffer nil)
1318
1319 (defvar wl-score-mode-syntax-table
1320   (let ((table (copy-syntax-table lisp-mode-syntax-table)))
1321     (modify-syntax-entry ?| "w" table)
1322     table)
1323   "Syntax table used in score-mode buffers.")
1324
1325 (defvar wl-score-mode-map nil)
1326 (defvar wl-score-mode-menu-spec
1327   '("Score"
1328     ["Exit" wl-score-edit-exit t]
1329     ["Insert date" wl-score-edit-insert-date t]
1330     ["Format" wl-score-pretty-print t]))
1331
1332 (unless wl-score-mode-map
1333   (setq wl-score-mode-map (copy-keymap emacs-lisp-mode-map))
1334   (define-key wl-score-mode-map "\C-c\C-k" 'wl-score-edit-kill)
1335   (define-key wl-score-mode-map "\C-c\C-c" 'wl-score-edit-exit)
1336   (define-key wl-score-mode-map "\C-c\C-p" 'wl-score-pretty-print)
1337   (define-key wl-score-mode-map "\C-c\C-d" 'wl-score-edit-insert-date)
1338   (define-key wl-score-mode-map "\C-c\C-s" 'wl-score-edit-insert-header)
1339   (define-key wl-score-mode-map "\C-c\C-e" 'wl-score-edit-insert-header-entry)
1340
1341   (unless (boundp 'wl-score-menu)
1342     (easy-menu-define
1343      wl-score-menu wl-score-mode-map "Menu used in score mode."
1344      wl-score-mode-menu-spec)))
1345
1346 (defun wl-score-mode ()
1347   "Mode for editing Wanderlust score files.
1348 This mode is an extended emacs-lisp mode.
1349
1350 Special commands;
1351 \\{wl-score-mode-map}
1352 Entering Score mode calls the value of `wl-score-mode-hook'."
1353   (interactive)
1354   (kill-all-local-variables)
1355   (use-local-map wl-score-mode-map)
1356   (set-syntax-table wl-score-mode-syntax-table)
1357   (setq major-mode 'wl-score-mode)
1358   (setq mode-name "Score")
1359   (lisp-mode-variables nil)
1360   (make-local-variable 'wl-score-edit-exit-function)
1361   (make-local-variable 'wl-score-edit-summary-buffer)
1362   (run-hooks 'emacs-lisp-mode-hook 'wl-score-mode-hook))
1363
1364 (defun wl-score-edit-insert-date ()
1365   "Insert date in numerical format."
1366   (interactive)
1367   (princ (wl-day-number (current-time-string)) (current-buffer)))
1368
1369 (defun wl-score-pretty-print ()
1370   "Format the current score file."
1371   (interactive)
1372   (goto-char (point-min))
1373   (let ((form (read (current-buffer))))
1374     (erase-buffer)
1375     (let ((emacs-lisp-mode-syntax-table wl-score-mode-syntax-table)
1376           print-length print-level)
1377       (pp form (current-buffer))))
1378   (goto-char (point-min)))
1379
1380 (defun wl-score-edit-exit ()
1381   "Stop editing the score file."
1382   (interactive)
1383   (unless (file-exists-p (file-name-directory (buffer-file-name)))
1384     (elmo-make-directory (file-name-directory (buffer-file-name))))
1385   (if (zerop (buffer-size))
1386       (progn
1387         (set-buffer-modified-p nil)
1388         (and (file-exists-p (buffer-file-name))
1389              (delete-file (buffer-file-name))))
1390     (wl-as-mime-charset wl-score-mode-mime-charset
1391       (save-buffer)))
1392   (let ((buf (current-buffer)))
1393     (when wl-score-edit-exit-function
1394       (funcall wl-score-edit-exit-function))
1395     (kill-buffer buf)))
1396
1397 (defun wl-score-edit-kill ()
1398   "Cancel editing the score file."
1399   (interactive)
1400   (let ((buf (current-buffer)))
1401     (set-buffer-modified-p nil)
1402     (when wl-score-edit-exit-function
1403       (funcall wl-score-edit-exit-function))
1404     (kill-buffer buf)))
1405
1406 (defun wl-score-edit-get-summary-buf ()
1407   (let ((summary-buf (and wl-score-edit-summary-buffer
1408                           (get-buffer wl-score-edit-summary-buffer))))
1409     (if (and summary-buf
1410              (buffer-live-p summary-buf))
1411         summary-buf
1412       (if (and (setq summary-buf (window-buffer (previous-window)))
1413                (string-match (concat "^" wl-summary-buffer-name)
1414                              (buffer-name summary-buf)))
1415           summary-buf))))
1416
1417 (defun wl-score-edit-get-header (header &optional extra)
1418   (let ((sum-buf (wl-score-edit-get-summary-buf))
1419         (index (nth 2 (assoc header wl-score-header-index))))
1420     (when (and sum-buf index)
1421       (save-excursion
1422         (set-buffer sum-buf)
1423         (wl-score-get-header header extra)))))
1424
1425 (defun wl-score-edit-insert-number ()
1426   (interactive)
1427   (let ((sum-buf (wl-score-edit-get-summary-buf))
1428         num)
1429     (when sum-buf
1430       (if (setq num (save-excursion
1431                       (set-buffer sum-buf)
1432                       (wl-summary-message-number)))
1433           (prin1 num (current-buffer))))))
1434
1435 (defun wl-score-edit-insert-header ()
1436   (interactive)
1437   (let (hchar entry)
1438     (unwind-protect
1439         (progn
1440           (while (not hchar)
1441             (message "Insert header (%s?): "
1442                      (mapconcat (lambda (s) (char-to-string (car s)))
1443                                 wl-score-edit-header-char ""))
1444             (setq hchar (read-char))
1445             (when (or (= hchar ??) (= hchar ?\C-h))
1446               (setq hchar nil)
1447               (wl-score-insert-help "Match on header"
1448                                     wl-score-edit-header-char 1)))
1449           (wl-score-kill-help-buffer)
1450           (unless (setq entry (assq (downcase hchar)
1451                                     wl-score-edit-header-char))
1452             (error "Invalid match type")))
1453       (message "")
1454       (wl-score-kill-help-buffer)
1455       (let* ((header (nth 1 entry))
1456              (value (wl-score-edit-get-header header)))
1457         (and value (prin1 value (current-buffer)))))))
1458
1459 (defun wl-score-edit-insert-header-entry ()
1460   (interactive)
1461   (let (form entry)
1462     (goto-char (point-min))
1463     (setq form (and (not (zerop (buffer-size)))
1464                     (condition-case ()
1465                         (read (current-buffer))
1466                       (error "Invalid syntax"))))
1467     (setq entry (wl-score-get-header-entry 'wl-score-edit-get-header))
1468     (unless (eq (nth 2 (nth 1 entry)) 'now)
1469       (if form
1470           (wl-score-update-score-entry (car entry) (nth 1 entry) form)
1471         (setq form (list entry)))
1472       (erase-buffer)
1473       (let ((emacs-lisp-mode-syntax-table wl-score-mode-syntax-table)
1474             print-length print-level)
1475         (pp form (current-buffer)))
1476       (goto-char (point-min)))))
1477
1478 (require 'product)
1479 (product-provide (provide 'wl-score) (require 'wl-version))
1480
1481 ;;; wl-score.el ends here