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