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