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