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