f22b6912eb6ac9c6cfc410c3164a98a48ab655e4
[elisp/wanderlust.git] / wl / wl-draft.el
1 ;;; wl-draft.el --- Message draft mode for Wanderlust.
2
3 ;; Copyright (C) 1998,1999,2000 Yuuichi Teranishi <teranisi@gohome.org>
4 ;; Copyright (C) 1998,1999,2000 Masahiro MURATA <muse@ba2.so-net.ne.jp>
5
6 ;; Author: Yuuichi Teranishi <teranisi@gohome.org>
7 ;;      Masahiro MURATA <muse@ba2.so-net.ne.jp>
8 ;; Keywords: mail, net news
9
10 ;; This file is part of Wanderlust (Yet Another Message Interface on Emacsen).
11
12 ;; This program is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16 ;;
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21 ;;
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26 ;;
27
28 ;;; Commentary:
29 ;;
30
31 ;;; Code:
32 ;;
33
34 (require 'sendmail)
35 (require 'wl-template)
36 (require 'emu)
37 (condition-case nil (require 'timezone) (error nil))
38 (require 'std11)
39 (require 'wl-vars)
40
41 (defvar x-face-add-x-face-version-header)
42 (defvar mail-reply-buffer)
43 (defvar mail-from-style)
44
45 (eval-when-compile
46   (require 'static)
47   (require 'elmo-pop3)
48   (defalias-maybe 'x-face-insert 'ignore)
49   (defalias-maybe 'x-face-insert-version-header 'ignore)
50   (defalias-maybe 'wl-init 'ignore)
51   (defalias-maybe 'wl-draft-mode 'ignore))
52
53 (eval-and-compile
54   (autoload 'wl-addrmgr "wl-addrmgr"))
55
56 (autoload 'open-ssl-stream "ssl")
57
58 (defvar wl-draft-buffer-message-number nil)
59 (defvar wl-draft-field-completion-list nil)
60 (defvar wl-draft-verbose-send t)
61 (defvar wl-draft-verbose-msg nil)
62 (defvar wl-draft-queue-flushing nil)
63 (defvar wl-draft-config-variables nil)
64 (defvar wl-draft-config-exec-flag t)
65 (defvar wl-draft-buffer-cur-summary-buffer nil)
66 (defvar wl-draft-clone-local-variable-regexp "^\\(wl\\|mime\\)")
67 (defvar wl-draft-sendlog-filename "sendlog")
68 (defvar wl-draft-queue-save-filename "qinfo")
69 (defvar wl-draft-config-save-filename "config")
70 (defvar wl-draft-queue-flush-send-function 'wl-draft-dispatch-message)
71 (defvar wl-sent-message-via nil)
72 (defvar wl-sent-message-modified nil)
73 (defvar wl-sent-message-queued nil)
74 (defvar wl-draft-fcc-list nil)
75 (defvar wl-draft-reedit nil)
76 (defvar wl-draft-reply-buffer nil)
77 (defvar wl-draft-forward nil)
78 (defvar wl-draft-doing-mime-bcc nil)
79
80 (defvar wl-draft-parent-folder nil
81   "Folder name of the summary in which current draft is invoked.
82 This variable is local in each draft buffer.
83 You can refer its value in `wl-draft-config-alist'.
84
85 e.g.
86 \(setq wl-draft-config-alist
87       '(((string-match \".*@domain1$\" wl-draft-parent-folder)
88          (\"From\" . \"user@domain1\"))
89         ((string-match \".*@domain2$\" wl-draft-parent-folder)
90          (\"From\" . \"user@domain2\"))))")
91
92 (defvar wl-draft-parent-number nil)
93
94 (defconst wl-draft-reply-saved-variables
95   '(wl-draft-parent-folder
96     wl-draft-parent-number))
97
98 (defvar wl-draft-config-sub-func-alist
99   '((body               . wl-draft-config-sub-body)
100     (top                . wl-draft-config-sub-top)
101     (bottom             . wl-draft-config-sub-bottom)
102     (header             . wl-draft-config-sub-header)
103     (header-top         . wl-draft-config-sub-header-top)
104     (header-bottom      . wl-draft-config-sub-header)
105     (part-top           . wl-draft-config-sub-part-top)
106     (part-bottom        . wl-draft-config-sub-part-bottom)
107     (body-file          . wl-draft-config-sub-body-file)
108     (top-file           . wl-draft-config-sub-top-file)
109     (bottom-file        . wl-draft-config-sub-bottom-file)
110     (header-file        . wl-draft-config-sub-header-file)
111     (template           . wl-draft-config-sub-template)
112     (x-face             . wl-draft-config-sub-x-face)))
113
114 (make-variable-buffer-local 'wl-draft-buffer-message-number)
115 (make-variable-buffer-local 'wl-draft-buffer-cur-summary-buffer)
116 (make-variable-buffer-local 'wl-draft-config-variables)
117 (make-variable-buffer-local 'wl-draft-config-exec-flag)
118 (make-variable-buffer-local 'wl-sent-message-via)
119 (make-variable-buffer-local 'wl-sent-message-queued)
120 (make-variable-buffer-local 'wl-draft-fcc-list)
121 (make-variable-buffer-local 'wl-draft-reply-buffer)
122 (make-variable-buffer-local 'wl-draft-parent-folder)
123 (make-variable-buffer-local 'wl-draft-parent-number)
124
125 (defvar wl-draft-folder-internal nil
126   "Internal variable for caching `opened' draft folder.")
127
128 (defsubst wl-smtp-password-key (user mechanism server)
129   (format "SMTP:%s/%s@%s"
130           user mechanism server))
131
132 (defmacro wl-smtp-extension-bind (&rest body)
133   (` (let* ((smtp-sasl-mechanisms
134              (if wl-smtp-authenticate-type
135                  (mapcar 'upcase
136                          (if (listp wl-smtp-authenticate-type)
137                              wl-smtp-authenticate-type
138                            (list wl-smtp-authenticate-type)))))
139             (smtp-use-sasl (and smtp-sasl-mechanisms t))
140             (smtp-use-starttls (eq wl-smtp-connection-type 'starttls))
141             (smtp-open-connection-function
142              (if (eq wl-smtp-connection-type 'ssl)
143                  #'open-ssl-stream
144                smtp-open-connection-function))
145             (smtp-end-of-line
146              (if (eq wl-smtp-connection-type 'ssl)
147                  "\n"
148                smtp-end-of-line))
149             smtp-sasl-user-name smtp-sasl-properties sasl-read-passphrase)
150        (if (and (string= (car smtp-sasl-mechanisms) "DIGEST-MD5")
151                 ;; sendmail bug?
152                 (string-match "^\\([^@]*\\)@\\([^@]*\\)"
153                               wl-smtp-posting-user))
154            (setq smtp-sasl-user-name (match-string 1 wl-smtp-posting-user)
155                  smtp-sasl-properties (list 'realm
156                                             (match-string 2 wl-smtp-posting-user)))
157          (setq smtp-sasl-user-name wl-smtp-posting-user
158                smtp-sasl-properties nil))
159        (setq sasl-read-passphrase
160              (function
161               (lambda (prompt)
162                 (elmo-get-passwd
163                  (wl-smtp-password-key
164                   smtp-sasl-user-name
165                   (car smtp-sasl-mechanisms)
166                   smtp-server)))))
167        (,@ body))))
168
169 (defun wl-draft-insert-date-field ()
170   "Insert Date field."
171   (insert "Date: " (wl-make-date-string) "\n"))
172
173 (defun wl-draft-insert-from-field ()
174   "Insert From field."
175   ;; Put the "From:" field in unless for some odd reason
176   ;; they put one in themselves.
177   (let (from)
178     (condition-case err
179         (setq from (wl-draft-eword-encode-address-list wl-from))
180       (error (error "Please look at `wl-from' again")))
181     (insert "From: " from "\n")))
182
183 (defun wl-draft-insert-x-face-field ()
184   "Insert X-Face header."
185   (interactive)
186   (if (not (file-exists-p wl-x-face-file))
187       (error "File %s does not exist" wl-x-face-file)
188     (goto-char (point-min))
189     (search-forward mail-header-separator nil t)
190     (beginning-of-line)
191     (wl-draft-insert-x-face-field-here)
192     (run-hooks 'wl-draft-insert-x-face-field-hook))) ; highlight it if you want.
193
194 (defun wl-draft-insert-x-face-field-here ()
195   "Insert X-Face field at point."
196   (let ((x-face-string (elmo-get-file-string wl-x-face-file)))
197     (when (string-match "^\\(X-Face:\\)?[ \t\n]*" x-face-string)
198       (setq x-face-string (substring x-face-string (match-end 0))))
199     (insert "X-Face: " x-face-string))
200   (when (not (= (preceding-char) ?\n))  ; for chomped (choped) x-face-string
201     (insert ?\n))
202   ;; Insert X-Face-Version: field
203   (when (and (fboundp 'x-face-insert-version-header)
204              (boundp 'x-face-add-x-face-version-header)
205              x-face-add-x-face-version-header)
206     (x-face-insert-version-header)))
207
208 (defun wl-draft-setup ()
209   (let ((field wl-draft-fields)
210         cl)
211     (while field
212       (setq cl (append cl
213                        (list (cons (concat (car field) " ")
214                                    (concat (car field) " ")))))
215       (setq field (cdr field)))
216     (setq cl
217           (cons (cons (concat wl-draft-mime-bcc-field-name  ": ")
218                       (concat wl-draft-mime-bcc-field-name  ": "))
219                 cl))
220     (setq wl-draft-field-completion-list cl)
221     (setq wl-address-complete-header-regexp
222           (wl-regexp-opt
223            (append wl-address-complete-header-list
224                    (list (concat wl-draft-mime-bcc-field-name  ":")))))))
225
226 (defun wl-draft-make-mail-followup-to (recipients)
227   (let ((rlist (wl-address-delete-user-mail-addresses recipients)))
228     (if (elmo-list-member rlist (mapcar 'downcase
229                                         wl-subscribed-mailing-list))
230         rlist
231       (append rlist (list (wl-address-header-extract-address
232                            wl-from))))))
233
234 (defun wl-draft-delete-myself-from-cc (to cc)
235   (cond (wl-draft-always-delete-myself ; always-delete option
236          (wl-address-delete-user-mail-addresses cc))
237         ((elmo-list-member (append to cc) ; subscribed mailing-list
238                            (mapcar 'downcase wl-subscribed-mailing-list))
239          (wl-address-delete-user-mail-addresses cc))
240         (t cc)))
241
242 (defsubst wl-draft-strip-subject-regexp (subject regexp)
243   "Remove REGEXP from SUBJECT string."
244   (if (string-match regexp subject)
245       (substring subject (match-end 0))
246     subject))
247
248 (defun wl-draft-forward-make-subject (original-subject)
249   "Generate subject string for forwarding."
250   (if wl-forward-subject-prefix
251       (concat wl-forward-subject-prefix
252               (wl-draft-strip-subject-regexp
253                (or original-subject "")
254                wl-subject-forward-prefix-regexp))
255     original-subject))
256
257 (defun wl-draft-reply-make-subject (original-subject)
258   "Generate subject string for replying."
259   (if wl-reply-subject-prefix
260       (concat wl-reply-subject-prefix
261               (wl-draft-strip-subject-regexp
262                (or original-subject "")
263                wl-subject-re-prefix-regexp))
264     original-subject))
265
266 (defun wl-draft-forward (original-subject summary-buf)
267   (let (references parent-folder)
268     (with-current-buffer summary-buf
269       (setq parent-folder (wl-summary-buffer-folder-name)))
270     (with-current-buffer (wl-message-get-original-buffer)
271       (setq references (nconc
272                         (std11-field-bodies '("References" "In-Reply-To"))
273                         (list (std11-field-body "Message-Id"))))
274       (setq references (delq nil references)
275             references (mapconcat 'identity references " ")
276             references (wl-draft-parse-msg-id-list-string references)
277             references (wl-delete-duplicates references)
278             references (when references
279                          (mapconcat 'identity references "\n\t"))))
280     (and wl-draft-use-frame
281          (get-buffer-window summary-buf)
282          (select-window (get-buffer-window summary-buf)))
283     (wl-draft (list (cons 'To "")
284                     (cons 'Subject
285                           (wl-draft-forward-make-subject original-subject))
286                     (cons 'References references))
287               nil nil nil nil parent-folder))
288   (goto-char (point-max))
289   (wl-draft-insert-message)
290   (mail-position-on-field "To"))
291
292 (defun wl-draft-self-reply-p ()
293   "Return t when From address in the current message is user's self one or not."
294   (wl-address-user-mail-address-p (or (elmo-field-body "From") "")))
295
296 (defun wl-draft-reply (buf with-arg summary-buf &optional number)
297   "Reply to BUF buffer message.
298 Reply to author if WITH-ARG is non-nil."
299 ;;;(save-excursion
300   (let (r-list
301         to mail-followup-to cc subject in-reply-to references newsgroups
302         to-alist cc-alist decoder parent-folder)
303     (when (buffer-live-p summary-buf)
304       (with-current-buffer summary-buf
305         (setq parent-folder (wl-summary-buffer-folder-name))))
306     (set-buffer (or buf mime-mother-buffer))
307     (setq r-list (if with-arg wl-draft-reply-with-argument-list
308                    wl-draft-reply-without-argument-list))
309     (catch 'done
310       (while r-list
311         (when (let ((condition (car (car r-list))))
312                 (cond ((stringp condition)
313                        (std11-field-body condition))
314                       ((listp condition)
315                        (catch 'done
316                          (while condition
317                            (cond
318                             ((stringp (car condition))
319                              (or (std11-field-body (car condition))
320                                  (throw 'done nil)))
321                             ((symbolp (car condition))
322                              (or (funcall (car condition))
323                                  (throw 'done nil)))
324                             (t
325                              (debug)))
326                            (setq condition (cdr condition)))
327                          t))
328                       ((symbolp condition)
329                        (funcall condition))))
330           (let ((r-to-list (nth 0 (cdr (car r-list))))
331                 (r-cc-list (nth 1 (cdr (car r-list))))
332                 (r-ng-list (nth 2 (cdr (car r-list)))))
333             (when (and (member "Followup-To" r-ng-list)
334                        (string= (std11-field-body "Followup-To") "poster"))
335               (setq r-to-list (cons "From" r-to-list))
336               (setq r-ng-list (delete "Followup-To"
337                                       (copy-sequence r-ng-list))))
338             (if (and r-to-list (symbolp r-to-list))
339                 (setq to (wl-concat-list (funcall r-to-list) ","))
340               (setq to (wl-concat-list (cons to
341                                              (elmo-multiple-fields-body-list
342                                               r-to-list))
343                                        ",")))
344             (if (and r-cc-list (symbolp r-cc-list))
345                 (setq cc (wl-concat-list (funcall r-cc-list) ","))
346               (setq cc (wl-concat-list (cons cc
347                                              (elmo-multiple-fields-body-list
348                                               r-cc-list))
349                                        ",")))
350             (if (and r-ng-list (symbolp r-ng-list))
351                 (setq newsgroups (wl-concat-list (funcall r-ng-list) ","))
352               (setq newsgroups (wl-concat-list (cons newsgroups
353                                                      (std11-field-bodies
354                                                       r-ng-list))
355                                                ","))))
356           (throw 'done nil))
357         (setq r-list (cdr r-list)))
358       (error "No match field: check your `wl-draft-reply-%s-argument-list'"
359              (if with-arg "with" "without")))
360     (setq subject (std11-field-body "Subject"))
361     (setq to (wl-parse-addresses to)
362           cc (wl-parse-addresses cc))
363     (with-temp-buffer                   ; to keep raw buffer unibyte.
364       (set-buffer-multibyte default-enable-multibyte-characters)
365       (setq decoder (mime-find-field-decoder 'Subject 'plain))
366       (setq subject (if (and subject decoder)
367                         (funcall decoder subject) subject))
368       (setq to-alist
369             (mapcar
370              (lambda (addr)
371                (setq decoder (mime-find-field-decoder 'To 'plain))
372                (cons (nth 1 (std11-extract-address-components addr))
373                      (if decoder (funcall decoder addr) addr)))
374              to))
375       (setq cc-alist
376             (mapcar
377              (lambda (addr)
378                (setq decoder (mime-find-field-decoder 'Cc 'plain))
379                (cons (nth 1 (std11-extract-address-components addr))
380                      (if decoder (funcall decoder addr) addr)))
381              cc)))
382     (setq subject (wl-draft-reply-make-subject subject))
383     (setq in-reply-to (std11-field-body "Message-Id"))
384     (setq references (nconc
385                       (std11-field-bodies '("References" "In-Reply-To"))
386                       (list in-reply-to)))
387     (setq to (delq nil (mapcar 'car to-alist)))
388     (setq cc (delq nil (mapcar 'car cc-alist)))
389     ;; if subscribed mailing list is contained in cc or to
390     ;; and myself is contained in cc,
391     ;; delete myself from cc.
392     (setq cc (wl-draft-delete-myself-from-cc to cc))
393     (when wl-insert-mail-followup-to
394       (setq mail-followup-to
395             (wl-draft-make-mail-followup-to (append to cc)))
396       (setq mail-followup-to (wl-delete-duplicates mail-followup-to nil t)))
397     (with-temp-buffer                   ; to keep raw buffer unibyte.
398       (set-buffer-multibyte default-enable-multibyte-characters)
399       (setq newsgroups (wl-parse newsgroups
400                                  "[ \t\f\r\n,]*\\([^ \t\f\r\n,]+\\)")
401             newsgroups (wl-delete-duplicates newsgroups)
402             newsgroups
403             (if newsgroups
404                 (mapconcat
405                  (lambda (grp)
406                    (setq decoder (mime-find-field-decoder 'Newsgroups 'plain))
407                    (if decoder (funcall decoder grp) grp))
408                  newsgroups ","))))
409     (setq to (wl-delete-duplicates to nil t))
410     (setq cc (wl-delete-duplicates
411               (append (wl-delete-duplicates cc nil t)
412                       to (copy-sequence to))
413               t t))
414     (and to (setq to (mapconcat
415                       '(lambda (addr)
416                          (if wl-draft-reply-use-address-with-full-name
417                              (or (cdr (assoc addr to-alist)) addr)
418                            addr))
419                       to ",\n\t")))
420     (and cc (setq cc (mapconcat
421                       '(lambda (addr)
422                          (if wl-draft-reply-use-address-with-full-name
423                              (or (cdr (assoc addr cc-alist)) addr)
424                            addr))
425                       cc ",\n\t")))
426     (and mail-followup-to
427          (setq mail-followup-to
428                (mapconcat
429                 '(lambda (addr)
430                    (if wl-draft-reply-use-address-with-full-name
431                        (or (cdr (assoc addr (append to-alist cc-alist))) addr)
432                      addr))
433                 mail-followup-to ",\n\t")))
434     (and (null to) (setq to cc cc nil))
435     (setq references (delq nil references)
436           references (mapconcat 'identity references " ")
437           references (wl-draft-parse-msg-id-list-string references)
438           references (wl-delete-duplicates references)
439           references (if references
440                          (mapconcat 'identity references "\n\t")))
441     (and wl-draft-use-frame
442          (get-buffer-window summary-buf)
443          (select-window (get-buffer-window summary-buf)))
444     (wl-draft (list (cons 'To to)
445                     (cons 'Cc cc)
446                     (cons 'Newsgroups newsgroups)
447                     (cons 'Subject subject)
448                     (cons 'In-Reply-To in-reply-to)
449                     (cons 'References references)
450                     (cons 'Mail-Followup-To mail-followup-to))
451               nil nil nil nil parent-folder)
452     (setq wl-draft-parent-number number)
453     (setq wl-draft-reply-buffer buf)
454     (setq wl-draft-config-variables
455           (append wl-draft-reply-saved-variables
456                   wl-draft-config-variables)))
457   (run-hooks 'wl-reply-hook))
458
459 (defun wl-draft-reply-position (position)
460   (cond ((eq position 'body)
461          (wl-draft-body-goto-top))
462         ((eq position 'bottom)
463          (wl-draft-body-goto-bottom))
464         ((eq position 'top)
465          (goto-char (point-min)))
466         ((and (stringp position)
467               (std11-field-body position))
468          (progn (mail-position-on-field position)
469                 (wl-draft-beginning-of-line)))
470         ((listp position)
471          (while (car position)
472            (wl-draft-reply-position (car position))
473            (setq position (cdr position))))))
474
475 (defun wl-draft-add-references ()
476   (wl-draft-add-in-reply-to "References"))
477
478 (defun wl-draft-add-in-reply-to (&optional alt-field)
479   (let* ((mes-id (save-excursion
480                    (set-buffer mail-reply-buffer)
481                    (std11-field-body "message-id")))
482          (field (or alt-field "In-Reply-To"))
483          (ref (std11-field-body field))
484          (ref-list nil) (st nil))
485     (when (and mes-id ref)
486       (while (string-match "<[^>]+>" ref st)
487         (setq ref-list
488               (cons (substring ref (match-beginning 0) (setq st (match-end 0)))
489                     ref-list)))
490       (when (and ref-list
491                  (member mes-id ref-list))
492         (setq mes-id nil)))
493     (when mes-id
494       (save-excursion
495         (when (mail-position-on-field field)
496           (forward-line)
497           (while (looking-at "^[ \t]")
498             (forward-line))
499           (setq mes-id (concat "\t" mes-id "\n")))
500         (insert mes-id))
501       t)))
502
503 (defun wl-draft-yank-from-mail-reply-buffer (decode-it
504                                              &optional ignored-fields)
505   (interactive)
506   (save-restriction
507     (narrow-to-region (point)(point))
508     (insert
509      (string-as-multibyte
510       (with-current-buffer mail-reply-buffer
511         (when decode-it
512           (decode-mime-charset-region (point-min) (point-max)
513                                       wl-mime-charset))
514         (buffer-substring-no-properties
515          (point-min) (point-max)))))
516     (when ignored-fields
517       (goto-char (point-min))
518       (wl-draft-delete-fields ignored-fields))
519     (goto-char (point-max))
520     (push-mark (point) nil t)
521     (goto-char (point-min)))
522   (let ((beg (point)))
523     (cond (mail-citation-hook (run-hooks 'mail-citation-hook))
524           (mail-yank-hooks (run-hooks 'mail-yank-hooks))
525           (wl-draft-cite-function (funcall wl-draft-cite-function))) ; default cite
526     (run-hooks 'wl-draft-cited-hook)
527     (when (if wl-draft-add-references
528               (wl-draft-add-references)
529             (if wl-draft-add-in-reply-to
530                 (wl-draft-add-in-reply-to)))
531       (wl-highlight-headers 'for-draft)) ; highlight when added References:
532     (when wl-highlight-body-too
533       (wl-highlight-body-region beg (point-max)))))
534
535 (defun wl-message-news-p ()
536   "If exist valid Newsgroups field, return non-nil."
537   (std11-field-body "Newsgroups"))
538
539 (defun wl-message-field-exists-p (field)
540   "If FIELD exist and FIELD value is not empty, return non-nil."
541   (let ((value (std11-field-body field)))
542     (and value
543          (not (string= value "")))))
544
545 (defun wl-message-mail-p ()
546   "If exist To, Cc or Bcc field, return non-nil."
547   (or (wl-message-field-exists-p "To")
548       (wl-message-field-exists-p "Resent-to")
549       (wl-message-field-exists-p "Cc")
550       (wl-message-field-exists-p "Bcc")
551       (wl-message-field-exists-p wl-draft-mime-bcc-field-name)
552 ;;; This may be needed..
553 ;;;   (wl-message-field-exists-p "Fcc")
554       ))
555
556 (defun wl-draft-edit-string (string)
557   (let ((cur-buf (current-buffer))
558         (tmp-buf (get-buffer-create " *wl-draft-edit-string*"))
559         to subject in-reply-to cc references newsgroups mail-followup-to
560         content-type content-transfer-encoding from
561         body-beg)
562     (set-buffer tmp-buf)
563     (erase-buffer)
564     (insert string)
565     (setq to (std11-field-body "To"))
566     (setq to (and to
567                   (eword-decode-string
568                    (decode-mime-charset-string
569                     to
570                     wl-mime-charset))))
571     (setq subject (std11-field-body "Subject"))
572     (setq subject (and subject
573                        (eword-decode-string
574                         (decode-mime-charset-string
575                          subject
576                          wl-mime-charset))))
577     (setq from (std11-field-body "From")
578           from (and from
579                     (eword-decode-string
580                      (decode-mime-charset-string
581                       from
582                       wl-mime-charset))))
583     (setq in-reply-to (std11-field-body "In-Reply-To"))
584     (setq cc (std11-field-body "Cc"))
585     (setq cc (and cc
586                   (eword-decode-string
587                    (decode-mime-charset-string
588                     cc
589                     wl-mime-charset))))
590     (setq references (std11-field-body "References"))
591     (setq newsgroups (std11-field-body "Newsgroups"))
592     (setq mail-followup-to (std11-field-body "Mail-Followup-To"))
593     (setq content-type (std11-field-body "Content-Type"))
594     (setq content-transfer-encoding (std11-field-body "Content-Transfer-Encoding"))
595     (goto-char (point-min))
596     (or (re-search-forward "\n\n" nil t)
597         (search-forward (concat mail-header-separator "\n") nil t))
598     (unwind-protect
599         (set-buffer
600          (wl-draft (list
601                     (cons 'From
602                           (if (wl-address-user-mail-address-p from) from))
603                     (cons 'To to)
604                     (cons 'Cc cc)
605                     (cons 'Subject subject)
606                     (cons 'Newsgroups newsgroups)
607                     (cons 'Mail-Followup-To mail-followup-to)
608                     (cons 'In-Reply-To in-reply-to)
609                     (cons 'References references))
610                    content-type content-transfer-encoding
611                    (buffer-substring (point) (point-max))
612                    'edit-again))
613       (kill-buffer tmp-buf))
614     ;; Set cursor point to the top.
615     (goto-char (point-min))
616     (search-forward (concat mail-header-separator "\n") nil t)
617     (run-hooks 'wl-draft-reedit-hook)
618     (and to (mail-position-on-field "To"))))
619
620 (defun wl-draft-insert-current-message (dummy)
621   (interactive)
622   (let (original-buffer
623         mail-reply-buffer
624         mail-citation-hook mail-yank-hooks
625         wl-draft-add-references wl-draft-add-in-reply-to
626         wl-draft-cite-function)
627     (if (and wl-draft-buffer-cur-summary-buffer
628              (with-current-buffer wl-draft-buffer-cur-summary-buffer
629                (and wl-message-buffer
630                     (with-current-buffer wl-message-buffer
631                       (setq original-buffer (wl-message-get-original-buffer))
632                       (not (zerop (with-current-buffer original-buffer
633                                     (buffer-size))))))))
634         (progn
635           (setq mail-reply-buffer original-buffer)
636           (wl-draft-yank-from-mail-reply-buffer
637            nil
638            wl-ignored-forwarded-headers))
639       (when (string= (mime-make-tag "message" "rfc822")
640                      (buffer-substring-no-properties (point-at-bol 0)(point-at-eol 0)))
641         (delete-region (point-at-bol 0) (1+ (point-at-eol 0))))
642       (error "No current message"))))
643
644 (defun wl-draft-insert-get-message (dummy)
645   (let ((fld (completing-read
646               "Folder name: "
647               (if (memq 'read-folder wl-use-folder-petname)
648                   (wl-folder-get-entity-with-petname)
649                 wl-folder-entity-hashtb)
650               nil nil wl-default-spec
651               'wl-read-folder-history))
652         (number (call-interactively
653                  (function (lambda (num)
654                              (interactive "nNumber: ")
655                              num))))
656         (mail-reply-buffer (get-buffer-create "*wl-draft-insert-get-message*"))
657         mail-citation-hook mail-yank-hooks
658         wl-draft-cite-function)
659     (unwind-protect
660         (progn
661           (elmo-message-fetch (wl-folder-get-elmo-folder fld)
662                               number
663                               ;; No cache.
664                               (elmo-make-fetch-strategy 'entire)
665                               nil mail-reply-buffer)
666           (wl-draft-yank-from-mail-reply-buffer nil))
667       (kill-buffer mail-reply-buffer))))
668
669 ;;
670 ;; default body citation func
671 ;;
672 (defun wl-default-draft-cite ()
673   (let ((mail-yank-ignored-headers "[^:]+:")
674         (mail-yank-prefix "> ")
675         date from cite-title)
676     (save-restriction
677       (if (< (mark t) (point))
678           (exchange-point-and-mark))
679       (narrow-to-region (point)(point-max))
680       (setq date (std11-field-body "date")
681             from (std11-field-body "from")))
682     (when (or date from)
683       (insert (format "At %s,\n%s wrote:\n"
684                       (or date "some time ago")
685                       (if wl-default-draft-cite-decorate-author
686                           (funcall wl-summary-from-function
687                                    (or from "you"))
688                         (or from "you")))))
689     (mail-indent-citation)))
690
691 (defvar wl-draft-buffer nil "Draft buffer to yank content.")
692 (defun wl-draft-yank-to-draft-buffer (buffer)
693   "Yank BUFFER content to `wl-draft-buffer'."
694   (set-buffer wl-draft-buffer)
695   (let ((mail-reply-buffer buffer))
696     (wl-draft-yank-from-mail-reply-buffer nil)
697     (kill-buffer buffer)))
698
699 (defun wl-draft-yank-original (&optional arg)
700   "Yank original message."
701   (interactive "P")
702   (if arg
703       (let (buf mail-reply-buffer)
704         (elmo-set-work-buf
705          (insert "\n")
706          (yank)
707          (setq buf (current-buffer)))
708         (setq mail-reply-buffer buf)
709         (wl-draft-yank-from-mail-reply-buffer nil))
710     (wl-draft-yank-current-message-entity)))
711
712 (defun wl-draft-hide (editing-buffer)
713   "Hide the editing draft buffer if possible."
714   (when (and editing-buffer
715              (buffer-live-p editing-buffer)
716              (get-buffer-window editing-buffer))
717     (select-window (get-buffer-window editing-buffer))
718     (let ((sum-buf wl-draft-buffer-cur-summary-buffer)
719           fld-buf sum-win fld-win)
720       (if (and wl-draft-use-frame
721                (> (length (visible-frame-list)) 1))
722           ;; hide draft frame
723           (delete-frame)
724         ;; hide draft window
725         (or (one-window-p)
726             (delete-window))
727         ;; stay folder window if required
728         (when wl-stay-folder-window
729           (if (setq fld-buf (get-buffer wl-folder-buffer-name))
730               (if (setq fld-win (get-buffer-window fld-buf))
731                   (select-window fld-win)
732                 (if wl-draft-resume-folder-window ;; resume folder window
733                     (switch-to-buffer fld-buf)))))
734         (if (buffer-live-p sum-buf)
735             (if (setq sum-win (get-buffer-window sum-buf t))
736                 ;; if Summary is on the frame, select it.
737                 (select-window sum-win)
738               ;; if summary is not on the frame, switch to it.
739               (if (and wl-stay-folder-window
740                        (or wl-draft-resume-folder-window fld-win))
741                   (wl-folder-select-buffer sum-buf)
742                 (switch-to-buffer sum-buf))))))))
743
744 (defun wl-draft-delete (editing-buffer)
745   "Kill the editing draft buffer and delete the file corresponds to it."
746   (save-excursion
747     (when editing-buffer
748       (set-buffer editing-buffer)
749       (when wl-draft-buffer-message-number
750         (elmo-folder-delete-messages (wl-draft-get-folder)
751                                      (list
752                                       wl-draft-buffer-message-number))
753         (wl-draft-config-info-operation wl-draft-buffer-message-number
754                                         'delete))
755       (set-buffer-modified-p nil)               ; force kill
756       (kill-buffer editing-buffer))))
757
758 (defun wl-draft-kill (&optional force-kill)
759   "Kill current draft buffer and quit editing."
760   (interactive "P")
761   (save-excursion
762     (when (and (or (eq major-mode 'wl-draft-mode)
763                    (eq major-mode 'mail-mode))
764                (or force-kill
765                    (yes-or-no-p "Kill Current Draft? ")))
766       (let ((cur-buf (current-buffer)))
767         (when (and wl-draft-parent-number
768                    (not (string= wl-draft-parent-folder "")))
769           (let* ((number wl-draft-parent-number)
770                  (folder-name wl-draft-parent-folder)
771                  (folder (wl-folder-get-elmo-folder folder-name))
772                  buffer)
773             (if (and (setq buffer (wl-summary-get-buffer folder-name))
774                      (with-current-buffer buffer
775                        (string= (wl-summary-buffer-folder-name)
776                                 folder-name)))
777                 (with-current-buffer buffer
778                   (elmo-folder-unset-flag folder (list number) 'answered)
779                   (when (wl-summary-jump-to-msg number)
780                     (wl-summary-update-persistent-mark)))
781               (elmo-folder-open folder 'load-msgdb)
782               (elmo-folder-unset-flag folder (list number) 'answered)
783               (elmo-folder-close folder))))
784         (wl-draft-hide cur-buf)
785         (wl-draft-delete cur-buf)))
786     (message "")))
787
788 (defun wl-draft-fcc ()
789   "Add a new Fcc field, with file name completion."
790   (interactive)
791   (or (mail-position-on-field "fcc" t)  ;Put new field after exiting Fcc.
792       (mail-position-on-field "to"))
793   (insert "\nFcc: "))
794
795 ;; Imported from message.el.
796 (defun wl-draft-elide-region (b e)
797   "Elide the text in the region.
798 An ellipsis (from `wl-draft-elide-ellipsis') will be inserted where the
799 text was killed."
800   (interactive "r")
801   (kill-region b e)
802   (insert wl-draft-elide-ellipsis))
803
804 ;; Imported from message.el.
805 (defun wl-draft-beginning-of-line (&optional n)
806   "Move point to beginning of header value or to beginning of line."
807   (interactive "p")
808   (let ((zrs 'zmacs-region-stays))
809     (when (and (interactive-p) (boundp zrs))
810       (set zrs t)))
811   (if (wl-draft-point-in-header-p)
812       (let* ((here (point))
813              (bol (progn (beginning-of-line n) (point)))
814              (eol (line-end-position))
815              (eoh (and (looking-at "[^ \t]")
816                        (re-search-forward ": *" eol t))))
817         (if (and eoh (or (> here eoh) (= here bol)))
818             (goto-char eoh)
819           (goto-char bol)))
820     (beginning-of-line n)))
821
822 (defun wl-draft-point-in-header-p ()
823   "Return t if point is in the header."
824   (save-excursion
825     (let ((p (point)))
826       (goto-char (point-min))
827       (not (re-search-forward
828             (concat "^" (regexp-quote mail-header-separator) "\n")
829             p t)))))
830
831 ;; function for wl-sent-message-via
832
833 (defmacro wl-draft-sent-message-p (type)
834   (` (eq (nth 1 (assq (, type) wl-sent-message-via)) 'sent)))
835
836 (defmacro wl-draft-set-sent-message (type result &optional server-port)
837   (` (let ((element (assq (, type) wl-sent-message-via)))
838        (if element
839            (unless (eq (nth 1 element) (, result))
840              (setcdr element (list (, result) (, server-port)))
841              (setq wl-sent-message-modified t))
842          (push (list (, type) (, result) (, server-port)) wl-sent-message-via)
843          (setq wl-sent-message-modified t)))))
844
845 (defun wl-draft-sent-message-results ()
846   (let ((results wl-sent-message-via)
847         unplugged-via sent-via)
848     (while results
849       (cond ((eq (nth 1 (car results)) 'unplugged)
850              (push (caar results) unplugged-via))
851             ((eq (nth 1 (car results)) 'sent)
852              (push (caar results) sent-via)))
853       (setq results (cdr results)))
854     (list unplugged-via sent-via)))
855
856 (defun wl-draft-write-sendlog (status proto server to id)
857   "Write send log file, if `wl-draft-sendlog' is non-nil."
858   (when wl-draft-sendlog
859     (with-temp-buffer
860       (let* ((filename (expand-file-name wl-draft-sendlog-filename
861                                          elmo-msgdb-directory))
862              (filesize (nth 7 (file-attributes filename)))
863              (server (if server (concat " server=" server) ""))
864              (to (if to (cond
865                          ((memq proto '(fcc queue))
866                           (format " folder=\"%s\"" to))
867                          ((eq proto 'nntp)
868                           (format " ng=<%s>" to))
869                          (t
870                           (concat " to="
871                                   (mapconcat
872                                    'identity
873                                    (mapcar '(lambda(x) (format "<%s>" x)) to)
874                                    ","))))
875                    ""))
876              (id (if id (concat " id=" id) ""))
877              (time (format-time-string "%Y/%m/%d %T")))
878         (insert (format "%s proto=%s stat=%s%s%s%s\n"
879                         time proto status server to id))
880         (if (and wl-draft-sendlog-max-size filesize
881                  (> filesize wl-draft-sendlog-max-size))
882             (rename-file filename (concat filename ".old") t))
883         (if (file-writable-p filename)
884             (write-region-as-binary (point-min) (point-max)
885                                     filename t 'no-msg)
886           (message "%s is not writable." filename))))))
887
888 (defun wl-draft-get-header-delimiter (&optional delete)
889   ;; If DELETE is non-nil, replace the header delimiter with a blank line
890   (let (delimline)
891     (goto-char (point-min))
892     (when (re-search-forward
893            (concat "^" (regexp-quote mail-header-separator) "$\\|^$") nil t)
894       (replace-match "")
895       (if delete
896           (forward-char -1))
897       (setq delimline (point-marker)))
898     delimline))
899
900 (defun wl-draft-send-mail-with-qmail ()
901   "Pass the prepared message buffer to qmail-inject.
902 Refer to the documentation for the variable `send-mail-function'
903 to find out how to use this."
904   (if (and wl-draft-qmail-send-plugged
905            (not (elmo-plugged-p)))
906       (wl-draft-set-sent-message 'mail 'unplugged)
907     ;; send the message
908     (run-hooks 'wl-mail-send-pre-hook) ;; X-PGP-Sig, Cancel-Lock
909     (let ((id (std11-field-body "Message-ID"))
910           (to (std11-field-body "To")))
911       (case
912           (as-binary-process
913            (apply
914             'call-process-region 1 (point-max) wl-qmail-inject-program
915             nil nil nil
916             wl-qmail-inject-args))
917         ;; qmail-inject doesn't say anything on it's stdout/stderr,
918         ;; we have to look at the retval instead
919         (0   (progn
920                (wl-draft-set-sent-message 'mail 'sent)
921                (wl-draft-write-sendlog 'ok 'qmail nil (list to) id)))
922         (1   (error "`qmail-inject' reported permanent failure"))
923         (111 (error "`qmail-inject' reported transient failure"))
924         ;; should never happen
925         (t   (error "`qmail-inject' reported unknown failure"))))))
926
927 (defun wl-draft-parse-msg-id-list-string (string)
928   "Get msg-id list from STRING."
929   (let (msg-id-list)
930     (dolist (parsed-id (std11-parse-msg-ids-string string))
931       (when (eq (car parsed-id) 'msg-id)
932         (setq msg-id-list (cons (std11-msg-id-string parsed-id)
933                                 msg-id-list))))
934     (nreverse msg-id-list)))
935
936 (defun wl-draft-eword-encode-address-list (string &optional column)
937   "Encode header field STRING as list of address, and return the result.
938 Cause an error when STRING contains invalid address.
939 Optional argument COLUMN is start-position of the field."
940   (car (eword-encode-rword-list
941         (or column eword-encode-default-start-column)
942         (eword-encode-addresses-to-rword-list
943          (wl-draft-std11-parse-addresses (std11-lexical-analyze string))))))
944
945 (defun wl-draft-std11-parse-addresses (lal)
946   (let ((ret (std11-parse-address lal)))
947     (when (and (not (and (eq (length lal) 1)
948                          (eq (car (car lal)) 'spaces)))
949                (null ret))
950       (error "Error while parsing address"))
951     (if ret
952         (let ((dest (list (car ret))))
953           (setq lal (cdr ret))
954           (while (and (setq ret (std11-parse-ascii-token lal))
955                       (string-equal (cdr (assq 'specials (car ret))) ",")
956                       (setq ret (std11-parse-address (cdr ret)))
957                       )
958             (setq dest (cons (car ret) dest))
959             (setq lal (cdr ret)))
960           (while (eq 'spaces (car (car lal)))
961             (setq lal (cdr lal)))
962           (if lal (error "Error while parsing address"))
963           (nreverse dest)))))
964
965 (defun wl-draft-parse-mailbox-list (field &optional remove-group-list)
966   "Get mailbox list of FIELD from current buffer.
967 The buffer is expected to be narrowed to just the headers of the message.
968 If optional argument REMOVE-GROUP-LIST is non-nil, remove group list content
969 from current buffer."
970   (save-excursion
971     (let ((case-fold-search t)
972           (inhibit-read-only t)
973           addresses address
974           mailbox-list beg seq has-group-list)
975       (goto-char (point-min))
976       (while (re-search-forward (concat "^" (regexp-quote field) "[\t ]*:")
977                                 nil t)
978         (setq beg (point))
979         (re-search-forward "^[^ \t]" nil 'move)
980         (beginning-of-line)
981         (skip-chars-backward "\n")
982         (setq seq (std11-lexical-analyze
983                    (buffer-substring-no-properties beg (point))))
984         (setq addresses (wl-draft-std11-parse-addresses seq))
985         (while addresses
986           (cond ((eq (car (car addresses)) 'group)
987                  (setq has-group-list t)
988                  (setq mailbox-list
989                        (nconc mailbox-list
990                               (mapcar
991                                'std11-address-string
992                                (nth 2 (car addresses))))))
993                 ((eq (car (car addresses)) 'mailbox)
994                  (setq address (nth 1 (car addresses)))
995                  (setq mailbox-list
996                        (nconc mailbox-list
997                               (list
998                                (std11-addr-to-string
999                                 (if (eq (car address) 'phrase-route-addr)
1000                                     (nth 2 address)
1001                                   (cdr address))))))))
1002           (setq addresses (cdr addresses)))
1003         (when (and remove-group-list has-group-list)
1004           (delete-region beg (point))
1005           (insert (wl-address-string-without-group-list-contents seq))))
1006       mailbox-list)))
1007
1008 (defun wl-draft-deduce-address-list (buffer header-start header-end)
1009   "Get address list suitable for smtp RCPT TO:<address>.
1010 Group list content is removed if `wl-draft-remove-group-list-contents' is
1011 non-nil."
1012   (let ((fields (if (and wl-draft-doing-mime-bcc
1013                          wl-draft-disable-bcc-for-mime-bcc)
1014                     '("to" "cc")
1015                   '("to" "cc" "bcc")))
1016         (resent-fields '("resent-to" "resent-cc" "resent-bcc"))
1017         (case-fold-search t)
1018         addrs recipients)
1019     (save-excursion
1020       (save-restriction
1021         (narrow-to-region header-start header-end)
1022         (goto-char (point-min))
1023         (save-excursion
1024           (if (re-search-forward "^resent-to[\t ]*:" nil t)
1025               (setq fields resent-fields)))
1026         (while fields
1027           (setq recipients
1028                 (nconc recipients
1029                        (wl-draft-parse-mailbox-list
1030                         (car fields)
1031                         wl-draft-remove-group-list-contents)))
1032           (setq fields (cdr fields)))
1033         recipients))))
1034
1035 ;;
1036 ;; from Semi-gnus
1037 ;;
1038 (defun wl-draft-send-mail-with-smtp ()
1039   "Send the prepared message buffer with SMTP."
1040   (require 'smtp)
1041   (let* ((errbuf (if mail-interactive
1042                      (generate-new-buffer " smtp errors")
1043                    0))
1044          (case-fold-search t)
1045          (default-case-fold-search t)
1046          (sender (or wl-envelope-from
1047                      (wl-address-header-extract-address wl-from)))
1048          (delimline (save-excursion
1049                       (goto-char (point-min))
1050                       (re-search-forward
1051                        (concat "^" (regexp-quote mail-header-separator)
1052                                "$\\|^$") nil t)
1053                       (point-marker)))
1054          (smtp-server
1055           (or wl-smtp-posting-server smtp-server "localhost"))
1056          (smtp-service (or wl-smtp-posting-port smtp-service))
1057          (smtp-local-domain (or smtp-local-domain wl-local-domain))
1058          (id (std11-field-body "message-id"))
1059          recipients)
1060     (if (not (elmo-plugged-p smtp-server smtp-service))
1061         (wl-draft-set-sent-message 'mail 'unplugged
1062                                    (cons smtp-server smtp-service))
1063       (unwind-protect
1064           (save-excursion
1065             ;; Instead of `smtp-deduce-address-list'.
1066             (setq recipients (wl-draft-deduce-address-list
1067                               (current-buffer) (point-min) delimline))
1068             (unless recipients (error "No recipients"))
1069             ;; Insert an extra newline if we need it to work around
1070             ;; Sun's bug that swallows newlines.
1071             (goto-char (1+ delimline))
1072             (if (eval mail-mailer-swallows-blank-line)
1073                 (newline))
1074             (run-hooks 'wl-mail-send-pre-hook) ;; X-PGP-Sig, Cancel-Lock
1075             (if mail-interactive
1076                 (save-excursion
1077                   (set-buffer errbuf)
1078                   (erase-buffer)))
1079             (wl-draft-delete-field "bcc" delimline)
1080             (wl-draft-delete-field "resent-bcc" delimline)
1081             (let (process-connection-type)
1082               (as-binary-process
1083                (when recipients
1084                  (wl-smtp-extension-bind
1085                   (condition-case err
1086                       (smtp-send-buffer sender recipients (current-buffer))
1087                     (error
1088                      (wl-draft-write-sendlog 'failed 'smtp smtp-server
1089                                              recipients id)
1090                      (if (and (eq (car err) 'smtp-response-error)
1091                               (= (nth 1 err) 535))
1092                          (elmo-remove-passwd
1093                           (wl-smtp-password-key
1094                            smtp-sasl-user-name
1095                            (car smtp-sasl-mechanisms)
1096                            smtp-server)))
1097                      (signal (car err) (cdr err)))
1098                     (quit
1099                      (wl-draft-write-sendlog 'uncertain 'smtp smtp-server
1100                                              recipients id)
1101                      (signal (car err) (cdr err)))))
1102                  (wl-draft-set-sent-message 'mail 'sent)
1103                  (wl-draft-write-sendlog
1104                   'ok 'smtp smtp-server recipients id)))))
1105         (if (bufferp errbuf)
1106             (kill-buffer errbuf))))))
1107
1108 (defun wl-draft-send-mail-with-pop-before-smtp ()
1109   "Send the prepared message buffer with POP-before-SMTP."
1110   (require 'elmo-pop3)
1111   (let ((folder
1112          (luna-make-entity
1113           'elmo-pop3-folder
1114           :user   (or wl-pop-before-smtp-user
1115                       elmo-pop3-default-user)
1116           :server (or wl-pop-before-smtp-server
1117                       elmo-pop3-default-server)
1118           :port   (or wl-pop-before-smtp-port
1119                       elmo-pop3-default-port)
1120           :auth   (or wl-pop-before-smtp-authenticate-type
1121                       elmo-pop3-default-authenticate-type)
1122           :stream-type (elmo-get-network-stream-type
1123                         (or wl-pop-before-smtp-stream-type
1124                             elmo-pop3-default-stream-type))))
1125         session)
1126     (condition-case error
1127         (progn
1128           (setq session (elmo-pop3-get-session folder))
1129           (when session (elmo-network-close-session session)))
1130       (error
1131        (unless (string= (nth 1 error) "Unplugged")
1132          (signal (car error) (cdr error))))))
1133   (wl-draft-send-mail-with-smtp))
1134
1135 (defun wl-draft-insert-required-fields (&optional force-msgid)
1136   "Insert Message-ID, Date, and From field.
1137 If FORCE-MSGID, insert message-id regardless of `wl-insert-message-id'."
1138   ;; Insert Message-Id field...
1139   (goto-char (point-min))
1140   (when (and (or force-msgid
1141                  wl-insert-message-id)
1142              (not (re-search-forward "^Message-ID[ \t]*:" nil t)))
1143     (insert (concat "Message-ID: "
1144                     (funcall wl-message-id-function)
1145                     "\n")))
1146   ;; Insert date field.
1147   (goto-char (point-min))
1148   (or (re-search-forward "^Date[ \t]*:" nil t)
1149       (wl-draft-insert-date-field))
1150   ;; Insert from field.
1151   (goto-char (point-min))
1152   (or (re-search-forward "^From[ \t]*:" nil t)
1153       (wl-draft-insert-from-field)))
1154
1155 (defun wl-draft-normal-send-func (editing-buffer kill-when-done)
1156   "Send the message in the current buffer."
1157   (save-restriction
1158     (narrow-to-region (goto-char (point-min))
1159                       (if (re-search-forward
1160                            (concat
1161                             "^" (regexp-quote mail-header-separator) "$")
1162                            nil t)
1163                           (match-beginning 0)
1164                         (point-max)))
1165     (wl-draft-insert-required-fields)
1166     ;; ignore any blank lines in the header
1167     (while (progn (goto-char (point-min))
1168                   (re-search-forward "\n[ \t]*\n\n*" nil t))
1169       (replace-match "\n"))
1170     (goto-char (point-min))
1171     (while (re-search-forward 
1172             "^[^ \t\n:]+:[ \t]*\\(.*\\(\n[ \t].*\\)*\\)\n"
1173             nil t)
1174       (when (string= "" (match-string 1))
1175         (replace-match ""))))
1176 ;;;  (run-hooks 'wl-mail-send-pre-hook) ;; X-PGP-Sig, Cancel-Lock
1177   (wl-draft-dispatch-message)
1178   (when kill-when-done
1179     ;; hide editing-buffer.
1180     (wl-draft-hide editing-buffer)
1181     ;; delete editing-buffer and its file.
1182     (wl-draft-delete editing-buffer)))
1183
1184 (defun wl-draft-dispatch-message (&optional mes-string)
1185   "Send the message in the current buffer.  Not modified the header fields."
1186   (let (delimline mime-bcc)
1187     (if (and wl-draft-verbose-send mes-string)
1188         (message "%s" mes-string))
1189     ;; get fcc folders.
1190     (setq delimline (wl-draft-get-header-delimiter t))
1191     (unless wl-draft-fcc-list
1192       (setq wl-draft-fcc-list (wl-draft-get-fcc-list delimline)))
1193     ;;
1194     (setq wl-sent-message-modified nil)
1195     (unwind-protect
1196         (progn
1197           (if (and (wl-message-mail-p)
1198                    (not (wl-draft-sent-message-p 'mail)))
1199               (if (or (not (or wl-draft-force-queuing
1200                                wl-draft-force-queuing-mail))
1201                       (memq 'mail wl-sent-message-queued))
1202                   (progn
1203                     (setq mime-bcc (wl-draft-mime-bcc-field))
1204                     (funcall wl-draft-send-mail-function)
1205                     (when (not (zerop (length mime-bcc)))
1206                       (wl-draft-do-mime-bcc mime-bcc)))
1207                 (push 'mail wl-sent-message-queued)
1208                 (wl-draft-set-sent-message 'mail 'unplugged)))
1209           (if (and (wl-message-news-p)
1210                    (not (wl-draft-sent-message-p 'news))
1211                    (not (wl-message-field-exists-p "Resent-to")))
1212               (if (or (not (or wl-draft-force-queuing
1213                                wl-draft-force-queuing-news))
1214                       (memq 'news wl-sent-message-queued))
1215                   (funcall wl-draft-send-news-function)
1216                 (push 'news wl-sent-message-queued)
1217                 (wl-draft-set-sent-message 'news 'unplugged))))
1218       (let* ((status (wl-draft-sent-message-results))
1219              (unplugged-via (car status))
1220              (sent-via (nth 1 status)))
1221         ;; If one sent, process fcc folder.
1222         (if (and sent-via wl-draft-fcc-list)
1223             (progn
1224               (wl-draft-do-fcc (wl-draft-get-header-delimiter)
1225                                wl-draft-fcc-list)
1226               (setq wl-draft-fcc-list nil)))
1227         (if wl-draft-use-cache
1228             (let ((id (std11-field-body "Message-ID"))
1229                   (elmo-enable-disconnected-operation t))
1230               (elmo-file-cache-save (elmo-file-cache-get-path id)
1231                                     nil)))
1232         ;; If one unplugged, append queue.
1233         (when (and unplugged-via
1234                    wl-sent-message-modified)
1235           (if wl-draft-enable-queuing
1236               (progn
1237                 (wl-draft-queue-append wl-sent-message-via)
1238                 (setq wl-sent-message-modified 'requeue))
1239             (error "Unplugged")))
1240         (when wl-draft-verbose-send
1241           (if (and unplugged-via sent-via);; combined message
1242               (progn
1243                 (setq wl-draft-verbose-msg
1244                       (format "Sending%s and Queuing%s..."
1245                               sent-via unplugged-via))
1246                 (message "%sdone" wl-draft-verbose-msg))
1247             (if mes-string
1248                 (message "%s%s"
1249                          mes-string
1250                          (if sent-via "done" "failed"))))))))
1251   (not wl-sent-message-modified)) ;; return value
1252
1253 (defun wl-draft-raw-send (&optional kill-when-done force-pre-hook mes-string)
1254   "Force send current buffer as raw message."
1255   (interactive)
1256   (save-excursion
1257     (let (wl-interactive-send
1258 ;;;       wl-draft-verbose-send
1259           (wl-mail-send-pre-hook (and force-pre-hook wl-mail-send-pre-hook))
1260           (wl-news-send-pre-hook (and force-pre-hook wl-news-send-pre-hook))
1261           mail-send-hook
1262           mail-send-actions)
1263       (wl-draft-send kill-when-done mes-string))))
1264
1265 (defun wl-draft-clone-local-variables ()
1266   (let ((locals (buffer-local-variables))
1267         result)
1268     (while locals
1269       (when (and (consp (car locals))
1270                  (car (car locals))
1271                  (string-match wl-draft-clone-local-variable-regexp
1272                                (symbol-name (car (car locals)))))
1273         (wl-append result (list (car (car locals)))))
1274       (setq locals (cdr locals)))
1275     result))
1276
1277 (defcustom wl-draft-send-confirm-with-preview t
1278   "Non-nil to invoke preview through confirmation of sending.
1279 This variable is valid when `wl-interactive-send' has non-nil value."
1280   :type 'boolean
1281   :group 'wl-draft)
1282
1283 (defun wl-draft-send-confirm ()
1284   (let (answer)
1285     (unwind-protect
1286         (condition-case quit
1287             (progn
1288               (when wl-draft-send-confirm-with-preview
1289                 (wl-draft-preview-message))
1290               (save-excursion
1291                 (goto-char (point-min)) ; to show recipients in header
1292                 (catch 'done
1293                   (while t
1294                     (discard-input)
1295                     (message "Send current draft? <y/n/j(down)/k(up)> ")
1296                     (setq answer (let ((cursor-in-echo-area t)) (read-char)))
1297                     (cond
1298                      ((or (eq answer ?y)
1299                           (eq answer ?Y)
1300                           (eq answer ? ))
1301                   (throw 'done t))
1302                      ((or (eq answer ?v)
1303                           (eq answer ?j)
1304                           (eq answer ?J))
1305                       (condition-case err
1306                           (scroll-up)
1307                         (error nil)))
1308                      ((or (eq answer ?^)
1309                           (eq answer ?k)
1310                           (eq answer ?K))
1311                       (condition-case err
1312                           (scroll-down)
1313                         (error nil)))
1314                      (t
1315                       (throw 'done nil)))))))
1316           (quit nil))
1317       (when wl-draft-send-confirm-with-preview
1318         (mime-preview-quit)))))
1319
1320 (defun wl-draft-send (&optional kill-when-done mes-string)
1321   "Send current draft message.
1322 If KILL-WHEN-DONE is non-nil, current draft buffer is killed"
1323   (interactive)
1324   ;; Don't call this explicitly.
1325   ;; Added to 'wl-draft-send-hook (by teranisi)
1326   ;; (wl-draft-config-exec)
1327   (run-hooks 'wl-draft-send-hook)
1328   (when (or (not wl-interactive-send)
1329             (wl-draft-send-confirm))
1330     (let ((send-mail-function 'wl-draft-raw-send)
1331           (editing-buffer (current-buffer))
1332           (sending-buffer (wl-draft-generate-clone-buffer
1333                            " *wl-draft-sending-buffer*"
1334                            (append wl-draft-config-variables
1335                                    (wl-draft-clone-local-variables))))
1336           (wl-draft-verbose-msg nil)
1337           err)
1338       (unwind-protect
1339           (save-excursion
1340             (set-buffer sending-buffer)
1341             (if (and (not (wl-message-mail-p))
1342                      (not (wl-message-news-p)))
1343                 (error "No recipient is specified"))
1344             (expand-abbrev)             ; for mail-abbrevs
1345             (let ((mime-header-encode-method-alist
1346                    (append
1347                     '((wl-draft-eword-encode-address-list
1348                        .  (To Cc Bcc Resent-To Resent-Cc Resent-Bcc From)))
1349                     (if (boundp 'mime-header-encode-method-alist)
1350                         (symbol-value 'mime-header-encode-method-alist)))))
1351               (run-hooks 'mail-send-hook) ; translate buffer
1352               )
1353             ;;
1354             (if wl-draft-verbose-send
1355                 (message "%s" (or mes-string "Sending...")))
1356             (funcall wl-draft-send-function editing-buffer kill-when-done)
1357             ;; Now perform actions on successful sending.
1358             (while mail-send-actions
1359               (condition-case ()
1360                   (apply (car (car mail-send-actions))
1361                          (cdr (car mail-send-actions)))
1362                 (error))
1363               (setq mail-send-actions (cdr mail-send-actions)))
1364             (if wl-draft-verbose-send
1365                 (message "%sdone"
1366                          (or wl-draft-verbose-msg
1367                              mes-string
1368                              "Sending..."))))
1369         ;; kill sending buffer, anyway.
1370         (and (buffer-live-p sending-buffer)
1371              (kill-buffer sending-buffer))))))
1372
1373 (defun wl-draft-mime-bcc-field ()
1374   "Return the MIME-Bcc field body.  The field is deleted."
1375   (prog1 (std11-field-body wl-draft-mime-bcc-field-name)
1376     (wl-draft-delete-field wl-draft-mime-bcc-field-name)))
1377
1378 (defun wl-draft-do-mime-bcc (field-body)
1379   "Send MIME-Bcc (Encapsulated blind carbon copy)."
1380   (let ((orig-from (mime-decode-field-body (std11-field-body "from")
1381                                            'From))
1382         (orig-subj (mime-decode-field-body (or (std11-field-body "subject")
1383                                                "")
1384                                            'Subject))
1385         (recipients (wl-parse-addresses field-body))
1386         (draft-buffer (current-buffer))
1387         wl-draft-use-frame)
1388     (save-window-excursion
1389       (when (and (not wl-draft-doing-mime-bcc) ; To avoid infinite loop.
1390                  (not (zerop (length field-body))))
1391         (let ((wl-draft-doing-mime-bcc t))
1392           (dolist (recipient recipients)
1393             (wl-draft-create-buffer)
1394             (wl-draft-create-contents
1395              (append `((From . ,orig-from)
1396                        (To . ,recipient)
1397                        (Subject . ,(concat "A blind carbon copy ("
1398                                            orig-subj
1399                                            ")")))
1400                      (wl-draft-default-headers)))
1401             (wl-draft-insert-mail-header-separator)
1402             (wl-draft-prepare-edit)
1403             (goto-char (point-max))
1404             (insert (or wl-draft-mime-bcc-body
1405                         "This is a blind carbon copy.")
1406                     "\n")
1407             (mime-edit-insert-tag "message" "rfc822")
1408             (insert-buffer draft-buffer)
1409             (let (wl-interactive-send)
1410               (wl-draft-send 'kill-when-done))))))))
1411
1412 (defun wl-draft-save ()
1413   "Save current draft."
1414   (interactive)
1415   (if (buffer-modified-p)
1416       (progn
1417         (message "Saving...")
1418         (let ((msg (buffer-substring-no-properties (point-min) (point-max)))
1419               next-number)
1420           (when wl-draft-buffer-message-number
1421             (elmo-folder-delete-messages (wl-draft-get-folder)
1422                                          (list wl-draft-buffer-message-number))
1423             (wl-draft-config-info-operation wl-draft-buffer-message-number
1424                                             'delete))
1425           (elmo-folder-check (wl-draft-get-folder))
1426           ;; If no header separator, insert it.
1427           (with-temp-buffer
1428             (insert msg)
1429             (goto-char (point-min))
1430             (unless (re-search-forward
1431                      (concat "^" (regexp-quote mail-header-separator) "$")
1432                      nil t)
1433               (goto-char (point-min))
1434               (if (re-search-forward "\n\n" nil t)
1435                   (replace-match (concat "\n" mail-header-separator "\n"))
1436                 (goto-char (point-max))
1437                 (insert (if (eq (char-before) ?\n) "" "\n")
1438                         mail-header-separator "\n")))
1439             (let ((mime-header-encode-method-alist
1440                    '((eword-encode-unstructured-field-body))))
1441               (mime-edit-translate-buffer))
1442             (wl-draft-get-header-delimiter t)
1443             (setq next-number
1444                   (elmo-folder-next-message-number (wl-draft-get-folder)))
1445             (elmo-folder-append-buffer (wl-draft-get-folder)))
1446           (elmo-folder-check (wl-draft-get-folder))
1447           (elmo-folder-commit (wl-draft-get-folder))
1448           (setq wl-draft-buffer-message-number next-number)
1449           (rename-buffer (format "%s/%d" wl-draft-folder next-number))
1450           (setq buffer-file-name (buffer-name))
1451           (set-buffer-modified-p nil)
1452           (wl-draft-config-info-operation wl-draft-buffer-message-number 'save)
1453           (message "Saving...done")))
1454     (message "(No changes need to be saved)")))
1455
1456 (defun wl-draft-mimic-kill-buffer ()
1457   "Kill the current (draft) buffer with query."
1458   (interactive)
1459   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
1460                                       (buffer-name))))
1461         wl-draft-use-frame)
1462     (if (or (not bufname)
1463             (string-equal bufname "")
1464             (string-equal bufname (buffer-name)))
1465         (let ((bufname (current-buffer)))
1466           (when (or (not (buffer-modified-p))
1467                     (yes-or-no-p
1468                      (format "Buffer %s modified; kill anyway? " bufname)))
1469             (set-buffer-modified-p nil)
1470             (wl-draft-hide bufname)
1471             (kill-buffer bufname)))
1472       (kill-buffer bufname))))
1473
1474 (defun wl-draft-save-and-exit ()
1475   "Save current draft and exit current draft mode."
1476   (interactive)
1477   (wl-draft-save)
1478   (let ((editing-buffer (current-buffer)))
1479     (wl-draft-hide editing-buffer)
1480     (kill-buffer editing-buffer)))
1481
1482 (defun wl-draft-send-and-exit ()
1483   "Send current draft message and kill it."
1484   (interactive)
1485   (wl-draft-send t))
1486
1487 (defun wl-draft-send-from-toolbar ()
1488   (interactive)
1489   (let ((wl-interactive-send t))
1490     (wl-draft-send-and-exit)))
1491
1492 (defun wl-draft-delete-field (field &optional delimline replace)
1493   (wl-draft-delete-fields (regexp-quote field) delimline replace))
1494
1495 (defun wl-draft-delete-fields (field &optional delimline replace)
1496   (save-restriction
1497     (unless delimline
1498       (goto-char (point-min))
1499       (if (search-forward "\n\n" nil t)
1500           (setq delimline (point))
1501         (setq delimline (point-max))))
1502     (narrow-to-region (point-min) delimline)
1503     (goto-char (point-min))
1504     (let ((regexp (concat "^" field ":"))
1505           (case-fold-search t))
1506       (while (not (eobp))
1507         (if (looking-at regexp)
1508             (progn
1509               (delete-region
1510                (point)
1511                (progn
1512                  (forward-line 1)
1513                  (if (re-search-forward "^[^ \t]" nil t)
1514                      (goto-char (match-beginning 0))
1515                    (point-max))))
1516               (if replace
1517                   (insert (concat field ": " replace "\n"))))
1518           (forward-line 1)
1519           (if (re-search-forward "^[^ \t]" nil t)
1520               (goto-char (match-beginning 0))
1521             (point-max)))))))
1522
1523 (defun wl-draft-get-fcc-list (header-end)
1524   (if (and wl-draft-doing-mime-bcc
1525            wl-draft-disable-fcc-for-mime-bcc)
1526       (progn
1527         (wl-draft-delete-field "fcc")
1528         nil)
1529     (let (fcc-list
1530           (case-fold-search t))
1531       (or (markerp header-end) (error "HEADER-END must be a marker"))
1532       (save-excursion
1533         (goto-char (point-min))
1534         (while (re-search-forward "^Fcc:[ \t]*" header-end t)
1535           (save-match-data
1536             (setq fcc-list
1537                   (append fcc-list
1538                           (split-string
1539                            (buffer-substring-no-properties
1540                             (point)
1541                             (progn
1542                               (end-of-line)
1543                               (skip-chars-backward " \t")
1544                               (point)))
1545                            ",[ \t]*")))
1546             (dolist (folder fcc-list)
1547               (wl-folder-confirm-existence
1548                (wl-folder-get-elmo-folder (eword-decode-string folder)))))
1549           (delete-region (match-beginning 0)
1550                          (progn (forward-line 1) (point)))))
1551       fcc-list)))
1552
1553 (defcustom wl-draft-fcc-append-read-folder-history t
1554   "Non-nil to append fcc'ed folder to `wl-read-folder-history'."
1555   :type 'boolean
1556   :group 'wl-draft)
1557
1558 (defun wl-draft-do-fcc (header-end &optional fcc-list)
1559   (let ((send-mail-buffer (current-buffer))
1560         (tembuf (generate-new-buffer " fcc output"))
1561         (case-fold-search t)
1562         beg end)
1563     (or (markerp header-end) (error "HEADER-END must be a marker"))
1564     (save-excursion
1565       (unless fcc-list
1566         (setq fcc-list (wl-draft-get-fcc-list header-end)))
1567       (set-buffer tembuf)
1568       (erase-buffer)
1569       ;; insert just the headers to avoid moving the gap more than
1570       ;; necessary (the message body could be arbitrarily huge.)
1571       (insert-buffer-substring send-mail-buffer 1 header-end)
1572       (wl-draft-insert-required-fields t)
1573       (goto-char (point-max))
1574       (insert-buffer-substring send-mail-buffer header-end)
1575       (let ((id (std11-field-body "Message-ID"))
1576             (elmo-enable-disconnected-operation t)
1577             cache-saved)
1578         (while fcc-list
1579           (unless (or cache-saved
1580                       (elmo-folder-plugged-p
1581                        (wl-folder-get-elmo-folder (car fcc-list))))
1582             (elmo-file-cache-save id nil) ;; for disconnected operation
1583             (setq cache-saved t))
1584           (if (elmo-folder-append-buffer
1585                (wl-folder-get-elmo-folder
1586                 (eword-decode-string (car fcc-list)))
1587                (and wl-fcc-force-as-read '(read)))
1588               (wl-draft-write-sendlog 'ok 'fcc nil (car fcc-list) id)
1589             (wl-draft-write-sendlog 'failed 'fcc nil (car fcc-list) id))
1590           (if (and wl-draft-fcc-append-read-folder-history
1591                    (boundp 'wl-read-folder-history))
1592               (or (equal (car fcc-list) (car wl-read-folder-history))
1593                   (setq wl-read-folder-history
1594                         (append (list (car fcc-list)) wl-read-folder-history))))
1595           (setq fcc-list (cdr fcc-list)))))
1596     (kill-buffer tembuf)))
1597
1598 (defun wl-draft-on-field-p ()
1599   (if (< (point)
1600          (save-excursion
1601            (goto-char (point-min))
1602            (search-forward (concat "\n" mail-header-separator "\n") nil 0)
1603            (point)))
1604       (if (bolp)
1605           (if (bobp)
1606               t
1607             (save-excursion
1608               (forward-line -1)
1609               (if (or (looking-at ".*,[ \t]?$")
1610                       (looking-at "^[^ \t]+:[ \t]+.*:$")); group list name
1611                   nil t)))
1612         (let ((pos (point)))
1613           (save-excursion
1614             (beginning-of-line)
1615             (if (looking-at "^[ \t]")
1616                 nil
1617               (if (re-search-forward ":" pos t) nil t)))))))
1618
1619 ;;;;;;;;;;;;;;;;
1620 ;;;###autoload
1621 (defun wl-draft (&optional header-alist
1622                            content-type content-transfer-encoding
1623                            body edit-again
1624                            parent-folder)
1625   "Write and send mail/news message with Wanderlust."
1626   (interactive)
1627   (require 'wl)
1628   (unless wl-init
1629     (wl-load-profile)
1630     (wl-folder-init)
1631     (elmo-init)
1632     (wl-plugged-init t))
1633   (let (wl-demo)
1634     (wl-init)) ; returns immediately if already initialized.
1635
1636
1637   (let (buffer header-alist-internal)
1638     (setq buffer (wl-draft-create-buffer parent-folder))
1639     (unless (cdr (assq 'From header-alist))
1640       (setq header-alist
1641             (append (list (cons 'From wl-from)) header-alist)))
1642     (unless (cdr (assq 'To header-alist))
1643       (let ((to))
1644         (when (setq to (and
1645                         (interactive-p)
1646                         ""))
1647           (if (assq 'To header-alist)
1648               (setcdr (assq 'To header-alist) to)
1649             (setq header-alist
1650                   (append header-alist
1651                           (list (cons 'To to))))))))
1652     (unless (cdr (assq 'Subject header-alist))
1653       (if (assq 'Subject header-alist)
1654           (setcdr (assq 'Subject header-alist) "")
1655         (setq header-alist
1656               (append header-alist (list (cons 'Subject ""))))))
1657     (setq header-alist (append header-alist
1658                                (wl-draft-default-headers)
1659                                wl-draft-additional-header-alist
1660                                (if body (list "" (cons 'Body body)))))
1661     (wl-draft-create-contents header-alist)
1662     (if edit-again
1663         (wl-draft-decode-body
1664          content-type content-transfer-encoding))
1665     (wl-draft-insert-mail-header-separator)
1666     (wl-draft-prepare-edit)
1667     (if (interactive-p)
1668         (run-hooks 'wl-mail-setup-hook))
1669     (goto-char (point-min))
1670     (setq buffer-undo-list nil)
1671     (wl-user-agent-compose-internal) ;; user-agent
1672     (cond ((and
1673             (interactive-p)
1674             (string= (cdr (assq 'To header-alist)) ""))
1675            (mail-position-on-field "To"))
1676           (t
1677            (goto-char (point-max))))
1678     buffer))
1679
1680 (defun wl-draft-create-buffer (&optional parent-folder)
1681   (let* ((draft-folder (wl-draft-get-folder))
1682          (parent-folder (or parent-folder (wl-summary-buffer-folder-name)))
1683          (summary-buf (wl-summary-get-buffer parent-folder))
1684          (reply-or-forward
1685           (or (eq this-command 'wl-summary-reply)
1686               (eq this-command 'wl-summary-reply-with-citation)
1687               (eq this-command 'wl-summary-forward)
1688               (eq this-command 'wl-summary-target-mark-forward)
1689               (eq this-command 'wl-summary-target-mark-reply-with-citation)))
1690          (buffer (generate-new-buffer "*draft*")) ; Just for initial name.
1691          change-major-mode-hook)
1692     (set-buffer buffer)
1693     ;; switch-buffer according to draft buffer style.
1694     (if wl-draft-use-frame
1695         (switch-to-buffer-other-frame buffer)
1696       (if reply-or-forward
1697           (case wl-draft-reply-buffer-style
1698             (split
1699              (split-window-vertically)
1700              (other-window 1)
1701              (switch-to-buffer buffer))
1702             (keep
1703              (switch-to-buffer buffer))
1704             (full
1705              (delete-other-windows)
1706              (switch-to-buffer buffer))
1707             (t
1708              (if (functionp wl-draft-reply-buffer-style)
1709                  (funcall wl-draft-reply-buffer-style buffer)
1710                (error "Invalid value for wl-draft-reply-buffer-style"))))
1711         (case wl-draft-buffer-style
1712           (split
1713            (when (eq major-mode 'wl-summary-mode)
1714              (wl-summary-toggle-disp-msg 'off))
1715            (split-window-vertically)
1716            (other-window 1)
1717            (switch-to-buffer buffer))
1718           (keep
1719            (switch-to-buffer buffer))
1720           (full
1721            (delete-other-windows)
1722            (switch-to-buffer buffer))
1723           (t (if (functionp wl-draft-buffer-style)
1724                  (funcall wl-draft-buffer-style buffer)
1725                (error "Invalid value for wl-draft-buffer-style"))))))
1726     (auto-save-mode -1)
1727     (wl-draft-mode)
1728     (set-buffer-multibyte t)            ; draft buffer is always multibyte.
1729     (make-local-variable 'truncate-partial-width-windows)
1730     (setq truncate-partial-width-windows nil)
1731     (setq truncate-lines wl-draft-truncate-lines)
1732     (setq wl-sent-message-via nil)
1733     (setq wl-sent-message-queued nil)
1734     (setq wl-draft-config-exec-flag t)
1735     (setq wl-draft-parent-folder (or parent-folder ""))
1736     (or (eq this-command 'wl-folder-write-current-folder)
1737         (setq wl-draft-buffer-cur-summary-buffer summary-buf))
1738     buffer))
1739
1740 (defun wl-draft-create-contents (header-alist)
1741   "header-alist' sample
1742 '(function  ;; funcall
1743   string    ;; insert string
1744   (symbol . string)    ;;  insert symbol-value: string
1745   (symbol . function)  ;;  (funcall) and if it returns string,
1746                        ;;  insert symbol-value: string
1747   (symbol . nil)       ;;  do nothing
1748   nil                  ;;  do nothing
1749   )"
1750   (unless (eq major-mode 'wl-draft-mode)
1751     (error "`wl-draft-create-header' must be use in wl-draft-mode"))
1752   (let ((halist header-alist)
1753         field value)
1754     (while halist
1755       (cond
1756        ;; function
1757        ((functionp (car halist)) (funcall (car halist)))
1758        ;; string
1759        ((stringp (car halist)) (insert (car halist) "\n"))
1760        ;; cons
1761        ((consp (car halist))
1762         (setq field (car (car halist)))
1763         (setq value (cdr (car halist)))
1764         (cond
1765          ((symbolp field)
1766           (cond
1767            ((eq field 'Body) ; body
1768             (insert value))
1769            ((stringp value) (insert (symbol-name field) ": " value "\n"))
1770            ((functionp value)
1771             (let ((value-return (funcall value)))
1772               (when (stringp value-return)
1773                 (insert (symbol-name field) ": " value-return "\n"))))
1774            ((not value))
1775            (t
1776             (debug))))
1777          ;;
1778          ((not field))
1779          (t
1780           (debug))
1781          )))
1782       (setq halist (cdr halist)))))
1783
1784 (defun wl-draft-prepare-edit ()
1785   (unless (eq major-mode 'wl-draft-mode)
1786     (error "`wl-draft-create-header' must be use in wl-draft-mode"))
1787   (let (change-major-mode-hook)
1788     (wl-draft-editor-mode)
1789     (static-when (boundp 'auto-save-file-name-transforms)
1790       (make-local-variable 'auto-save-file-name-transforms)
1791       (setq auto-save-file-name-transforms
1792             (cons (list (concat (regexp-quote wl-draft-folder)
1793                                 "/\\([0-9]+\\)")
1794                         (concat (expand-file-name
1795                                  "auto-save-"
1796                                  (elmo-folder-msgdb-path
1797                                   (wl-draft-get-folder)))
1798                                 "\\1"))
1799                   auto-save-file-name-transforms)))
1800     (when wl-draft-write-file-function
1801       (add-hook 'local-write-file-hooks wl-draft-write-file-function))
1802     (wl-draft-overload-functions)
1803     (wl-highlight-headers 'for-draft)
1804     (wl-draft-save)
1805     (clear-visited-file-modtime)))
1806
1807 (defun wl-draft-decode-header ()
1808   (save-excursion
1809     (std11-narrow-to-header)
1810     (wl-draft-decode-message-in-buffer)
1811     (widen)))
1812
1813 (defun wl-draft-decode-body (&optional content-type content-transfer-encoding)
1814   (let ((content-type
1815          (or content-type
1816                 (std11-field-body "content-type")))
1817         (content-transfer-encoding
1818          (or content-transfer-encoding
1819              (std11-field-body "content-transfer-encoding")))
1820         delimline)
1821     (save-excursion
1822       (std11-narrow-to-header)
1823       (wl-draft-delete-field "content-type")
1824       (wl-draft-delete-field "content-transfer-encoding")
1825       (goto-char (point-max))
1826       (setq delimline (point-marker))
1827       (widen)
1828       (narrow-to-region delimline (point-max))
1829       (goto-char (point-min))
1830       (when content-type
1831         (insert "Content-type: " content-type "\n"))
1832       (when content-transfer-encoding
1833         (insert "Content-Transfer-Encoding: " content-transfer-encoding "\n"))
1834       (wl-draft-decode-message-in-buffer)
1835       (goto-char (point-min))
1836       (unless (re-search-forward "^$" (point-at-eol) t)
1837         (insert "\n"))
1838       (widen)
1839       delimline)))
1840
1841 ;;; subroutine for wl-draft-create-contents
1842 ;;; must be used in wl-draft-mode
1843 (defun wl-draft-check-new-line ()
1844   (if (not (= (preceding-char) ?\n))
1845       (insert ?\n)))
1846
1847 (defsubst wl-draft-trim-ccs (cc)
1848   (let ((field
1849          (if (functionp cc)
1850              (funcall cc)
1851            cc)))
1852     (if (and field
1853              (null (and wl-draft-delete-myself-from-bcc-fcc
1854                         (elmo-list-member
1855                          (mapcar 'wl-address-header-extract-address
1856                                  (append
1857                                   (wl-parse-addresses (std11-field-body "To"))
1858                                   (wl-parse-addresses (std11-field-body "Cc"))))
1859                          (mapcar 'downcase wl-subscribed-mailing-list)))))
1860         field
1861       nil)))
1862
1863 (defsubst wl-draft-default-headers ()
1864   (list
1865    (cons 'Mail-Reply-To (and wl-insert-mail-reply-to
1866                              (wl-address-header-extract-address
1867                               wl-from)))
1868    (cons 'User-Agent wl-generate-mailer-string-function)
1869    (cons 'Reply-To mail-default-reply-to)
1870    (cons 'Bcc (function
1871                (lambda ()
1872                  (wl-draft-trim-ccs
1873                   (or wl-bcc (and mail-self-blind (user-login-name)))))))
1874    (cons 'Fcc (function
1875                (lambda ()
1876                  (wl-draft-trim-ccs wl-fcc))))
1877    (cons 'Organization wl-organization)
1878    (and wl-auto-insert-x-face
1879         (file-exists-p wl-x-face-file)
1880         'wl-draft-insert-x-face-field-here) ;; allow nil
1881    mail-default-headers
1882    ;; check \n at th end of line for `mail-default-headers'
1883    'wl-draft-check-new-line
1884    ))
1885
1886 (defun wl-draft-insert-mail-header-separator (&optional delimline)
1887   (save-excursion
1888     (if delimline
1889         (goto-char delimline)
1890       (goto-char (point-min))
1891       (if (search-forward "\n\n" nil t)
1892           (delete-backward-char 1)
1893         (goto-char (point-max))))
1894     (wl-draft-check-new-line)
1895     (put-text-property (point)
1896                        (progn
1897                          (insert mail-header-separator "\n")
1898                          (1- (point)))
1899                        'category 'mail-header-separator)
1900     (point)))
1901
1902 ;;;;;;;;;;;;;;;;
1903
1904 (defun wl-draft-elmo-nntp-send ()
1905   (let ((elmo-nntp-post-pre-hook wl-news-send-pre-hook)
1906         (elmo-nntp-default-user
1907          (or wl-nntp-posting-user elmo-nntp-default-user))
1908         (elmo-nntp-default-server
1909          (or wl-nntp-posting-server elmo-nntp-default-server))
1910         (elmo-nntp-default-port
1911          (or wl-nntp-posting-port elmo-nntp-default-port))
1912         (elmo-nntp-default-stream-type
1913          (or wl-nntp-posting-stream-type elmo-nntp-default-stream-type))
1914         (elmo-nntp-default-function wl-nntp-posting-function)
1915         condition)
1916     (if (setq condition (cdr (elmo-string-matched-assoc
1917                               (std11-field-body "Newsgroups")
1918                               wl-nntp-posting-config-alist)))
1919         (if (stringp condition)
1920             (setq elmo-nntp-default-server condition)
1921           (while (car condition)
1922             (set (intern (format "elmo-nntp-default-%s"
1923                                  (symbol-name (caar condition))))
1924                  (cdar condition))
1925             (setq condition (cdr condition)))))
1926     (unless elmo-nntp-default-function
1927       (error "wl-draft-nntp-send: posting-function is nil"))
1928     (if (not (elmo-plugged-p elmo-nntp-default-server elmo-nntp-default-port))
1929         (wl-draft-set-sent-message 'news 'unplugged
1930                                    (cons elmo-nntp-default-server
1931                                          elmo-nntp-default-port))
1932       (funcall elmo-nntp-default-function
1933                elmo-nntp-default-server (current-buffer))
1934       (wl-draft-set-sent-message 'news 'sent)
1935       (wl-draft-write-sendlog 'ok 'nntp elmo-nntp-default-server
1936                               (std11-field-body "Newsgroups")
1937                               (std11-field-body "Message-ID")))))
1938
1939 (defun wl-draft-generate-clone-buffer (name &optional local-variables)
1940   "Generate clone of current buffer named NAME."
1941   (let ((editing-buffer (current-buffer)))
1942     (save-excursion
1943       (set-buffer (generate-new-buffer name))
1944       (erase-buffer)
1945       (wl-draft-mode)
1946       (wl-draft-editor-mode)
1947       (insert-buffer editing-buffer)
1948       (message "")
1949       (while local-variables
1950         (make-local-variable (car local-variables))
1951         (set (car local-variables)
1952              (save-excursion
1953                (set-buffer editing-buffer)
1954                (symbol-value (car local-variables))))
1955         (setq local-variables (cdr local-variables)))
1956       (current-buffer))))
1957
1958 (defun wl-draft-remove-text-plain-tag ()
1959   "Remove text/plain tag of mime-edit."
1960   (when (string= (mime-make-text-tag "plain")
1961                  (buffer-substring-no-properties (point-at-bol)(point-at-eol)))
1962     (delete-region (point-at-bol)(1+ (point-at-eol)))))
1963
1964 (defun wl-draft-reedit (number)
1965   (let ((draft-folder (wl-draft-get-folder))
1966         (wl-draft-reedit t)
1967         (num 0)
1968         buffer change-major-mode-hook body-top)
1969     (setq buffer (get-buffer-create (format "%s/%d" wl-draft-folder
1970                                             number)))
1971     (if wl-draft-use-frame
1972         (switch-to-buffer-other-frame buffer)
1973       (switch-to-buffer buffer))
1974     (set-buffer buffer)
1975     (elmo-message-fetch draft-folder number (elmo-make-fetch-strategy 'entire)
1976                         nil (current-buffer))
1977     (elmo-delete-cr-buffer)
1978     (let ((mime-edit-again-ignored-field-regexp
1979            "^\\(Content-.*\\|Mime-Version\\):"))
1980       (wl-draft-decode-message-in-buffer))
1981     (setq body-top (wl-draft-insert-mail-header-separator))
1982     (auto-save-mode -1)
1983     (wl-draft-mode)
1984     (make-local-variable 'truncate-partial-width-windows)
1985     (setq truncate-partial-width-windows nil)
1986     (setq truncate-lines wl-draft-truncate-lines)
1987     (setq wl-sent-message-via nil)
1988     (setq wl-sent-message-queued nil)
1989     (wl-draft-config-info-operation number 'load)
1990     (goto-char (point-min))
1991     (wl-draft-overload-functions)
1992     (wl-draft-editor-mode)
1993     (static-when (boundp 'auto-save-file-name-transforms)
1994       (make-local-variable 'auto-save-file-name-transforms)
1995       (setq auto-save-file-name-transforms
1996             (cons (list (concat (regexp-quote wl-draft-folder)
1997                                 "/\\([0-9]+\\)")
1998                         (concat (expand-file-name
1999                                  "auto-save-"
2000                                  (elmo-folder-msgdb-path
2001                                   (wl-draft-get-folder)))
2002                                 "\\1"))
2003                   auto-save-file-name-transforms)))
2004     (setq buffer-file-name (buffer-name)
2005           wl-draft-parent-folder ""
2006           wl-draft-buffer-message-number number)
2007     (when wl-draft-write-file-function
2008       (add-hook 'local-write-file-hooks wl-draft-write-file-function))
2009     (wl-highlight-headers 'for-draft)
2010     (goto-char body-top)
2011     (run-hooks 'wl-draft-reedit-hook)
2012     (goto-char (point-max))
2013     buffer))
2014
2015 (defmacro wl-draft-body-goto-top ()
2016   (` (progn
2017        (goto-char (point-min))
2018        (if (re-search-forward mail-header-separator nil t)
2019            (forward-char 1)
2020          (goto-char (point-max))))))
2021
2022 (defmacro wl-draft-body-goto-bottom ()
2023   (` (goto-char (point-max))))
2024
2025 (defmacro wl-draft-config-body-goto-header ()
2026   (` (progn
2027        (goto-char (point-min))
2028        (if (re-search-forward mail-header-separator nil t)
2029            (beginning-of-line)
2030          (goto-char (point-max))))))
2031
2032 (defsubst wl-draft-config-sub-eval-insert (content &optional newline)
2033   (let (content-value)
2034     (when (and content
2035                (stringp (setq content-value (eval content))))
2036       (insert content-value)
2037       (if newline (insert "\n")))))
2038
2039 (defun wl-draft-config-sub-body (content)
2040   (wl-draft-body-goto-top)
2041   (delete-region (point) (point-max))
2042   (wl-draft-config-sub-eval-insert content))
2043
2044 (defun wl-draft-config-sub-top (content)
2045   (wl-draft-body-goto-top)
2046   (wl-draft-config-sub-eval-insert content))
2047
2048 (defun wl-draft-config-sub-bottom (content)
2049   (wl-draft-body-goto-bottom)
2050   (wl-draft-config-sub-eval-insert content))
2051
2052 (defun wl-draft-config-sub-header (content)
2053   (wl-draft-config-body-goto-header)
2054   (wl-draft-config-sub-eval-insert content 'newline))
2055
2056 (defun wl-draft-config-sub-header-top (content)
2057   (goto-char (point-min))
2058   (wl-draft-config-sub-eval-insert content 'newline))
2059
2060 (defun wl-draft-config-sub-part-top (content)
2061   (goto-char (mime-edit-content-beginning))
2062   (wl-draft-config-sub-eval-insert content 'newline))
2063
2064 (defun wl-draft-config-sub-part-bottom (content)
2065   (goto-char (mime-edit-content-end))
2066   (wl-draft-config-sub-eval-insert content 'newline))
2067
2068 (defsubst wl-draft-config-sub-file (content)
2069   (let ((coding-system-for-read wl-cs-autoconv)
2070         (file (expand-file-name (eval content))))
2071     (if (file-exists-p file)
2072         (insert-file-contents file)
2073       (error "%s: no exists file" file))))
2074
2075 (defun wl-draft-config-sub-body-file (content)
2076   (wl-draft-body-goto-top)
2077   (delete-region (point) (point-max))
2078   (wl-draft-config-sub-file content))
2079
2080 (defun wl-draft-config-sub-top-file (content)
2081   (wl-draft-body-goto-top)
2082   (wl-draft-config-sub-file content))
2083
2084 (defun wl-draft-config-sub-bottom-file (content)
2085   (wl-draft-body-goto-bottom)
2086   (wl-draft-config-sub-file content))
2087
2088 (defun wl-draft-config-sub-header-file (content)
2089   (wl-draft-config-body-goto-header)
2090   (wl-draft-config-sub-file content))
2091
2092 (defun wl-draft-config-sub-template (content)
2093   (setq wl-draft-config-variables
2094         (wl-template-insert (eval content))))
2095
2096 (defun wl-draft-config-sub-x-face (content)
2097   (if (and (string-match "\\.xbm\\(\\.gz\\)?$" content)
2098            (fboundp 'x-face-insert)) ; x-face.el is installed.
2099       (x-face-insert content)
2100     (wl-draft-replace-field "X-Face" (elmo-get-file-string content t) t)))
2101
2102 (defsubst wl-draft-config-sub-func (field content)
2103   (let (func)
2104     (if (setq func (assq field wl-draft-config-sub-func-alist))
2105         (let (wl-draft-config-variables)
2106           (funcall (cdr func) content)
2107           ;; for wl-draft-config-sub-template
2108           (cons t wl-draft-config-variables)))))
2109
2110 (defsubst wl-draft-config-exec-sub (clist)
2111   (let (config local-variables)
2112     (while clist
2113       (setq config (car clist))
2114       (cond
2115        ((functionp config)
2116         (funcall config))
2117        ((consp config)
2118         (let ((field (car config))
2119               (content (cdr config))
2120               ret-val)
2121           (cond
2122            ((stringp field)
2123             (wl-draft-replace-field field (eval content) t))
2124            ((setq ret-val (wl-draft-config-sub-func field content))
2125             (if (cdr ret-val) ;; for wl-draft-config-sub-template
2126                 (wl-append local-variables (cdr ret-val))))
2127            ((boundp field) ;; variable
2128             (make-local-variable field)
2129             (set field (eval content))
2130             (wl-append local-variables (list field)))
2131            (t
2132             (error "%s: not variable" field)))))
2133        (t
2134         (error "%s: not supported type" config)))
2135       (setq clist (cdr clist)))
2136     local-variables))
2137
2138 (defun wl-draft-prepared-config-exec (&optional config-alist reply-buf)
2139   "Change headers in draft preparation time."
2140   (interactive)
2141   (unless wl-draft-reedit
2142     (let ((config-alist
2143            (or config-alist
2144                (and (boundp 'wl-draft-prepared-config-alist)
2145                     wl-draft-prepared-config-alist)     ;; For compatible.
2146                wl-draft-config-alist)))
2147       (if config-alist
2148           (wl-draft-config-exec config-alist reply-buf)))))
2149
2150 (defun wl-draft-config-exec (&optional config-alist reply-buf)
2151   "Change headers according to the value of `wl-draft-config-alist'.
2152 Automatically applied in draft sending time."
2153   (interactive)
2154   (let ((case-fold-search t)
2155         (alist (or config-alist wl-draft-config-alist))
2156         (reply-buf (or reply-buf (and (buffer-live-p wl-draft-reply-buffer)
2157                                       wl-draft-reply-buffer)))
2158         (local-variables wl-draft-config-variables)
2159         key clist found)
2160     (when (and (or (interactive-p)
2161                    wl-draft-config-exec-flag)
2162                alist)
2163       (save-excursion
2164         (catch 'done
2165           (while alist
2166             (setq key (caar alist)
2167                   clist (cdar alist))
2168             (cond
2169              ((eq key 'reply)
2170               (when (and
2171                      reply-buf
2172                      (save-excursion
2173                        (set-buffer reply-buf)
2174                        (save-restriction
2175                          (std11-narrow-to-header)
2176                          (goto-char (point-min))
2177                          (re-search-forward (car clist) nil t))))
2178                 (wl-draft-config-exec-sub (cdr clist))
2179                 (setq found t)))
2180              ((stringp key)
2181               (when (save-restriction
2182                       (std11-narrow-to-header mail-header-separator)
2183                       (goto-char (point-min))
2184                       (re-search-forward key nil t))
2185                 (wl-append local-variables
2186                            (wl-draft-config-exec-sub clist))
2187                 (setq found t)))
2188              ((eval key)
2189               (wl-append local-variables
2190                          (wl-draft-config-exec-sub clist))
2191               (setq found t)))
2192             (if (and found wl-draft-config-matchone)
2193                 (throw 'done t))
2194             (setq alist (cdr alist))))
2195         (if found
2196             (setq wl-draft-config-exec-flag nil))
2197         (run-hooks 'wl-draft-config-exec-hook)
2198         (put-text-property (point-min)(point-max) 'face nil)
2199         (wl-highlight-message (point-min)(point-max) t)
2200         (setq wl-draft-config-variables
2201               (elmo-uniq-list local-variables))))))
2202
2203 (defun wl-draft-replace-field (field content &optional add)
2204   (save-excursion
2205     (save-restriction
2206       (let ((case-fold-search t)
2207             (inhibit-read-only t) ;; added by teranisi.
2208             beg)
2209         (std11-narrow-to-header mail-header-separator)
2210         (goto-char (point-min))
2211         (if (re-search-forward (concat "^" (regexp-quote field) ":") nil t)
2212             (if content
2213                 ;; replace field
2214                 (progn
2215                   (setq beg (point))
2216                   (re-search-forward "^[^ \t]" nil 'move)
2217                   (beginning-of-line)
2218                   (skip-chars-backward "\n")
2219                   (delete-region beg (point))
2220                   (insert " " content))
2221               ;; delete field
2222               (save-excursion
2223                 (beginning-of-line)
2224                 (setq beg (point)))
2225               (re-search-forward "^[^ \t]" nil 'move)
2226               (beginning-of-line)
2227               (delete-region beg (point)))
2228           (when (and add content)
2229             ;; add field
2230             (goto-char (point-max))
2231             (insert (concat field ": " content "\n"))))))))
2232
2233 (defun wl-draft-config-info-operation (msg operation)
2234   (let* ((msgdb-dir (elmo-folder-msgdb-path (wl-draft-get-folder)))
2235          (filename
2236           (expand-file-name
2237            (format "%s-%d" wl-draft-config-save-filename msg)
2238            msgdb-dir))
2239          element alist variable)
2240     (cond
2241      ((eq operation 'save)
2242       (let ((variables (elmo-uniq-list wl-draft-config-variables)))
2243         (while (setq variable (pop variables))
2244           (when (boundp variable)
2245             (wl-append alist
2246                        (list (cons variable (eval variable))))))
2247         (elmo-object-save filename alist)))
2248      ((eq operation 'load)
2249       (setq alist (elmo-object-load filename))
2250       (while (setq element (pop alist))
2251         (set (make-local-variable (car element)) (cdr element))
2252         (wl-append wl-draft-config-variables (list (car element)))))
2253      ((eq operation 'delete)
2254       (if (file-exists-p filename)
2255           (delete-file filename))))))
2256
2257 (defun wl-draft-queue-info-operation (msg operation
2258                                           &optional add-sent-message-via)
2259   (let* ((msgdb-dir (elmo-folder-msgdb-path
2260                      (wl-folder-get-elmo-folder wl-queue-folder)))
2261          (filename
2262           (expand-file-name
2263            (format "%s-%d" wl-draft-queue-save-filename msg)
2264            msgdb-dir))
2265          element alist variable)
2266     (cond
2267      ((eq operation 'save)
2268       (let ((variables (elmo-uniq-list
2269                         (append wl-draft-queue-save-variables
2270                                 wl-draft-config-variables
2271                                 (list 'wl-draft-fcc-list)))))
2272         (if add-sent-message-via
2273             (progn
2274               (push 'wl-sent-message-queued variables)
2275               (push 'wl-sent-message-via variables)))
2276         (while (setq variable (pop variables))
2277           (when (boundp variable)
2278             (wl-append alist
2279                        (list (cons variable (eval variable))))))
2280         (elmo-object-save filename alist)))
2281      ((eq operation 'load)
2282       (setq alist (elmo-object-load filename))
2283       (while (setq element (pop alist))
2284         (set (make-local-variable (car element)) (cdr element))))
2285      ((eq operation 'get-sent-via)
2286       (setq alist (elmo-object-load filename))
2287       (cdr (assq 'wl-sent-message-via alist)))
2288      ((eq operation 'delete)
2289       (if (file-exists-p filename)
2290           (delete-file filename))))))
2291
2292 (defun wl-draft-queue-append (wl-sent-message-via)
2293   (if wl-draft-verbose-send
2294       (message "Queuing..."))
2295   (let ((send-buffer (current-buffer))
2296         (folder (wl-folder-get-elmo-folder wl-queue-folder))
2297         (message-id (std11-field-body "Message-ID")))
2298     (if (elmo-folder-append-buffer folder)
2299         (progn
2300           (wl-draft-queue-info-operation
2301            (car (elmo-folder-status folder))
2302            'save wl-sent-message-via)
2303           (wl-draft-write-sendlog 'ok 'queue nil wl-queue-folder message-id)
2304           (when wl-draft-verbose-send
2305             (setq wl-draft-verbose-msg "Queuing...")
2306             (message "Queuing...done")))
2307       (wl-draft-write-sendlog 'failed 'queue nil wl-queue-folder message-id)
2308       (error "Queuing failed"))))
2309
2310 (defun wl-draft-queue-flush ()
2311   "Flush draft queue."
2312   (interactive)
2313   (let* ((queue-folder (wl-folder-get-elmo-folder wl-queue-folder))
2314          (msgs2 (progn
2315                   (elmo-folder-open-internal queue-folder)
2316                   (elmo-folder-list-messages queue-folder)))
2317          (i 0)
2318          (performed 0)
2319          (wl-draft-queue-flushing t)
2320          msgs failure len buffer msgid sent-via)
2321     ;; get plugged send message
2322     (while msgs2
2323       (setq sent-via (wl-draft-queue-info-operation (car msgs2) 'get-sent-via))
2324       (catch 'found
2325         (while sent-via
2326           (when (and (eq (nth 1 (car sent-via)) 'unplugged)
2327                      (or (not (nth 2 (car sent-via)))
2328                          (elmo-plugged-p
2329                           (car (nth 2 (car sent-via)))
2330                           (cdr (nth 2 (car sent-via))))))
2331             (wl-append msgs (list (car msgs2)))
2332             (throw 'found t))
2333           (setq sent-via (cdr sent-via))))
2334       (setq msgs2 (cdr msgs2)))
2335     (when (> (setq len (length msgs)) 0)
2336       (if (elmo-y-or-n-p (format
2337                           "%d message(s) are in the sending queue.  Send now? "
2338                           len)
2339                          (not elmo-dop-flush-confirm) t)
2340           (progn
2341             (save-excursion
2342               (setq buffer (get-buffer-create " *wl-draft-queue-flush*"))
2343               (set-buffer buffer)
2344               (while msgs
2345                 ;; reset buffer local variables
2346                 (kill-all-local-variables)
2347                 (erase-buffer)
2348                 (setq i (+ 1 i)
2349                       failure nil)
2350                 (setq wl-sent-message-via nil)
2351                 (wl-draft-queue-info-operation (car msgs) 'load)
2352                 (elmo-message-fetch queue-folder
2353                                     (car msgs)
2354                                     (elmo-make-fetch-strategy 'entire)
2355                                     nil (current-buffer))
2356                 (condition-case err
2357                     (setq failure (funcall
2358                                    wl-draft-queue-flush-send-function
2359                                    (format "Sending (%d/%d)..." i len)))
2360 ;;;               (wl-draft-raw-send nil nil
2361 ;;;                                  (format "Sending (%d/%d)..." i len))
2362                   (error
2363                    (elmo-display-error err t)
2364                    (setq failure t))
2365                   (quit
2366                    (setq failure t)))
2367                 (if (eq wl-sent-message-modified 'requeue)
2368                     (progn
2369                       (elmo-folder-delete-messages
2370                        queue-folder (cons (car msgs) nil))
2371                       (wl-draft-queue-info-operation (car msgs) 'delete))
2372                   (unless failure
2373                     (elmo-folder-delete-messages
2374                      queue-folder (cons (car msgs) nil))
2375                     (wl-draft-queue-info-operation (car msgs) 'delete)
2376                     (setq performed (+ 1 performed))))
2377                 (setq msgs (cdr msgs)))
2378               (kill-buffer buffer)
2379               (message "%d message(s) are sent." performed)))
2380         (message "%d message(s) are remained to be sent." len))
2381       (elmo-folder-close queue-folder)
2382       len)))
2383
2384 (defun wl-jump-to-draft-buffer (&optional arg)
2385   "Jump to the draft if exists."
2386   (interactive "P")
2387   (if arg
2388       (wl-jump-to-draft-folder)
2389     (let ((draft-bufs (wl-collect-draft))
2390           buf)
2391       (cond
2392        ((null draft-bufs)
2393         (message "No draft buffer exist."))
2394        (t
2395         (setq draft-bufs
2396               (sort (mapcar 'buffer-name draft-bufs)
2397                     (function (lambda (a b)
2398                                 (not (string< a b))))))
2399         (if (setq buf (cdr (member (buffer-name)
2400                                    draft-bufs)))
2401             (setq buf (car buf))
2402           (setq buf (car draft-bufs)))
2403         (switch-to-buffer buf))))))
2404
2405 (defun wl-jump-to-draft-folder ()
2406   (let ((msgs (reverse (elmo-folder-list-messages (wl-draft-get-folder))))
2407         (mybuf (buffer-name))
2408         msg buf)
2409     (if (not msgs)
2410         (message "No draft message exist.")
2411       (if (string-match (concat "^" wl-draft-folder "/") mybuf)
2412           (setq msg (cadr (memq
2413                            (string-to-int (substring mybuf (match-end 0)))
2414                            msgs))))
2415       (or msg (setq msg (car msgs)))
2416       (if (setq buf (get-buffer (format "%s/%d" wl-draft-folder msg)))
2417           (switch-to-buffer buf)
2418         (wl-draft-reedit msg)))))
2419
2420 (defun wl-draft-highlight-and-recenter (&optional n)
2421   (interactive "P")
2422   (when wl-highlight-body-too
2423     (let ((modified (buffer-modified-p)))
2424       (unwind-protect
2425           (progn
2426             (put-text-property (point-min) (point-max) 'face nil)
2427             (wl-highlight-message (point-min) (point-max) t))
2428         (set-buffer-modified-p modified))))
2429   (static-when (featurep 'xemacs)
2430     ;; Cope with one of many XEmacs bugs that `recenter' takes
2431     ;; a long time if there are a lot of invisible text lines.
2432     (redraw-frame))
2433   (recenter n))
2434
2435 ;; insert element from history
2436 (defvar wl-draft-current-history-position nil)
2437 (defvar wl-draft-history-backup-word "")
2438
2439 (defun wl-draft-previous-history-element (n)
2440   (interactive "p")
2441   (let (bol history beg end prev new)
2442     (when (and (not (wl-draft-on-field-p))
2443                (< (point)
2444                   (save-excursion
2445                     (goto-char (point-min))
2446                     (search-forward (concat "\n" mail-header-separator "\n") nil 0)
2447                     (point)))
2448                (save-excursion
2449                  (beginning-of-line)
2450                  (while (and (looking-at "^[ \t]")
2451                              (not (= (point) (point-min))))
2452                    (forward-line -1))
2453                  (cond
2454                   ((looking-at wl-folder-complete-header-regexp)
2455                    (and (boundp 'wl-read-folder-history)
2456                         (setq history wl-read-folder-history)))
2457                   ;; ((looking-at wl-address-complete-header-regexp)
2458                   ;;  (setq history .....))
2459                   (t
2460                    nil)))
2461                (eolp))
2462       (setq bol (save-excursion (beginning-of-line) (point)))
2463       (cond ((and (or (eq last-command 'wl-draft-previous-history-element)
2464                       (eq last-command 'wl-draft-next-history-element))
2465                   wl-draft-current-history-position)
2466              (setq end (point))
2467              (or (search-backward-regexp ",[ \t]*\\(.*\\)" bol t)
2468                  (search-backward-regexp "^[ \t]\\(.*\\)" bol t)
2469                  (search-backward-regexp "^[^ \t]*: \\(.*\\)" bol t))
2470              (setq prev (match-string 1))
2471              (goto-char (match-beginning 1))
2472              (setq beg (point))
2473              (if (cond ((< n 0)
2474                         (>= (+ n wl-draft-current-history-position) 0))
2475                        ((> n 0)
2476                         (<= (+ n wl-draft-current-history-position)
2477                             (length history))))
2478                  (progn
2479                    (setq wl-draft-current-history-position
2480                          (+ n wl-draft-current-history-position))
2481                    (setq new
2482                          (nth wl-draft-current-history-position
2483                               (append (list wl-draft-history-backup-word)
2484                                       history)))
2485                    (delete-region beg end)
2486                    (insert new))
2487                (goto-char end)
2488                (cond ((< n 0)
2489                       (message "End of history; no next item"))
2490                      ((> n 0)
2491                       (message "Beginning of history; no preceding item")))))
2492             ((and (> n 0)
2493                   (save-excursion
2494                     (or (search-backward-regexp ",[ \t]*\\(.*\\)" bol t)
2495                         (search-backward-regexp "^[ \t]\\(.*\\)" bol t)
2496                         (search-backward-regexp "^[^ \t]*: \\(.*\\)" bol t)))
2497                   (car history))
2498              (setq wl-draft-current-history-position 1)
2499              (setq wl-draft-history-backup-word (match-string 1))
2500              (delete-region (match-beginning 1) (match-end 1))
2501              (insert (car history)))
2502             (t
2503              (setq wl-draft-current-history-position nil))))))
2504
2505 (defun wl-draft-next-history-element (n)
2506   (interactive "p")
2507   (wl-draft-previous-history-element (- n)))
2508
2509 ;;;; user-agent support by Sen Nagata
2510
2511 ;; this appears to be necessarily global...
2512 (defvar wl-user-agent-compose-p nil)
2513 (defvar wl-user-agent-headers-and-body-alist nil)
2514
2515 ;; this should be a generic function for mail-mode -- i wish there was
2516 ;; something like it in sendmail.el
2517 (defun wl-user-agent-insert-header (header-name header-value)
2518   "Insert HEADER-NAME w/ value HEADER-VALUE into a message."
2519   ;; it seems like overriding existing headers is acceptable -- should
2520   ;; we provide an option?
2521
2522   ;; plan was: unfold header (might be folded), remove existing value, insert
2523   ;;           new value
2524   ;; wl doesn't seem to fold header lines yet anyway :-)
2525
2526   (let ((kill-whole-line t)
2527         end-of-line)
2528     (mail-position-on-field (capitalize header-name))
2529     (setq end-of-line (point))
2530     (beginning-of-line)
2531     (re-search-forward ":" end-of-line)
2532     (insert (concat " " header-value "\n"))
2533     (kill-line)))
2534
2535 ;; this should be a generic function for mail-mode -- i wish there was
2536 ;; something like it in sendmail.el
2537 ;;
2538 ;; ** haven't dealt w/ case where the body is already set **
2539 (defun wl-user-agent-insert-body (body-text)
2540   "Insert a body of text, BODY-TEXT, into a message."
2541   ;; code defensively... :-P
2542   (goto-char (point-min))
2543   (search-forward mail-header-separator)
2544   (forward-line 1)
2545   (insert body-text))
2546
2547 ;;;###autoload
2548 (defun wl-user-agent-compose (&optional to subject other-headers continue
2549                                         switch-function yank-action
2550                                         send-actions)
2551   "Support the `compose-mail' interface for wl.
2552 Only support for TO, SUBJECT, and OTHER-HEADERS has been implemented.
2553 Support for CONTINUE, YANK-ACTION, and SEND-ACTIONS has not
2554 been implemented yet.  Partial support for SWITCH-FUNCTION now supported."
2555
2556   (unless (featurep 'wl)
2557     (require 'wl))
2558   (or switch-function
2559       (setq switch-function 'keep))
2560   ;; protect these -- to and subject get bound at some point, so it looks
2561   ;; to be necessary to protect the values used w/in
2562   (let ((wl-user-agent-headers-and-body-alist other-headers)
2563         (wl-draft-use-frame (eq switch-function 'switch-to-buffer-other-frame))
2564         (wl-draft-buffer-style switch-function))
2565     (if to
2566         (if (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
2567                                    'ignore-case)
2568             (setcdr
2569              (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
2570                                     'ignore-case)
2571              to)
2572           (setq wl-user-agent-headers-and-body-alist
2573                 (cons (cons "to" to)
2574                       wl-user-agent-headers-and-body-alist))))
2575     (if subject
2576         (if (wl-string-match-assoc "subject"
2577                                    wl-user-agent-headers-and-body-alist
2578                                    'ignore-case)
2579             (setcdr
2580              (wl-string-match-assoc "subject"
2581                                     wl-user-agent-headers-and-body-alist
2582                                     'ignore-case)
2583              subject)
2584           (setq wl-user-agent-headers-and-body-alist
2585                 (cons (cons "subject" subject)
2586                       wl-user-agent-headers-and-body-alist))))
2587     ;; i think this is what we want to use...
2588     (unwind-protect
2589         (progn
2590           ;; tell the hook-function to do its stuff
2591           (setq wl-user-agent-compose-p t)
2592           ;; because to get the hooks working, wl-draft has to think it has
2593           ;; been called interactively
2594           (call-interactively 'wl-draft))
2595       (setq wl-user-agent-compose-p nil))))
2596
2597 (defun wl-user-agent-compose-internal ()
2598   "Manipulate headers and/or a body of a draft message."
2599   ;; being called from wl-user-agent-compose?
2600   (if wl-user-agent-compose-p
2601       (progn
2602         ;; insert headers
2603         (let ((headers wl-user-agent-headers-and-body-alist)
2604               (case-fold-search t))
2605           (while headers
2606             ;; skip body
2607             (if (not (string-match "^body$" (car (car headers))))
2608                 (wl-user-agent-insert-header
2609                  (car (car headers)) (cdr (car headers)))
2610               t)
2611             (setq headers (cdr headers))))
2612         ;; highlight headers (from wl-draft in wl-draft.el)
2613         (wl-highlight-headers 'for-draft)
2614         ;; insert body
2615         (if (wl-string-match-assoc "body" wl-user-agent-headers-and-body-alist
2616                                    'ignore-case)
2617             (wl-user-agent-insert-body
2618              (cdr (wl-string-match-assoc
2619                    "body"
2620                    wl-user-agent-headers-and-body-alist 'ignore-case)))))
2621     t))
2622
2623 (require 'product)
2624 (product-provide (provide 'wl-draft) (require 'wl-version))
2625
2626 ;;; wl-draft.el ends here