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