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