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