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