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