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