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