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