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