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