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