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