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