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