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