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