28ead359c3165ca664b873b5183a0f190cde806f
[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   ;; Insert the unique message headers in the buffer.
715   (let ((wl-score-index (nth 2 (assoc header wl-score-header-index)))
716         (all-scores scores)
717         entries alist messages
718         new news)
719     (when (integerp wl-score-index)
720       (setq wl-scores-messages
721             (wl-score-string-sort wl-scores-messages wl-score-index)))
722     (setq messages wl-scores-messages)
723
724     (wl-score-insert-header (if thread "references" "from") messages)
725
726     ;; Find matches.
727     (while scores
728       (setq alist (car scores)
729             scores (cdr scores)
730             entries (assoc header alist))
731       (while (cdr entries)              ;First entry is the header index.
732         (let* ((rest (cdr entries))
733                (kill (car rest))
734                (match (nth 0 kill))
735                (type (or (nth 3 kill) 's))
736                (score (or (nth 1 kill) wl-score-interactive-default-score))
737                (date (nth 2 kill))
738                (found nil)
739                (mt (aref (symbol-name type) 0))
740                (case-fold-search (not (memq mt '(?R ?S ?E ?F))))
741                (dmt (downcase mt))
742                (search-func
743                 (cond ((= dmt ?r) 're-search-forward)
744                       ((memq dmt '(?e ?s ?f)) 'search-forward)
745                       (t (error "Invalid match type: %s" type))))
746                arts art day)
747           (goto-char (point-min))
748           (while (funcall search-func match nil t)
749             (when (or (not (= dmt ?e))
750                       (and (eolp)
751                            (= (progn (beginning-of-line) (point))
752                               (match-beginning 0))))
753 ;;;           (end-of-line)
754               (setq found (setq arts (wl-score-get-alike)))
755               ;; Found a match, update scores.
756               (while (setq art (pop arts))
757                 (setq day nil)
758                 (when (or (not wl-score-make-followup)
759                           (and wl-score-update-entry-dates
760                                expire
761                                (< expire
762                                   (setq day
763                                         (elmo-time-to-days
764                                          (elmo-message-entity-field
765                                           (car art) 'date))))))
766                   (when (setq new (wl-score-add-followups
767                                    (car art) score all-scores alist thread
768                                    day))
769                     (when thread
770                       (unless wl-score-stop-add-entry
771                         (wl-append rest (list new)))
772                       (setcdr art (+ score (cdr art))))
773                     (wl-push new news))))
774               (forward-line 1)))
775           ;; Update expire date
776           (cond ((null date))           ;Permanent entry.
777                 ((and found wl-score-update-entry-dates) ;Match, update date.
778                  (wl-score-set 'touched '(t) alist)
779                  (setcar (nthcdr 2 kill) now))
780                 ((and expire (< date expire)) ;Old entry, remove.
781                  (wl-score-set 'touched '(t) alist)
782                  (setcdr entries (cdr rest))
783                  (setq rest entries)))
784           (setq entries rest))))
785     (when (and news (not thread))
786       (list (cons "references" news)))))
787
788 (defun wl-score-add-followups (header score scores alist &optional thread day)
789   (let* ((id (elmo-message-entity-field header 'message-id))
790          (scores (car scores))
791          entry dont)
792     (when id
793       ;; Don't enter a score if there already is one.
794       (while (setq entry (pop scores))
795         (and (member (car entry) '("thread" "references"))
796              (memq (nth 3 (cadr entry)) '(s nil))
797              (assoc id entry)
798              (setq dont t)))
799       (unless dont
800         (let ((entry (list id score
801                            (or day (elmo-time-to-days (current-time))) 's)))
802           (unless (or thread wl-score-stop-add-entry)
803             (wl-score-update-score-entry "references" entry alist))
804           (wl-score-set 'touched '(t) alist)
805           entry)))))
806
807 (defun wl-score-flush-cache ()
808   "Flush the cache of score files."
809   (interactive)
810   (wl-score-save)
811   (setq wl-score-cache nil
812         wl-score-alist nil)
813   (message "The score cache is now flushed"))
814
815 (defun wl-score-set-mark-below (score)
816   "Automatically mark messages with score below SCORE as read."
817   (interactive
818    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
819              (string-to-number (read-string "Mark below: ")))))
820   (setq score (or score wl-summary-default-score 0))
821   (wl-score-set 'mark (list score))
822   (wl-score-set 'touched '(t))
823   (setq wl-summary-mark-below score)
824   (wl-summary-score-update-all-lines t))
825
826 (defun wl-score-set-expunge-below (score)
827   "Automatically expunge messages with score below SCORE."
828   (interactive
829    (list (or (and current-prefix-arg (prefix-numeric-value current-prefix-arg))
830              (string-to-number (read-string "Expunge below: ")))))
831   (setq score (or score wl-summary-default-score 0))
832   (wl-score-set 'expunge (list score))
833   (wl-score-set 'touched '(t)))
834
835 (defun wl-score-change-score-file (file)
836   "Change current score alist."
837   (interactive
838    (list (read-file-name "Change to score file: " wl-score-files-directory)))
839   (wl-score-load-file file))
840
841 (defun wl-score-default (level)
842   (if level (prefix-numeric-value level)
843     wl-score-interactive-default-score))
844
845 (defun wl-summary-lower-score (&optional score)
846   (interactive "P")
847   (wl-summary-increase-score score t))
848
849 (defun wl-summary-increase-score (&optional score lower)
850   (interactive "P")
851   (if (wl-summary-message-number)
852   (let* ((rscore (if lower
853                      (- (wl-score-default score))
854                    (wl-score-default score)))
855          (increase (> rscore 0))
856          lscore entry list match type)
857     (setq entry (wl-score-get-header-entry nil rscore))
858     (setq list (nth 1 entry))
859     (setq match (car list))
860     (setq type (nth 3 list))
861     (cond ((memq type '(r R s S nil))
862            (when (and match (string= (car entry) "subject"))
863              (setq match (wl-score-simplify-subject match))))
864           ((memq type '(f F))
865            (setq match (wl-score-simplify-string-fuzzy match))))
866     (setq match (read-string
867                  (format "Match on %s, %s: "
868                          (car entry)
869                          (if increase "raise" "lower"))
870                  (if (numberp match)
871                      (number-to-string match)
872                    match)))
873     ;; transform from string to int.
874     (when (eq (nth 1 (assoc (car entry) wl-score-header-index))
875               'wl-score-integer)
876       (setq match (string-to-number match)))
877     ;; set score
878     (if score
879         (setq lscore rscore)
880       (setq lscore (nth 1 list))
881       (setq lscore
882             (abs (if lscore
883                      lscore
884                    wl-score-interactive-default-score)))
885       (setq lscore (if lower (- lscore) lscore)))
886     (setcar (cdr list)
887             (if (eq lscore wl-score-interactive-default-score)
888                 nil
889               lscore))
890     ;; update score file
891     (setcar list match)
892     (unless (eq (nth 2 list) 'now)
893       (let ((alist (if wl-current-score-file
894                        (cdr (assoc wl-current-score-file wl-score-cache))
895                      wl-score-alist)))
896         (wl-score-update-score-entry (car entry) list alist)
897         (wl-score-set 'touched '(t) alist)))
898     (wl-summary-score-effect (car entry) list (eq (nth 2 list) 'now)))))
899
900 (defun wl-score-get-latest-msgs ()
901   (let* ((now (elmo-time-to-days (current-time)))
902          (expire (and wl-score-expiry-days
903                       (- now wl-score-expiry-days)))
904          (rnumbers (reverse wl-summary-buffer-number-list))
905          msgs)
906     (if (not expire)
907         (elmo-folder-list-messages wl-summary-buffer-elmo-folder
908                                    nil t)
909       (catch 'break
910         (while rnumbers
911           (if (< (elmo-time-to-days
912                   (elmo-message-entity-field wl-summary-buffer-elmo-folder
913                                              (car rnumbers)
914                                              'date))
915                  expire)
916               (throw 'break t))
917           (wl-push (car rnumbers) msgs)
918           (setq rnumbers (cdr rnumbers))))
919       msgs)))
920
921 (defun wl-score-get-header (header &optional extra)
922   (let ((index (nth 2 (assoc header wl-score-header-index)))
923         (decode (nth 3 (assoc header wl-score-header-index))))
924     (if index
925         (wl-score-ov-entity-get
926          (elmo-message-entity wl-summary-buffer-elmo-folder
927                               (wl-summary-message-number))
928          index extra))))
929
930 (defun wl-score-kill-help-buffer ()
931   (when (get-buffer "*Score Help*")
932     (kill-buffer "*Score Help*")
933     (when wl-score-help-winconf
934       (set-window-configuration wl-score-help-winconf))))
935
936 (defun wl-score-insert-help (string alist idx)
937   (setq wl-score-help-winconf (current-window-configuration))
938   (let ((cur-win (selected-window))
939         mes-win)
940     (with-current-buffer (get-buffer-create "*Score Help*")
941       (buffer-disable-undo (current-buffer))
942       (delete-windows-on (current-buffer))
943       (erase-buffer)
944       (insert string ":\n\n")
945       (let ((max -1)
946             (list alist)
947             (i 0)
948             n width pad format)
949         ;; find the longest string to display
950         (while list
951           (setq n (length (nth idx (car list))))
952           (unless (> max n)
953             (setq max n))
954           (setq list (cdr list)))
955         (setq max (+ max 4))            ; %c, `:', SPACE, a SPACE at end
956         (setq n (/ (1- (window-width)) max)) ; items per line
957         (setq width (/ (1- (window-width)) n)) ; width of each item
958         ;; insert `n' items, each in a field of width `width'
959         (while alist
960           (unless (< i n)
961             (setq i 0)
962             (delete-char -1)            ; the `\n' takes a char
963             (insert "\n"))
964           (setq pad (- width 3))
965           (setq format (concat "%c: %-" (number-to-string pad) "s"))
966           (insert (format format (caar alist) (nth idx (car alist))))
967           (setq alist (cdr alist))
968           (setq i (1+ i)))
969         (set-buffer-modified-p nil)))
970     (when (and wl-message-buffer
971                (get-buffer wl-message-buffer)
972                (setq mes-win (get-buffer-window
973                               (get-buffer wl-message-buffer))))
974       (select-window mes-win)
975       (unless (eq (next-window) cur-win)
976         (delete-window (next-window))))
977     (split-window)
978     (pop-to-buffer "*Score Help*")
979     (let ((window-min-height 1))
980       (shrink-window-if-larger-than-buffer))
981     (select-window cur-win)))
982
983 (defun wl-score-get-header-entry (&optional match-func increase)
984   (let (hchar tchar pchar
985         header score perm type extra hentry entry)
986     (unwind-protect
987         (progn
988           ;; read the header to score.
989           (while (not hchar)
990             (message "%s header (%s?): "
991                      (if increase
992                          (if (> increase 0) "Increase" "Lower")
993                        "Set")
994                      (mapconcat (lambda (s) (char-to-string (car s)))
995                                 wl-score-edit-header-char ""))
996             (setq hchar (read-char))
997             (when (or (= hchar ??) (= hchar ?\C-h))
998               (setq hchar nil)
999               (wl-score-insert-help "Match on header"
1000                                     wl-score-edit-header-char 1)))
1001           (wl-score-kill-help-buffer)
1002           (unless (setq hentry (assq (downcase hchar)
1003                                      wl-score-edit-header-char))
1004             (error "Invalid header type"))
1005
1006           (message "")
1007           (setq entry (assoc (setq header (nth 1 hentry))
1008                              wl-score-header-default-entry))
1009           (setq score (nth 1 entry)
1010                 perm (nth 2 entry)
1011                 type (nth 3 entry))
1012
1013           ;; read extra header.
1014           (when (equal header "extra")
1015             (setq extra
1016                   (completing-read
1017                    "Set extra header: "
1018                    (mapcar 'list
1019                            elmo-msgdb-extra-fields))))
1020
1021           ;; read the type.
1022           (unless type
1023             (let ((valid-types
1024                    (delq nil
1025                          (mapcar (lambda (s)
1026                                    (if (eq (nth 3 hentry)
1027                                            (nth 3 s))
1028                                        s nil))
1029                                  (copy-sequence
1030                                   wl-score-edit-type-char)))))
1031               (while (not tchar)
1032                 (message "Set header '%s' with match type (%s?): "
1033                          header
1034                          (mapconcat (lambda (s) (char-to-string (car s)))
1035                                     valid-types ""))
1036                 (setq tchar (read-char))
1037                 (when (or (= tchar ??) (= tchar ?\C-h))
1038                   (setq tchar nil)
1039                   (wl-score-insert-help "Match type" valid-types 2)))
1040               (wl-score-kill-help-buffer)
1041               (unless (setq type (nth 1 (assq (downcase tchar) valid-types)))
1042                 (error "Invalid match type"))
1043               (message "")))
1044
1045           ;; read the permanence.
1046           (unless perm
1047             (while (not pchar)
1048               (message "Set permanence (%s?): "
1049                        (mapconcat (lambda (s) (char-to-string (car s)))
1050                                   wl-score-edit-perm-char ""))
1051               (setq pchar (read-char))
1052               (when (or (= pchar ??) (= pchar ?\C-h))
1053                 (setq pchar nil)
1054                 (wl-score-insert-help "Match permanence"
1055                                       wl-score-edit-perm-char 2)))
1056             (wl-score-kill-help-buffer)
1057             (unless (setq perm (nth 1 (assq (downcase pchar)
1058                                             wl-score-edit-perm-char)))
1059               (error "Invalid match duration"))
1060             (message ""))
1061
1062           ;; read the score.
1063           (unless (or score increase)
1064             (setq score (string-to-number (read-string "Set score: ")))))
1065       (message "")
1066       (wl-score-kill-help-buffer))
1067
1068     (let* ((match-header (or (nth 2 hentry) header))
1069            (match (if match-func
1070                       (funcall match-func match-header extra)
1071                     (wl-score-get-header match-header extra)))
1072            (match (cond ((memq type '(r R regexp Regexp))
1073                          (regexp-quote match))
1074                         ((eq (nth 1 (assoc (car entry) wl-score-header-index))
1075                              'wl-score-integer)
1076                          match)
1077                         (t
1078                          (or match ""))))
1079            (perm (cond ((eq perm 'perm)
1080                         nil)
1081                        ((eq perm 'temp)
1082                         (elmo-time-to-days (current-time)))
1083                        ((eq perm 'now)
1084                         perm)))
1085            (new (list match score perm type extra)))
1086       (list header new))))
1087
1088 (defun wl-score-update-score-entries (header entries &optional alist)
1089   (while entries
1090     (wl-score-update-score-entry header (car entries) alist)
1091     (setq entries (cdr entries)))
1092   (wl-score-set 'touched '(t) alist))
1093
1094 (defun wl-score-update-score-entry (header new &optional alist)
1095   (let ((old (wl-score-get header alist))
1096         (match (nth 0 new))
1097         elem)
1098     (if (and old
1099              (setq elem (assoc match old))
1100              (eq (nth 3 elem) (nth 3 new))
1101              (or (and (numberp (nth 2 elem)) (numberp (nth 2 new)))
1102                  (and (not (nth 2 elem)) (not (nth 2 new)))))
1103         (setcar (cdr elem) (+ (or (nth 1 elem)
1104                                   wl-score-interactive-default-score)
1105                               (or (nth 1 new)
1106                                   wl-score-interactive-default-score)))
1107       (wl-score-set header (if old (cons new old) (list new)) alist t))))
1108
1109 ;; functions for summary mode
1110
1111 (defun wl-summary-score-effect (header entry &optional now)
1112   (let ((scores (list (list (list header entry)))))
1113     (setq wl-summary-scored nil)
1114     (cond ((string= header "followup")
1115            (if wl-score-auto-make-followup-entry
1116                (let ((wl-score-make-followup t))
1117                  (wl-score-headers scores (wl-score-get-latest-msgs)))
1118              (wl-score-headers scores
1119                                (if (eq wl-summary-buffer-view 'thread)
1120                                    (wl-thread-get-children-msgs
1121                                     (wl-summary-message-number))
1122                                  (list (wl-summary-message-number)))))
1123            (unless now
1124              (wl-score-update-score-entries
1125               "references"
1126               (cdr (assoc "references" (car scores))))))
1127           ((string= header "thread")
1128            (wl-score-headers scores
1129                              (if (eq wl-summary-buffer-view 'thread)
1130                                  (wl-thread-get-children-msgs
1131                                   (wl-summary-message-number))
1132                                (list (wl-summary-message-number))))
1133            (unless now
1134              (wl-score-update-score-entries header
1135                                             ;; remove parent
1136                                             (cdr (cdaar scores)))))
1137           (t
1138            (wl-score-headers scores
1139                              (list (wl-summary-message-number)))))
1140     (wl-summary-score-update-all-lines t)))
1141
1142 (defun wl-summary-rescore-msgs (numbers)
1143   (nthcdr
1144    (max (- (length numbers)
1145            wl-summary-rescore-partial-threshold)
1146         0)
1147    numbers))
1148
1149 (defun wl-summary-rescore (&optional arg)
1150   "Redo the entire scoring process in the current summary."
1151   (interactive "P")
1152   (let (number-alist expunged)
1153     (wl-score-save)
1154     (setq wl-score-cache nil)
1155     (setq wl-summary-scored nil)
1156     (wl-summary-score-headers (unless arg
1157                                 (wl-summary-rescore-msgs
1158                                  (elmo-folder-list-messages
1159                                   wl-summary-buffer-elmo-folder t t))))
1160     (setq expunged (wl-summary-score-update-all-lines t))
1161     (if expunged
1162         (message "%d message(s) are expunged by scoring." (length expunged)))
1163     (set-buffer-modified-p nil)))
1164
1165 ;; optional argument force-msgs is added by teranisi.
1166 (defun wl-summary-score-headers (&optional force-msgs not-add)
1167   "Do scoring if scoring is required."
1168   (let ((scores (wl-score-get-score-alist)))
1169     (when scores
1170       (wl-score-headers scores force-msgs not-add))))
1171
1172 (defun wl-summary-score-update-all-lines (&optional update)
1173   (let ((alist wl-summary-scored)
1174         (update-unread nil)
1175         wl-summary-unread-message-hook
1176         num score dels visible score-mark mark-alist)
1177     (save-excursion
1178       (elmo-with-progress-display (wl-update-score (length alist))
1179           "Updating score"
1180         (while alist
1181           (setq num (caar alist)
1182                 score (cdar alist))
1183           (when wl-score-debug
1184             (message "Scored %d with %d" score num)
1185             (wl-push (list (elmo-string (wl-summary-buffer-folder-name)) num score)
1186                      wl-score-trace))
1187           (setq score-mark (wl-summary-get-score-mark num))
1188           (and (setq visible (wl-summary-jump-to-msg num))
1189                (wl-summary-set-score-mark score-mark))
1190           (cond ((and wl-summary-expunge-below
1191                       (< score wl-summary-expunge-below))
1192                  (wl-push num dels))
1193                 ((< score wl-summary-mark-below)
1194                  (if visible
1195                      (wl-summary-mark-as-read num); opened
1196                    (setq update-unread t)
1197                    (wl-summary-mark-as-read num))) ; closed
1198                 ((and wl-summary-important-above
1199                       (> score wl-summary-important-above))
1200                  (if (wl-thread-jump-to-msg num);; force open
1201                      (wl-summary-set-persistent-mark 'important num)))
1202                 ((and wl-summary-target-above
1203                       (> score wl-summary-target-above))
1204                  (if visible
1205                      (wl-summary-set-mark "*"))))
1206           (setq alist (cdr alist))
1207           (elmo-progress-notify 'wl-update-score))
1208         (when dels
1209           (dolist (del dels)
1210             (elmo-message-unset-flag wl-summary-buffer-elmo-folder
1211                                      del 'unread))
1212           (elmo-folder-kill-messages wl-summary-buffer-elmo-folder dels)
1213           (wl-summary-delete-messages-on-buffer dels))
1214         (when (and update update-unread)
1215           ;; Update Folder mode
1216           (wl-folder-set-folder-updated (wl-summary-buffer-folder-name)
1217                                         (list
1218                                          0
1219                                          (let ((flag-count
1220                                                 (wl-summary-count-unread)))
1221                                            (or (cdr (assq 'unread flag-count))
1222                                                0))
1223                                          (elmo-folder-length
1224                                           wl-summary-buffer-elmo-folder)))
1225           (wl-summary-update-modeline)))
1226       dels)))
1227
1228 (defun wl-score-edit-done ()
1229   (let ((bufnam (buffer-file-name (current-buffer)))
1230         (winconf wl-prev-winconf))
1231     (when winconf
1232       (set-window-configuration winconf))
1233     (wl-score-remove-from-cache bufnam)
1234     (wl-score-load-file bufnam)))
1235
1236 (defun wl-score-edit-current-scores (file)
1237   "Edit the current score alist."
1238   (interactive (list wl-current-score-file))
1239   (if file
1240       (wl-score-edit-file file)
1241     (call-interactively 'wl-score-edit-file)))
1242
1243 (defun wl-score-edit-file (file)
1244   "Edit a score FILE."
1245   (interactive
1246    (list (read-file-name "Edit score file: " wl-score-files-directory)))
1247   (when (wl-collect-summary)
1248     (wl-score-save))
1249   (let ((winconf (current-window-configuration))
1250         (edit-buffer (wl-as-mime-charset wl-score-mode-mime-charset
1251                        (find-file-noselect file)))
1252         (sum-buf (current-buffer)))
1253     (if (string-match (concat "^" wl-summary-buffer-name) (buffer-name))
1254         (let ((cur-buf (current-buffer)))
1255           (when wl-message-buffer
1256             (wl-message-select-buffer wl-message-buffer)
1257             (delete-window)
1258             (select-window (get-buffer-window cur-buf)))
1259           (wl-message-select-buffer edit-buffer))
1260       (switch-to-buffer edit-buffer))
1261     (wl-score-mode)
1262     (setq wl-score-edit-exit-function 'wl-score-edit-done)
1263     (setq wl-score-edit-summary-buffer sum-buf)
1264     (make-local-variable 'wl-prev-winconf)
1265     (setq wl-prev-winconf winconf))
1266   (message
1267    (substitute-command-keys
1268     "\\<wl-score-mode-map>\\[wl-score-edit-exit] to save edits")))
1269
1270 ;; score-mode
1271
1272 (defvar wl-score-edit-summary-buffer nil)
1273
1274 (defvar wl-score-mode-syntax-table
1275   (let ((table (copy-syntax-table lisp-mode-syntax-table)))
1276     (modify-syntax-entry ?| "w" table)
1277     table)
1278   "Syntax table used in score-mode buffers.")
1279
1280 (defvar wl-score-mode-map nil)
1281 (defvar wl-score-mode-menu-spec
1282   '("Score"
1283     ["Exit" wl-score-edit-exit t]
1284     ["Insert date" wl-score-edit-insert-date t]
1285     ["Format" wl-score-pretty-print t]))
1286
1287 (unless wl-score-mode-map
1288   (setq wl-score-mode-map (copy-keymap emacs-lisp-mode-map))
1289   (define-key wl-score-mode-map "\C-c\C-k" 'wl-score-edit-kill)
1290   (define-key wl-score-mode-map "\C-c\C-c" 'wl-score-edit-exit)
1291   (define-key wl-score-mode-map "\C-c\C-p" 'wl-score-pretty-print)
1292   (define-key wl-score-mode-map "\C-c\C-d" 'wl-score-edit-insert-date)
1293   (define-key wl-score-mode-map "\C-c\C-s" 'wl-score-edit-insert-header)
1294   (define-key wl-score-mode-map "\C-c\C-e" 'wl-score-edit-insert-header-entry)
1295
1296   (unless (boundp 'wl-score-menu)
1297     (easy-menu-define
1298      wl-score-menu wl-score-mode-map "Menu used in score mode."
1299      wl-score-mode-menu-spec)))
1300
1301 (defun wl-score-mode ()
1302   "Mode for editing Wanderlust score files.
1303 This mode is an extended emacs-lisp mode.
1304
1305 Special commands;
1306 \\{wl-score-mode-map}
1307 Entering Score mode calls the value of `wl-score-mode-hook'."
1308   (interactive)
1309   (kill-all-local-variables)
1310   (use-local-map wl-score-mode-map)
1311   (set-syntax-table wl-score-mode-syntax-table)
1312   (setq major-mode 'wl-score-mode)
1313   (setq mode-name "Score")
1314   (lisp-mode-variables nil)
1315   (make-local-variable 'wl-score-edit-exit-function)
1316   (make-local-variable 'wl-score-edit-summary-buffer)
1317   (run-hooks 'emacs-lisp-mode-hook 'wl-score-mode-hook))
1318
1319 (defun wl-score-edit-insert-date ()
1320   "Insert date in numerical format."
1321   (interactive)
1322   (princ (elmo-time-to-days (current-time)) (current-buffer)))
1323
1324 (defun wl-score-pretty-print ()
1325   "Format the current score file."
1326   (interactive)
1327   (goto-char (point-min))
1328   (let ((form (read (current-buffer))))
1329     (erase-buffer)
1330     (let ((emacs-lisp-mode-syntax-table wl-score-mode-syntax-table)
1331           print-length print-level)
1332       (pp form (current-buffer))))
1333   (goto-char (point-min)))
1334
1335 (defun wl-score-edit-exit ()
1336   "Stop editing the score file."
1337   (interactive)
1338   (unless (file-exists-p (file-name-directory (buffer-file-name)))
1339     (elmo-make-directory (file-name-directory (buffer-file-name))))
1340   (if (zerop (buffer-size))
1341       (progn
1342         (set-buffer-modified-p nil)
1343         (and (file-exists-p (buffer-file-name))
1344              (delete-file (buffer-file-name))))
1345     (wl-as-mime-charset wl-score-mode-mime-charset
1346       (save-buffer)))
1347   (let ((buf (current-buffer)))
1348     (when wl-score-edit-exit-function
1349       (funcall wl-score-edit-exit-function))
1350     (kill-buffer buf)))
1351
1352 (defun wl-score-edit-kill ()
1353   "Cancel editing the score file."
1354   (interactive)
1355   (let ((buf (current-buffer)))
1356     (set-buffer-modified-p nil)
1357     (when wl-score-edit-exit-function
1358       (funcall wl-score-edit-exit-function))
1359     (kill-buffer buf)))
1360
1361 (defun wl-score-edit-get-summary-buf ()
1362   (let ((summary-buf (and wl-score-edit-summary-buffer
1363                           (get-buffer wl-score-edit-summary-buffer))))
1364     (if (and summary-buf
1365              (buffer-live-p summary-buf))
1366         summary-buf
1367       (if (and (setq summary-buf (window-buffer (previous-window)))
1368                (string-match (concat "^" wl-summary-buffer-name)
1369                              (buffer-name summary-buf)))
1370           summary-buf))))
1371
1372 (defun wl-score-edit-get-header (header &optional extra)
1373   (let ((sum-buf (wl-score-edit-get-summary-buf))
1374         (index (nth 2 (assoc header wl-score-header-index))))
1375     (when (and sum-buf index)
1376       (with-current-buffer sum-buf
1377         (wl-score-get-header header extra)))))
1378
1379 (defun wl-score-edit-insert-number ()
1380   (interactive)
1381   (let ((sum-buf (wl-score-edit-get-summary-buf))
1382         num)
1383     (when sum-buf
1384       (if (setq num (with-current-buffer sum-buf
1385                       (wl-summary-message-number)))
1386           (prin1 num (current-buffer))))))
1387
1388 (defun wl-score-edit-insert-header ()
1389   (interactive)
1390   (let (hchar entry)
1391     (unwind-protect
1392         (progn
1393           (while (not hchar)
1394             (message "Insert header (%s?): "
1395                      (mapconcat (lambda (s) (char-to-string (car s)))
1396                                 wl-score-edit-header-char ""))
1397             (setq hchar (read-char))
1398             (when (or (= hchar ??) (= hchar ?\C-h))
1399               (setq hchar nil)
1400               (wl-score-insert-help "Match on header"
1401                                     wl-score-edit-header-char 1)))
1402           (wl-score-kill-help-buffer)
1403           (unless (setq entry (assq (downcase hchar)
1404                                     wl-score-edit-header-char))
1405             (error "Invalid match type")))
1406       (message "")
1407       (wl-score-kill-help-buffer)
1408       (let* ((header (nth 1 entry))
1409              (value (wl-score-edit-get-header header)))
1410         (and value (prin1 value (current-buffer)))))))
1411
1412 (defun wl-score-edit-insert-header-entry ()
1413   (interactive)
1414   (let (form entry)
1415     (goto-char (point-min))
1416     (setq form (and (not (zerop (buffer-size)))
1417                     (condition-case ()
1418                         (read (current-buffer))
1419                       (error "Invalid syntax"))))
1420     (setq entry (wl-score-get-header-entry 'wl-score-edit-get-header))
1421     (unless (eq (nth 2 (nth 1 entry)) 'now)
1422       (if form
1423           (wl-score-update-score-entry (car entry) (nth 1 entry) form)
1424         (setq form (list entry)))
1425       (erase-buffer)
1426       (let ((emacs-lisp-mode-syntax-table wl-score-mode-syntax-table)
1427             print-length print-level)
1428         (pp form (current-buffer)))
1429       (goto-char (point-min)))))
1430
1431 (require 'product)
1432 (product-provide (provide 'wl-score) (require 'wl-version))
1433
1434 ;;; wl-score.el ends here