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