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