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