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