d8f2e41b5d0a14ad76ad1fa19c70f23334065540
[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 (defvar wl-draft-buf-name "Draft")
53 (defvar wl-draft-cite-function 'wl-default-draft-cite)
54 (defvar wl-draft-buffer-file-name nil)
55 (defvar wl-draft-field-completion-list nil)
56 (defvar wl-draft-verbose-send t)
57 (defvar wl-draft-verbose-msg nil)
58 (defvar wl-draft-queue-flushing nil)
59 (defvar wl-draft-config-variables nil)
60 (defvar wl-draft-config-exec-flag t)
61 (defvar wl-draft-buffer-cur-summary-buffer nil)
62 (defvar wl-draft-clone-local-variable-regexp "^\\(wl\\|mime\\)")
63 (defvar wl-draft-sendlog-filename "sendlog")
64 (defvar wl-draft-queue-save-filename "qinfo")
65 (defvar wl-draft-config-save-filename "config")
66 (defvar wl-draft-queue-flush-send-function 'wl-draft-dispatch-message)
67 (defvar wl-sent-message-via nil)
68 (defvar wl-sent-message-modified nil)
69 (defvar wl-draft-fcc-list nil)
70 (defvar wl-draft-reedit nil)
71 (defvar wl-draft-reply-buffer nil)
72 (defvar wl-draft-forward nil)
73
74 (defvar wl-draft-config-sub-func-alist
75   '((body        . wl-draft-config-sub-body)
76     (top         . wl-draft-config-sub-top)
77     (bottom      . wl-draft-config-sub-bottom)
78     (header      . wl-draft-config-sub-header)
79     (body-file   . wl-draft-config-sub-body-file)
80     (top-file    . wl-draft-config-sub-top-file)
81     (bottom-file . wl-draft-config-sub-bottom-file)
82     (header-file . wl-draft-config-sub-header-file)
83     (template    . wl-draft-config-sub-template)
84     (x-face      . wl-draft-config-sub-x-face)))
85
86 (make-variable-buffer-local 'wl-draft-buffer-file-name)
87 (make-variable-buffer-local 'wl-draft-buffer-cur-summary-buffer)
88 (make-variable-buffer-local 'wl-draft-config-variables)
89 (make-variable-buffer-local 'wl-draft-config-exec-flag)
90 (make-variable-buffer-local 'wl-sent-message-via)
91 (make-variable-buffer-local 'wl-draft-fcc-list)
92 (make-variable-buffer-local 'wl-draft-reply-buffer)
93
94 (defmacro wl-smtp-extension-bind (&rest body)
95   (` (let* ((smtp-sasl-mechanisms
96              (if wl-smtp-authenticate-type
97                  (mapcar 'upcase
98                          (if (listp wl-smtp-authenticate-type)
99                              wl-smtp-authenticate-type
100                            (list wl-smtp-authenticate-type)))))
101             (smtp-use-sasl (and smtp-sasl-mechanisms t))
102             (smtp-use-starttls wl-smtp-connection-type)
103             smtp-sasl-user-name smtp-sasl-properties sasl-read-passphrase)
104        (if (and (string= (car smtp-sasl-mechanisms) "DIGEST-MD5")
105                 ;; sendmail bug?
106                 (string-match "^\\([^@]*\\)@\\([^@]*\\)"
107                               wl-smtp-posting-user))
108            (setq smtp-sasl-user-name (match-string 1 wl-smtp-posting-user)
109                  smtp-sasl-properties (list 'realm 
110                                             (match-string 2 wl-smtp-posting-user)))
111          (setq smtp-sasl-user-name wl-smtp-posting-user
112                smtp-sasl-properties nil))
113        (setq sasl-read-passphrase
114              (function
115               (lambda (prompt)
116                 (elmo-get-passwd
117                  (format "%s@%s"
118                          smtp-sasl-user-name
119                          smtp-server)))))
120        (,@ body))))
121
122 (defun wl-draft-insert-date-field ()
123   "Insert Date field."
124   (insert "Date: " (wl-make-date-string) "\n"))
125
126 (defun wl-draft-insert-from-field ()
127   "Insert From field."
128   ;; Put the "From:" field in unless for some odd reason
129   ;; they put one in themselves.
130   (let* ((login (or user-mail-address (user-login-name)))
131          (fullname (user-full-name)))
132     (cond ((eq mail-from-style 'angles)
133            (insert "From: " fullname)
134            (let ((fullname-start (+ (point-min) (length "From: ")))
135                  (fullname-end (point-marker)))
136              (goto-char fullname-start)
137              ;; Look for a character that cannot appear unquoted
138              ;; according to RFC 822.
139              (if (re-search-forward "[^- !#-'*+/-9=?A-Z^-~]"
140                                     fullname-end 1)
141                  (progn
142                    ;; Quote fullname, escaping specials.
143                    (goto-char fullname-start)
144                    (insert "\"")
145                    (while (re-search-forward "[\"\\]"
146                                              fullname-end 1)
147                      (replace-match "\\\\\\&" t))
148                    (insert "\""))))
149            (insert " <" login ">\n"))
150           ((eq mail-from-style 'parens)
151            (insert "From: " login " (")
152            (let ((fullname-start (point)))
153              (insert fullname)
154              (let ((fullname-end (point-marker)))
155                (goto-char fullname-start)
156                ;; RFC 822 says \ and nonmatching parentheses
157                ;; must be escaped in comments.
158                ;; Escape every instance of ()\ ...
159                (while (re-search-forward "[()\\]" fullname-end 1)
160                  (replace-match "\\\\\\&" t))
161                ;; ... then undo escaping of matching parentheses,
162                ;; including matching nested parentheses.
163                (goto-char fullname-start)
164                (while (re-search-forward
165                        "\\(\\=\\|[^\\]\\(\\\\\\\\\\)*\\)\\\\(\\(\\([^\\]\\|\\\\\\\\\\)*\\)\\\\)"
166                        fullname-end 1)
167                  (replace-match "\\1(\\3)" t)
168                  (goto-char fullname-start))))
169            (insert ")\n"))
170           ((not mail-from-style)
171            (insert "From: " login "\n")))))
172
173 (defun wl-draft-insert-x-face-field ()
174   "Insert X-Face header."
175   (interactive)
176   (if (not (file-exists-p wl-x-face-file))
177       (error "File %s does not exist" wl-x-face-file)
178     (beginning-of-buffer)
179     (search-forward mail-header-separator nil t)
180     (beginning-of-line)
181     (wl-draft-insert-x-face-field-here)
182     (run-hooks 'wl-draft-insert-x-face-field-hook))) ; highlight it if you want.
183
184 (defun wl-draft-insert-x-face-field-here ()
185   "Insert X-Face field at point."
186   (let ((x-face-string (elmo-get-file-string wl-x-face-file)))
187     (when (string-match "^[ \t]*" x-face-string)
188       (setq x-face-string (substring x-face-string (match-end 0))))
189     (insert "X-Face: " x-face-string))
190   (when (not (= (preceding-char) ?\n))  ; for chomped (choped) x-face-string
191     (insert ?\n))
192   ;; Insert X-Face-Version: field
193   (when (and (fboundp 'x-face-insert-version-header)
194              (boundp 'x-face-add-x-face-version-header)
195              x-face-add-x-face-version-header)
196     (x-face-insert-version-header)))
197
198 (defun wl-draft-setup ()
199   (let ((field wl-draft-fields)
200         ret-val)
201     (while field
202       (setq ret-val (append ret-val
203                             (list (cons (concat (car field) " ")
204                                         (concat (car field) " ")))))
205       (setq field (cdr field)))
206     (setq wl-draft-field-completion-list ret-val)))
207
208 (defun wl-draft-make-mail-followup-to (recipients)
209   (if (elmo-list-member
210        (or wl-user-mail-address-list
211            (list (wl-address-header-extract-address wl-from)))
212        recipients)
213       (let ((rlist (elmo-list-delete
214                     (or wl-user-mail-address-list
215                         (list (wl-address-header-extract-address wl-from)))
216                     (copy-sequence recipients))))
217         (if (elmo-list-member rlist (mapcar 'downcase
218                                             wl-subscribed-mailing-list))
219             rlist
220           (append rlist (list (wl-address-header-extract-address
221                                wl-from)))))
222     recipients))
223
224 (defun wl-draft-delete-myself-from-cc (to cc)
225   (let ((myself (or wl-user-mail-address-list
226                     (list (wl-address-header-extract-address wl-from)))))
227     (cond (wl-draft-always-delete-myself ; always-delete option
228            (elmo-list-delete myself cc))
229           ((elmo-list-member (append to cc) ; subscribed mailing-list
230                              (mapcar 'downcase wl-subscribed-mailing-list))
231            (elmo-list-delete myself cc))
232           (t cc))))
233
234 (defun wl-draft-forward (original-subject summary-buf)
235   (let (references)
236     (with-current-buffer (wl-message-get-original-buffer)
237       (setq references (nconc
238                         (std11-field-bodies '("References" "In-Reply-To"))
239                         (list (std11-field-body "Message-Id"))))
240       (setq references (delq nil references)
241             references (mapconcat 'identity references " ")
242             references (wl-draft-parse-msg-id-list-string references)
243             references (wl-delete-duplicates references)
244             references (when references
245                          (mapconcat 'identity references "\n\t"))))
246     (wl-draft "" (concat "Forward: " original-subject)
247               nil nil references nil nil nil nil nil nil summary-buf))
248   (goto-char (point-max))
249   (wl-draft-insert-message)
250   (mail-position-on-field "To"))
251
252 (defun wl-draft-strip-subject-re (subject)
253   "Remove \"Re:\" from subject lines. Shamelessly copied from Gnus"
254   (if (string-match wl-subject-prefix-regexp subject)
255       (substring subject (match-end 0))
256     subject))
257
258 (defun wl-draft-reply-list-symbol (with-arg)
259   "Return symbol `wl-draft-reply-*-argument-list' match condition.
260 Check WITH-ARG and From: field."
261   (if (wl-address-user-mail-address-p (or (elmo-field-body "From") ""))
262       (if with-arg
263           'wl-draft-reply-myself-with-argument-list
264         'wl-draft-reply-myself-without-argument-list)
265     (if with-arg
266         'wl-draft-reply-with-argument-list
267       'wl-draft-reply-without-argument-list)))
268
269 (defun wl-draft-reply (buf with-arg summary-buf)
270   "Reply to BUF buffer message.
271 Reply to author if WITH-ARG is non-nil."
272 ;;;(save-excursion
273   (let (r-list
274         to mail-followup-to cc subject in-reply-to references newsgroups
275         from to-alist cc-alist decoder)
276     (set-buffer buf)
277     (setq r-list (symbol-value (wl-draft-reply-list-symbol with-arg)))
278     (catch 'done
279       (while r-list
280         (when (let ((condition (car (car r-list))))
281                 (cond ((stringp condition)
282                        (std11-field-body condition))
283                       ((listp condition)
284                        (catch 'done
285                          (while condition
286                            (if (not (std11-field-body (car condition)))
287                                (throw 'done nil))
288                            (setq condition (cdr condition)))
289                          t))
290                       ((symbolp condition)
291                        (funcall condition))))
292           (let ((r-to-list (nth 0 (cdr (car r-list))))
293                 (r-cc-list (nth 1 (cdr (car r-list))))
294                 (r-ng-list (nth 2 (cdr (car r-list)))))
295             (when (and (member "Followup-To" r-ng-list)
296                        (string= (std11-field-body "Followup-To") "poster"))
297               (setq r-to-list (cons "From" r-to-list))
298               (setq r-ng-list (delete "Followup-To" (copy-sequence r-ng-list))))
299             (setq to (wl-concat-list (cons to
300                                            (elmo-multiple-fields-body-list
301                                             r-to-list))
302                                      ","))
303             (setq cc (wl-concat-list (cons cc
304                                            (elmo-multiple-fields-body-list
305                                             r-cc-list))
306                                      ","))
307             (setq newsgroups (wl-concat-list (cons newsgroups
308                                                    (std11-field-bodies
309                                                     r-ng-list))
310                                              ",")))
311           (throw 'done nil))
312         (setq r-list (cdr r-list)))
313       (error "No match field: check your `%s'"
314              (symbol-name (wl-draft-reply-list-symbol with-arg))))
315     (setq subject (std11-field-body "Subject"))
316     (setq to (wl-parse-addresses to)
317           cc (wl-parse-addresses cc))
318     (with-temp-buffer                   ; to keep raw buffer unibyte.
319       (elmo-set-buffer-multibyte default-enable-multibyte-characters)
320       (setq decoder (mime-find-field-decoder 'Subject 'plain))
321       (setq subject (if (and subject decoder)
322                         (funcall decoder subject) subject))
323       (setq to-alist 
324             (mapcar
325              (lambda (addr)
326                (setq decoder (mime-find-field-decoder 'To 'plain))
327                (cons (nth 1 (std11-extract-address-components addr))
328                      (if decoder (funcall decoder addr) addr)))
329              to))
330       (setq cc-alist 
331             (mapcar
332              (lambda (addr)
333                (setq decoder (mime-find-field-decoder 'Cc 'plain))
334                (cons (nth 1 (std11-extract-address-components addr))
335                      (if decoder (funcall decoder addr) addr)))
336              cc)))
337     (and wl-reply-subject-prefix
338          (setq subject (concat wl-reply-subject-prefix
339                                (wl-draft-strip-subject-re
340                                 (or subject "")))))
341     (setq in-reply-to (std11-field-body "Message-Id"))
342     (setq references (nconc
343                       (std11-field-bodies '("References" "In-Reply-To"))
344                       (list in-reply-to)))
345     (setq to (delq nil (mapcar 'car to-alist)))
346     (setq cc (delq nil (mapcar 'car cc-alist)))
347     ;; if subscribed mailing list is contained in cc or to
348     ;; and myself is contained in cc,
349     ;; delete myself from cc.
350     (setq cc (wl-draft-delete-myself-from-cc to cc))
351     (when wl-insert-mail-followup-to
352       (setq mail-followup-to
353             (wl-draft-make-mail-followup-to (append to cc)))
354       (setq mail-followup-to (wl-delete-duplicates mail-followup-to nil t)))
355     (setq newsgroups (wl-parse newsgroups
356                                "[ \t\f\r\n,]*\\([^ \t\f\r\n,]+\\)")
357           newsgroups (wl-delete-duplicates newsgroups)
358           newsgroups (if newsgroups (mapconcat 'identity newsgroups ",")))
359     (setq to (wl-delete-duplicates to nil t))
360     (setq cc (wl-delete-duplicates
361               (append (wl-delete-duplicates cc nil t)
362                       to (copy-sequence to))
363               t t))
364     (and to (setq to (mapconcat
365                       '(lambda (addr)
366                          (if wl-draft-reply-use-address-with-full-name
367                              (or (cdr (assoc addr to-alist)) addr)
368                            addr))
369                       to ",\n\t")))
370     (and cc (setq cc (mapconcat
371                       '(lambda (addr)
372                          (if wl-draft-reply-use-address-with-full-name
373                              (or (cdr (assoc addr cc-alist)) addr)
374                            addr))
375                       cc ",\n\t")))
376     (and mail-followup-to
377          (setq mail-followup-to
378                (mapconcat
379                 '(lambda (addr)
380                    (if wl-draft-reply-use-address-with-full-name
381                        (or (cdr (assoc addr (append to-alist cc-alist))) addr)
382                      addr))
383                 mail-followup-to ",\n\t")))
384     (and (null to) (setq to cc cc nil))
385     (setq references (delq nil references)
386           references (mapconcat 'identity references " ")
387           references (wl-draft-parse-msg-id-list-string references)
388           references (wl-delete-duplicates references)
389           references (if references
390                          (mapconcat 'identity references "\n\t")))
391     (wl-draft
392      to subject in-reply-to cc references newsgroups mail-followup-to
393      nil nil nil nil summary-buf)
394     (setq wl-draft-reply-buffer buf))
395   (run-hooks 'wl-reply-hook))
396
397 (defun wl-draft-add-references ()
398   (let* ((mes-id (save-excursion
399                    (set-buffer mail-reply-buffer)
400                    (std11-field-body "message-id")))
401          (ref (std11-field-body "References"))
402          (ref-list nil) (st nil))
403     (when (and mes-id ref)
404       (while (string-match "<[^>]+>" ref st)
405         (setq ref-list
406               (cons (substring ref (match-beginning 0) (setq st (match-end 0)))
407                     ref-list)))
408       (when (and ref-list
409                  (member mes-id ref-list))
410         (setq mes-id nil)))
411     (when mes-id
412       (save-excursion
413         (when (mail-position-on-field "References")
414           (forward-line)
415           (while (looking-at "^[ \t]")
416             (forward-line))
417           (setq mes-id (concat "\t" mes-id "\n")))
418         (insert mes-id))
419       t)))
420
421 (defun wl-draft-yank-from-mail-reply-buffer (decode-it
422                                              &optional ignored-fields)
423   (interactive)
424   (save-restriction
425     (narrow-to-region (point)(point))
426     (insert
427      (with-current-buffer mail-reply-buffer
428        (when decode-it
429          (decode-mime-charset-region (point-min) (point-max)
430                                      wl-mime-charset))
431        (buffer-substring-no-properties
432         (point-min) (point-max))))
433     (when ignored-fields
434       (goto-char (point-min))
435       (wl-draft-delete-fields ignored-fields))
436     (goto-char (point-max))
437     (push-mark)
438     (goto-char (point-min)))
439   (let ((beg (point)))
440     (cond (mail-citation-hook (run-hooks 'mail-citation-hook))
441           (mail-yank-hooks (run-hooks 'mail-yank-hooks))
442           (wl-draft-cite-function (funcall wl-draft-cite-function))) ; default cite
443     (run-hooks 'wl-draft-cited-hook)
444     (when (and wl-draft-add-references
445                (wl-draft-add-references))
446       (wl-highlight-headers 'for-draft)) ; highlight when added References:
447     (when wl-highlight-body-too
448       (wl-highlight-body-region beg (point-max)))))
449
450 (defun wl-draft-confirm ()
451   "Confirm send message."
452   (interactive)
453   (y-or-n-p (format "Send current draft as %s? "
454                     (cond ((and (wl-message-mail-p) (wl-message-news-p))
455                            "Mail and News")
456                           ((wl-message-mail-p) "Mail")
457                           ((wl-message-news-p) "News")))))
458
459 (defun wl-message-news-p ()
460   "If exist valid Newsgroups field, return non-nil."
461   (std11-field-body "Newsgroups"))
462
463 (defun wl-message-field-exists-p (field)
464   "If FIELD exist and FIELD value is not empty, return non-nil."
465   (let ((value (std11-field-body field)))
466     (and value
467          (not (string= value "")))))
468
469 (defun wl-message-mail-p ()
470   "If exist To, Cc or Bcc field, return non-nil."
471   (or (wl-message-field-exists-p "To")
472       (wl-message-field-exists-p "Resent-to")
473       (wl-message-field-exists-p "Cc")
474       (wl-message-field-exists-p "Bcc")
475 ;;; This may be needed..
476 ;;;   (wl-message-field-exists-p "Fcc")
477       ))
478
479 (defun wl-draft-open-file (&optional file)
480   "Open FILE for edit."
481   (interactive)
482 ;;;(interactive "*fFile to edit: ")
483   (wl-draft-edit-string (elmo-get-file-string
484                          (or file
485                              (read-file-name "File to edit: "
486                                              (or wl-tmp-dir "~/"))))))
487
488 (defun wl-draft-edit-string (string)
489   (let ((cur-buf (current-buffer))
490         (tmp-buf (get-buffer-create " *wl-draft-edit-string*"))
491         to subject in-reply-to cc references newsgroups mail-followup-to
492         content-type content-transfer-encoding from
493         body-beg buffer-read-only)
494     (set-buffer tmp-buf)
495     (erase-buffer)
496     (insert string)
497     (setq to (std11-field-body "To"))
498     (setq to (and to
499                   (eword-decode-string
500                    (decode-mime-charset-string
501                     to
502                     wl-mime-charset))))
503     (setq subject (std11-field-body "Subject"))
504     (setq subject (and subject
505                        (eword-decode-string
506                         (decode-mime-charset-string
507                          subject
508                          wl-mime-charset))))
509     (setq from (std11-field-body "From")
510           from (and from
511                     (eword-decode-string
512                      (decode-mime-charset-string
513                       from
514                       wl-mime-charset))))
515     (setq in-reply-to (std11-field-body "In-Reply-To"))
516     (setq cc (std11-field-body "Cc"))
517     (setq cc (and cc
518                   (eword-decode-string
519                    (decode-mime-charset-string
520                     cc
521                     wl-mime-charset))))
522     (setq references (std11-field-body "References"))
523     (setq newsgroups (std11-field-body "Newsgroups"))
524     (setq mail-followup-to (std11-field-body "Mail-Followup-To"))
525     (setq content-type (std11-field-body "Content-Type"))
526     (setq content-transfer-encoding (std11-field-body "Content-Transfer-Encoding"))
527     (goto-char (point-min))
528     (or (re-search-forward "\n\n" nil t)
529         (search-forward (concat mail-header-separator "\n") nil t))
530     (unwind-protect
531         (set-buffer
532          (wl-draft to subject in-reply-to cc references newsgroups
533                    mail-followup-to
534                    content-type content-transfer-encoding
535                    (buffer-substring (point) (point-max))
536                    'edit-again nil
537                    (if (member (nth 1 (std11-extract-address-components from))
538                                wl-user-mail-address-list)
539                        from)))
540       (and to (mail-position-on-field "To"))
541       (delete-other-windows)
542       (kill-buffer tmp-buf)))
543   (setq buffer-read-only nil) ;;??
544   (run-hooks 'wl-draft-reedit-hook))
545
546 (defun wl-draft-insert-current-message (dummy)
547   (interactive)
548   (let (original-buffer
549         mail-reply-buffer
550         mail-citation-hook mail-yank-hooks
551         wl-draft-add-references wl-draft-cite-function)
552     (with-current-buffer wl-draft-buffer-cur-summary-buffer
553       (with-current-buffer wl-message-buffer
554         (setq original-buffer (wl-message-get-original-buffer))
555         (if (zerop
556              (with-current-buffer original-buffer
557                (buffer-size)))
558             (error "No current message"))))
559     (setq mail-reply-buffer original-buffer)
560     (wl-draft-yank-from-mail-reply-buffer
561      nil
562      wl-ignored-forwarded-headers)))
563
564 (defun wl-draft-insert-get-message (dummy)
565   (let ((fld (completing-read
566               "Folder name: "
567               (if (memq 'read-folder wl-use-folder-petname)
568                   (wl-folder-get-entity-with-petname)
569                 wl-folder-entity-hashtb)
570               nil nil wl-default-spec
571               'wl-read-folder-hist))
572         (number (call-interactively
573                  (function (lambda (num)
574                              (interactive "nNumber: ")
575                              num))))
576         (mail-reply-buffer (get-buffer-create "*wl-draft-insert-get-message*"))
577         mail-citation-hook mail-yank-hooks
578         wl-draft-cite-function)
579     (unwind-protect
580         (progn
581           (elmo-message-fetch (wl-folder-get-elmo-folder fld)
582                               number
583                               ;; No cache.
584                               (elmo-make-fetch-strategy 'entire)
585                               nil mail-reply-buffer)
586           (wl-draft-yank-from-mail-reply-buffer nil))
587       (kill-buffer mail-reply-buffer))))
588
589 ;;
590 ;; default body citation func
591 ;;
592 (defun wl-default-draft-cite ()
593   (let ((mail-yank-ignored-headers "[^:]+:")
594         (mail-yank-prefix "> ")
595         (summary-buf wl-current-summary-buffer)
596         (message-buf (get-buffer (wl-current-message-buffer)))
597         from date cite-title num entity)
598     (if (and summary-buf
599              (buffer-live-p summary-buf)
600              message-buf
601              (buffer-live-p message-buf))
602         (progn
603           (with-current-buffer summary-buf
604             (setq num (save-excursion
605                         (set-buffer message-buf)
606                         wl-message-buffer-cur-number))
607             (setq entity (elmo-msgdb-overview-get-entity
608                           num (wl-summary-buffer-msgdb)))
609             (setq date (elmo-msgdb-overview-entity-get-date entity))
610             (setq from (elmo-msgdb-overview-entity-get-from entity)))
611           (setq cite-title (format "At %s,\n%s wrote:"
612                                    (or date "some time ago")
613                                    (wl-summary-from-func-internal
614                                     (or from "you"))))))
615     (and cite-title
616          (insert cite-title "\n"))
617     (mail-indent-citation)))
618
619 (defvar wl-draft-buffer nil "Draft buffer to yank content")
620 (defun wl-draft-yank-to-draft-buffer (buffer)
621   "Yank BUFFER content to `wl-draft-buffer'."
622   (set-buffer wl-draft-buffer)
623   (let ((mail-reply-buffer buffer))
624     (wl-draft-yank-from-mail-reply-buffer nil)
625     (kill-buffer buffer)))
626
627 (defun wl-draft-yank-original (&optional arg)
628   "Yank original message."
629   (interactive "P")
630   (if arg
631       (let (buf mail-reply-buffer)
632         (elmo-set-work-buf
633          (yank)
634          (setq buf (current-buffer)))
635         (setq mail-reply-buffer buf)
636         (wl-draft-yank-from-mail-reply-buffer nil))
637     (wl-draft-yank-current-message-entity)))
638
639 (defun wl-draft-hide (editing-buffer)
640   "Hide the editing draft buffer if possible."
641   (interactive)
642   (when (and editing-buffer
643              (buffer-live-p editing-buffer))
644     (set-buffer editing-buffer)
645     (let ((sum-buf wl-draft-buffer-cur-summary-buffer)
646           fld-buf sum-win fld-win)
647       (if (and wl-draft-use-frame
648                (> (length (visible-frame-list)) 1))
649           ;; hide draft frame
650           (delete-frame)
651         ;; hide draft window
652         (or (one-window-p)
653             (delete-window)))
654       ;; stay folder window if required
655       (when wl-stay-folder-window
656         (if (setq fld-buf (get-buffer wl-folder-buffer-name))
657             (if (setq fld-win (get-buffer-window fld-buf))
658                 (select-window fld-win)
659               (if wl-draft-resume-folder-window ;; resume folder window
660                   (switch-to-buffer fld-buf)))))
661       (if (buffer-live-p sum-buf)
662           (if (setq sum-win (get-buffer-window sum-buf t))
663               ;; if Summary is on the frame, select it.
664               (select-window sum-win)
665             ;; if summary is not on the frame, switch to it.
666             (if (and wl-stay-folder-window
667                      (or wl-draft-resume-folder-window fld-win))
668                 (wl-folder-select-buffer sum-buf)
669               (switch-to-buffer sum-buf)))))))
670
671 (defun wl-draft-delete (editing-buffer)
672   "kill the editing draft buffer and delete the file corresponds to it."
673   (save-excursion
674     (when editing-buffer
675       (set-buffer editing-buffer)
676       (if wl-draft-buffer-file-name
677           (progn
678             (if (file-exists-p wl-draft-buffer-file-name)
679                 (delete-file wl-draft-buffer-file-name))
680             (let ((msg (and wl-draft-buffer-file-name
681                             (string-match "[0-9]+$" wl-draft-buffer-file-name)
682                             (string-to-int
683                              (match-string 0 wl-draft-buffer-file-name)))))
684               (wl-draft-config-info-operation msg 'delete))))
685       (set-buffer-modified-p nil)               ; force kill
686       (kill-buffer editing-buffer))))
687
688 (defun wl-draft-kill (&optional force-kill)
689   "Kill current draft buffer and quit editing."
690   (interactive "P")
691   (save-excursion
692     (when (and (or (eq major-mode 'wl-draft-mode)
693                    (eq major-mode 'mail-mode))
694                (or force-kill
695                    (y-or-n-p "Kill Current Draft?")))
696       (let ((cur-buf (current-buffer)))
697         (wl-draft-hide cur-buf)
698         (wl-draft-delete cur-buf)))
699     (message "")))
700
701 (defun wl-draft-fcc ()
702   "Add a new Fcc field, with file name completion."
703   (interactive)
704   (or (mail-position-on-field "fcc" t)  ;Put new field after exiting Fcc.
705       (mail-position-on-field "to"))
706   (insert "\nFcc: "))
707
708 ;; function for wl-sent-message-via
709
710 (defmacro wl-draft-sent-message-p (type)
711   (` (eq (nth 1 (assq (, type) wl-sent-message-via)) 'sent)))
712
713 (defmacro wl-draft-set-sent-message (type result &optional server-port)
714   (` (let ((element (assq (, type) wl-sent-message-via)))
715        (if element
716            (unless (eq (nth 1 element) (, result))
717              (setcdr element (list (, result) (, server-port)))
718              (setq wl-sent-message-modified t))
719          (push (list (, type) (, result) (, server-port)) wl-sent-message-via)
720          (setq wl-sent-message-modified t)))))
721
722 (defun wl-draft-sent-message-results ()
723   (let ((results wl-sent-message-via)
724         unplugged-via sent-via)
725     (while results
726       (cond ((eq (nth 1 (car results)) 'unplugged)
727              (push (caar results) unplugged-via))
728             ((eq (nth 1 (car results)) 'sent)
729              (push (caar results) sent-via)))
730       (setq results (cdr results)))
731     (list unplugged-via sent-via)))
732
733 (defun wl-draft-write-sendlog (status proto server to id)
734   "Write send log file, if `wl-draft-sendlog' is non-nil."
735   (when wl-draft-sendlog
736     (save-excursion
737       (let* ((tmp-buf (get-buffer-create " *wl-draft-sendlog*"))
738              (filename (expand-file-name wl-draft-sendlog-filename
739                                          elmo-msgdb-dir))
740              (filesize (nth 7 (file-attributes filename)))
741              (server (if server (concat " server=" server) ""))
742              (to (if to (cond
743                          ((memq proto '(fcc queue))
744                           (format " folder=\"%s\"" to))
745                          ((eq proto 'nntp)
746                           (format " ng=<%s>" to))
747                          (t
748                           (concat " to="
749                                   (mapconcat
750                                    'identity
751                                    (mapcar '(lambda(x) (format "<%s>" x)) to)
752                                    ","))))
753                    ""))
754              (id (if id (concat " id=" id) ""))
755              (time (wl-sendlog-time)))
756         (set-buffer tmp-buf)
757         (erase-buffer)
758         (insert (format "%s proto=%s stat=%s%s%s%s\n"
759                         time proto status server to id))
760         (if (and wl-draft-sendlog-max-size filesize
761                  (> filesize wl-draft-sendlog-max-size))
762             (rename-file filename (concat filename ".old") t))
763         (if (file-writable-p filename)
764             (write-region (point-min) (point-max)
765                           filename t 'no-msg)
766           (message (format "%s is not writable." filename)))
767         (kill-buffer tmp-buf)))))
768
769 (defun wl-draft-get-header-delimiter (&optional delete)
770   ;; If DELETE is non-nil, replace the header delimiter with a blank line
771   (let (delimline)
772     (goto-char (point-min))
773     (when (re-search-forward
774            (concat "^" (regexp-quote mail-header-separator) "$\\|^$") nil t)
775       (replace-match "")
776       (if delete
777           (forward-char -1))
778       (setq delimline (point-marker)))
779     delimline))
780
781 (defun wl-draft-send-mail-with-qmail ()
782   "Pass the prepared message buffer to qmail-inject.
783 Refer to the documentation for the variable `send-mail-function'
784 to find out how to use this."
785   (if (and wl-draft-qmail-send-plugged
786            (not (elmo-plugged-p)))
787       (wl-draft-set-sent-message 'mail 'unplugged)
788     ;; send the message
789     (let ((id (std11-field-body "Message-ID"))
790           (to (std11-field-body "To")))
791       (case
792           (as-binary-process
793            (apply
794             'call-process-region 1 (point-max) wl-qmail-inject-program
795             nil nil nil
796             wl-qmail-inject-args))
797         ;; qmail-inject doesn't say anything on it's stdout/stderr,
798         ;; we have to look at the retval instead
799         (0   (progn
800                (wl-draft-set-sent-message 'mail 'sent)
801                (wl-draft-write-sendlog 'ok 'qmail nil (list to) id)))
802         (1   (error "qmail-inject reported permanent failure"))
803         (111 (error "qmail-inject reported transient failure"))
804         ;; should never happen
805         (t   (error "qmail-inject reported unknown failure"))))))
806
807 (defun wl-draft-parse-msg-id-list-string (string)
808   "Get msg-id list from STRING."
809   (let (msg-id-list)
810     (dolist (parsed-id (std11-parse-msg-ids-string string))
811       (when (eq (car parsed-id) 'msg-id)
812         (setq msg-id-list (cons (std11-msg-id-string parsed-id)
813                                 msg-id-list))))
814     (nreverse msg-id-list)))
815
816 (defun wl-draft-parse-mailbox-list (field &optional remove-group-list)
817   "Get mailbox list of FIELD from current buffer.
818 The buffer is expected to be narrowed to just the headers of the message.
819 If optional argument REMOVE-GROUP-LIST is non-nil, remove group list content
820 from current buffer."
821   (save-excursion
822     (let ((case-fold-search t)
823           (inhibit-read-only t)
824           addresses address
825           mailbox-list beg seq has-group-list)
826       (goto-char (point-min))
827       (while (re-search-forward (concat "^" (regexp-quote field) "[\t ]*:")
828                                 nil t)
829         (setq beg (point))
830         (re-search-forward "^[^ \t]" nil 'move)
831         (beginning-of-line)
832         (skip-chars-backward "\n")
833         (setq seq (std11-lexical-analyze
834                    (buffer-substring-no-properties beg (point))))
835         (setq addresses (std11-parse-addresses seq))
836         (while addresses
837           (cond ((eq (car (car addresses)) 'group)
838                  (setq has-group-list t)
839                  (setq mailbox-list
840                        (nconc mailbox-list
841                               (mapcar
842                                'std11-address-string
843                                (nth 2 (car addresses))))))
844                 ((eq (car (car addresses)) 'mailbox)
845                  (setq address (nth 1 (car addresses)))
846                  (setq mailbox-list
847                        (nconc mailbox-list
848                               (list
849                                (std11-addr-to-string
850                                 (if (eq (car address) 'phrase-route-addr)
851                                     (nth 2 address)
852                                   (cdr address))))))))
853           (setq addresses (cdr addresses)))
854         (when (and remove-group-list has-group-list)
855           (delete-region beg (point))
856           (insert (wl-address-string-without-group-list-contents seq))))
857       mailbox-list)))
858
859 (defun wl-draft-deduce-address-list (buffer header-start header-end)
860   "Get address list suitable for smtp RCPT TO:<address>.
861 Group list content is removed if `wl-draft-remove-group-list-contents' is
862 non-nil."
863   (let ((fields        '("to" "cc" "bcc"))
864         (resent-fields '("resent-to" "resent-cc" "resent-bcc"))
865         (case-fold-search t)
866         addrs recipients)
867     (save-excursion
868       (save-restriction
869         (narrow-to-region header-start header-end)
870         (goto-char (point-min))
871         (save-excursion
872           (if (re-search-forward "^resent-to[\t ]*:" nil t)
873               (setq fields resent-fields)))
874         (while fields
875           (setq recipients
876                 (nconc recipients
877                        (wl-draft-parse-mailbox-list
878                         (car fields)
879                         wl-draft-remove-group-list-contents)))
880           (setq fields (cdr fields)))
881         recipients))))
882
883 ;;
884 ;; from Semi-gnus
885 ;;
886 (defun wl-draft-send-mail-with-smtp ()
887   "Send the prepared message buffer with SMTP."
888   (require 'smtp)
889   (let* ((errbuf (if mail-interactive
890                      (generate-new-buffer " smtp errors")
891                    0))
892          (case-fold-search t)
893          (default-case-fold-search t)
894          (sender (or wl-envelope-from
895                      (wl-address-header-extract-address wl-from)))
896          (delimline (save-excursion
897                       (goto-char (point-min))
898                       (re-search-forward
899                        (concat "^" (regexp-quote mail-header-separator)
900                                "$\\|^$") nil t)
901                       (point-marker)))
902          (smtp-server
903           (or wl-smtp-posting-server
904               ;; Compatibility stuff for FLIM 1.12.5 or earlier.
905               ;; They don't accept a function as the value of `smtp-server'.
906               (if (functionp smtp-server)
907                   (funcall
908                    smtp-server
909                    sender
910                    ;; no harm..
911                    (let (wl-draft-remove-group-list-contents)
912                      (wl-draft-deduce-address-list
913                       (current-buffer) (point-min) delimline)))
914                 (or smtp-server "localhost"))))
915          (smtp-service (or wl-smtp-posting-port smtp-service))
916          (smtp-local-domain (or smtp-local-domain wl-local-domain))
917          (id (std11-field-body "message-id"))
918          recipients)
919     (if (not (elmo-plugged-p smtp-server smtp-service))
920         (wl-draft-set-sent-message 'mail 'unplugged
921                                    (cons smtp-server smtp-service))
922       (unwind-protect
923           (save-excursion
924             ;; Instead of `smtp-deduce-address-list'.
925             (setq recipients (wl-draft-deduce-address-list
926                               (current-buffer) (point-min) delimline))
927             (unless recipients (error "No recipients"))
928             ;; Insert an extra newline if we need it to work around
929             ;; Sun's bug that swallows newlines.
930             (goto-char (1+ delimline))
931             (if (eval mail-mailer-swallows-blank-line)
932                 (newline))
933 ;;;         (run-hooks 'wl-mail-send-pre-hook)
934             (if mail-interactive
935                 (save-excursion
936                   (set-buffer errbuf)
937                   (erase-buffer)))
938             (wl-draft-delete-field "bcc" delimline)
939             (wl-draft-delete-field "resent-bcc" delimline)
940             (let (process-connection-type)
941               (as-binary-process
942                (when recipients
943                  (wl-smtp-extension-bind
944                   (condition-case err
945                       (smtp-send-buffer sender recipients (current-buffer))
946                     (error
947                      (wl-draft-write-sendlog 'failed 'smtp smtp-server
948                                              recipients id)
949                      (signal (car err) (cdr err)))))
950                  (wl-draft-set-sent-message 'mail 'sent)
951                  (wl-draft-write-sendlog
952                   'ok 'smtp smtp-server recipients id)))))
953         (if (bufferp errbuf)
954             (kill-buffer errbuf))))))
955
956 (defun wl-draft-send-mail-with-pop-before-smtp ()
957   "Send the prepared message buffer with POP-before-SMTP."
958   (require 'elmo-pop3)
959   (condition-case ()
960       (let ((session (elmo-pop3-get-session
961                       (list 'pop3
962                             (or wl-pop-before-smtp-user
963                                 elmo-pop3-default-user)
964                             (or wl-pop-before-smtp-authenticate-type
965                                 elmo-pop3-default-authenticate-type)
966                             (or wl-pop-before-smtp-server
967                                 elmo-pop3-default-server)
968                             (or wl-pop-before-smtp-port
969                                 elmo-pop3-default-port)
970                             (or wl-pop-before-smtp-stream-type
971                                 elmo-pop3-default-stream-type)))))
972         (when session (elmo-network-close-session session)))
973     (error))
974   (wl-draft-send-mail-with-smtp))
975
976 (defun wl-draft-insert-required-fields (&optional force-msgid)
977   "Insert Message-ID, Date, and From field.
978 If FORCE-MSGID, ignore 'wl-insert-message-id'."
979   ;; Insert Message-Id field...
980   (goto-char (point-min))
981   (when (and (or force-msgid
982                  wl-insert-message-id)
983              (not (re-search-forward "^Message-ID[ \t]*:" nil t)))
984     (insert (concat "Message-ID: "
985                     (wl-draft-make-message-id-string)
986                     "\n")))
987   ;; Insert date field.
988   (goto-char (point-min))
989   (or (re-search-forward "^Date[ \t]*:" nil t)
990       (wl-draft-insert-date-field))
991   ;; Insert from field.
992   (goto-char (point-min))
993   (or (re-search-forward "^From[ \t]*:" nil t)
994       (wl-draft-insert-from-field)))
995
996 (defun wl-draft-normal-send-func (editing-buffer kill-when-done)
997   "Send the message in the current buffer."
998   (save-restriction
999     (std11-narrow-to-header mail-header-separator)
1000     (wl-draft-insert-required-fields)
1001     ;; Delete null fields.
1002     (goto-char (point-min))
1003     (while (re-search-forward "^[^ \t\n:]+:[ \t]*\n" nil t)
1004       (replace-match ""))
1005     ;; ignore any blank lines in the header
1006     (while (re-search-forward "\n\n\n*" nil t)
1007       (replace-match "\n")))
1008   (run-hooks 'wl-mail-send-pre-hook) ;; X-PGP-Sig, Cancel-Lock
1009   (wl-draft-dispatch-message)
1010   (when kill-when-done
1011     ;; hide editing-buffer.
1012     (wl-draft-hide editing-buffer)
1013     ;; delete editing-buffer and its file.
1014     (wl-draft-delete editing-buffer)))
1015
1016 (defun wl-draft-dispatch-message (&optional mes-string)
1017   "Send the message in the current buffer.  Not modified the header fields."
1018   (let (delimline)
1019     (if (and wl-draft-verbose-send mes-string)
1020         (message mes-string))
1021     ;; get fcc folders.
1022     (setq delimline (wl-draft-get-header-delimiter t))
1023     (unless wl-draft-fcc-list
1024       (setq wl-draft-fcc-list (wl-draft-get-fcc-list delimline)))
1025     ;;
1026     (setq wl-sent-message-modified nil)
1027     (unwind-protect
1028         (progn
1029           (if (and (wl-message-mail-p)
1030                    (not (wl-draft-sent-message-p 'mail)))
1031               (funcall wl-draft-send-mail-function))
1032           (if (and (wl-message-news-p)
1033                    (not (wl-draft-sent-message-p 'news))
1034                    (not (wl-message-field-exists-p "Resent-to")))
1035               (funcall wl-draft-send-news-function)))
1036       ;;
1037       (let* ((status (wl-draft-sent-message-results))
1038              (unplugged-via (car status))
1039              (sent-via (nth 1 status)))
1040         ;; If one sent, process fcc folder.
1041         (if (and sent-via wl-draft-fcc-list)
1042             (progn
1043               (wl-draft-do-fcc (wl-draft-get-header-delimiter) wl-draft-fcc-list)
1044               (setq wl-draft-fcc-list nil)))
1045         (if wl-draft-use-cache
1046             (let ((id (std11-field-body "Message-ID"))
1047                   (elmo-enable-disconnected-operation t))
1048               (elmo-file-cache-save (elmo-file-cache-get-path id)
1049                                     nil)))
1050         ;; If one unplugged, append queue.
1051         (when (and unplugged-via
1052                    wl-sent-message-modified)
1053           (if wl-draft-enable-queuing
1054               (wl-draft-queue-append wl-sent-message-via)
1055             (error "Unplugged")))
1056         (when wl-draft-verbose-send
1057           (if (and unplugged-via sent-via);; combined message
1058               (progn
1059                 (setq wl-draft-verbose-msg
1060                       (format "Sending%s and Queuing%s..."
1061                               sent-via unplugged-via))
1062                 (message (concat wl-draft-verbose-msg "done")))
1063             (if mes-string
1064                 (message (concat mes-string
1065                                  (if sent-via "done" "failed")))))))))
1066   (not wl-sent-message-modified)) ;; return value
1067
1068 (defun wl-draft-raw-send (&optional kill-when-done force-pre-hook mes-string)
1069   "Force send current buffer as raw message."
1070   (interactive)
1071   (save-excursion
1072     (let (wl-interactive-send
1073 ;;;       wl-draft-verbose-send
1074           (wl-mail-send-pre-hook (and force-pre-hook wl-mail-send-pre-hook))
1075 ;;;       wl-news-send-pre-hook
1076           mail-send-hook
1077           mail-send-actions)
1078       (wl-draft-send kill-when-done mes-string))))
1079
1080 (defun wl-draft-clone-local-variables ()
1081   (let ((locals (buffer-local-variables))
1082         result)
1083     (while locals
1084       (when (and (consp (car locals))
1085                  (car (car locals))
1086                  (string-match wl-draft-clone-local-variable-regexp
1087                                (symbol-name (car (car locals)))))
1088         (wl-append result (list (car (car locals)))))
1089       (setq locals (cdr locals)))
1090     result))
1091
1092 (defun wl-draft-send (&optional kill-when-done mes-string)
1093   "Send current draft message.
1094 If optional argument is non-nil, current draft buffer is killed"
1095   (interactive)
1096   ;; Don't call this explicitly.
1097   ;; Added to 'wl-draft-send-hook (by teranisi)
1098   ;; (wl-draft-config-exec)
1099   (run-hooks 'wl-draft-send-hook)
1100   (when (or (not wl-interactive-send)
1101             (y-or-n-p "Send current draft. OK?"))
1102     (let ((send-mail-function 'wl-draft-raw-send)
1103           (editing-buffer (current-buffer))
1104           (sending-buffer (wl-draft-generate-clone-buffer
1105                            " *wl-draft-sending-buffer*"
1106                            (append wl-draft-config-variables
1107                                    (wl-draft-clone-local-variables))))
1108           (wl-draft-verbose-msg nil)
1109           err)
1110       (unwind-protect
1111           (save-excursion (set-buffer sending-buffer)
1112             (if (and (not (wl-message-mail-p))
1113                      (not (wl-message-news-p)))
1114                 (error "No recipient is specified"))
1115             (expand-abbrev) ; for mail-abbrevs
1116             (run-hooks 'mail-send-hook) ; translate buffer
1117             (if wl-draft-verbose-send
1118                 (message (or mes-string "Sending...")))
1119             (funcall wl-draft-send-function editing-buffer kill-when-done)
1120             ;; Now perform actions on successful sending.
1121             (while mail-send-actions
1122               (condition-case ()
1123                   (apply (car (car mail-send-actions))
1124                          (cdr (car mail-send-actions)))
1125                 (error))
1126               (setq mail-send-actions (cdr mail-send-actions)))
1127 ;;          (if (or (eq major-mode 'wl-draft-mode)
1128 ;;                  (eq major-mode 'mail-mode))
1129 ;;              (local-set-key "\C-c\C-s" 'wl-draft-send)) ; override
1130             (if wl-draft-verbose-send
1131                 (message (concat (or wl-draft-verbose-msg
1132                                      mes-string "Sending...")
1133                                  "done"))))
1134         ;; kill sending buffer, anyway.
1135         (and (buffer-live-p sending-buffer)
1136              (kill-buffer sending-buffer))))))
1137
1138 (defun wl-draft-save ()
1139   "Save current draft."
1140   (interactive)
1141   (save-buffer)
1142   (wl-draft-config-info-operation
1143    (and (string-match "[0-9]+$" wl-draft-buffer-file-name)
1144         (string-to-int
1145          (match-string 0 wl-draft-buffer-file-name)))
1146    'save))
1147
1148 (defun wl-draft-mimic-kill-buffer ()
1149   "Kill the current (draft) buffer with query."
1150   (interactive)
1151   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
1152                                       (buffer-name))))
1153         wl-draft-use-frame)
1154     (if (or (not bufname)
1155             (string-equal bufname "")
1156             (string-equal bufname (buffer-name)))
1157         (wl-draft-save-and-exit)
1158       (kill-buffer bufname))))
1159
1160 (defun wl-draft-save-and-exit ()
1161   "Save current draft and exit current draft mode."
1162   (interactive)
1163   (wl-draft-save)
1164   (let ((editing-buffer (current-buffer)))
1165     (wl-draft-hide editing-buffer)
1166     (kill-buffer editing-buffer)))
1167   
1168 (defun wl-draft-send-and-exit ()
1169   "Send current draft message and kill it."
1170   (interactive)
1171   (wl-draft-send t))
1172
1173 (defun wl-draft-send-from-toolbar ()
1174   (interactive)
1175   (let ((wl-interactive-send t))
1176     (wl-draft-send-and-exit)))
1177
1178 (defun wl-draft-delete-field (field &optional delimline)
1179   (wl-draft-delete-fields (regexp-quote field) delimline))
1180
1181 (defun wl-draft-delete-fields (regexp &optional delimline)
1182   (save-restriction
1183     (unless delimline
1184       (if (search-forward "\n\n" nil t)
1185           (setq delimline (point))
1186         (setq delimline (point-max))))
1187     (narrow-to-region (point-min) delimline)
1188     (goto-char (point-min))
1189     (let ((regexp (concat "^" regexp ":"))
1190           (case-fold-search t)
1191           last)
1192       (while (not (eobp))
1193         (if (looking-at regexp)
1194             (progn
1195               (delete-region
1196                (point)
1197                (progn
1198                  (forward-line 1)
1199                  (if (re-search-forward "^[^ \t]" nil t)
1200                      (goto-char (match-beginning 0))
1201                    (point-max)))))
1202           (forward-line 1)
1203           (if (re-search-forward "^[^ \t]" nil t)
1204               (goto-char (match-beginning 0))
1205             (point-max)))))))
1206
1207 (defun wl-draft-get-fcc-list (header-end)
1208   (let (fcc-list
1209         (case-fold-search t))
1210     (or (markerp header-end) (error "header-end must be a marker"))
1211     (save-excursion
1212       (goto-char (point-min))
1213       (while (re-search-forward "^Fcc:[ \t]*" header-end t)
1214         (setq fcc-list
1215               (cons (buffer-substring-no-properties
1216                      (point)
1217                      (progn
1218                        (end-of-line)
1219                        (skip-chars-backward " \t")
1220                        (point)))
1221                     fcc-list))
1222         (save-match-data
1223           (wl-folder-confirm-existence
1224            (wl-folder-get-elmo-folder (eword-decode-string (car fcc-list)))))
1225         (delete-region (match-beginning 0)
1226                        (progn (forward-line 1) (point)))))
1227     fcc-list))
1228
1229 (defun wl-draft-do-fcc (header-end &optional fcc-list)
1230   (let ((send-mail-buffer (current-buffer))
1231         (tembuf (generate-new-buffer " fcc output"))
1232         (case-fold-search t)
1233         beg end)
1234     (or (markerp header-end) (error "header-end must be a marker"))
1235     (save-excursion
1236       (unless fcc-list
1237         (setq fcc-list (wl-draft-get-fcc-list header-end)))
1238       (set-buffer tembuf)
1239       (erase-buffer)
1240       ;; insert just the headers to avoid moving the gap more than
1241       ;; necessary (the message body could be arbitrarily huge.)
1242       (insert-buffer-substring send-mail-buffer 1 header-end)
1243       (wl-draft-insert-required-fields t)
1244       (goto-char (point-max))
1245       (insert-buffer-substring send-mail-buffer header-end)
1246       (let ((id (std11-field-body "Message-ID"))
1247             (elmo-enable-disconnected-operation t)
1248             cache-saved)
1249         (while fcc-list
1250           (unless (or cache-saved
1251                       (elmo-folder-plugged-p
1252                        (wl-folder-get-elmo-folder (car fcc-list))))
1253             (elmo-file-cache-save id nil) ;; for disconnected operation
1254             (setq cache-saved t))
1255           (if (elmo-folder-append-buffer
1256                (wl-folder-get-elmo-folder
1257                 (eword-decode-string (car fcc-list)))
1258                id)
1259               (wl-draft-write-sendlog 'ok 'fcc nil (car fcc-list) id)
1260             (wl-draft-write-sendlog 'failed 'fcc nil (car fcc-list) id))
1261           (setq fcc-list (cdr fcc-list)))))
1262     (kill-buffer tembuf)))
1263
1264 (defun wl-draft-on-field-p ()
1265   (if (< (point)
1266          (save-excursion
1267            (goto-char (point-min))
1268            (search-forward (concat "\n" mail-header-separator "\n") nil 0)
1269            (point)))
1270       (if (bolp)
1271           (if (bobp)
1272               t
1273             (save-excursion
1274               (forward-line -1)
1275               (if (or (looking-at ".*,[ \t]?$")
1276                       (looking-at "^[^ \t]+:[ \t]+.*:$")); group list name
1277                   nil t)))
1278         (let ((pos (point)))
1279           (save-excursion
1280             (beginning-of-line)
1281             (if (looking-at "^[ \t]")
1282                 nil
1283               (if (re-search-forward ":" pos t) nil t)))))))
1284
1285 (defun wl-draft-random-alphabet ()
1286   (let ((alphabet '(?A ?B ?C ?D ?E ?F ?G ?H ?I ?J ?K ?L ?M ?N ?O ?P ?Q ?R ?S ?T ?U ?V ?W ?X ?Y ?Z)))
1287     (nth (abs (% (random) 26)) alphabet)))
1288
1289 ;;;###autoload
1290 (defun wl-draft (&optional to subject in-reply-to cc references newsgroups
1291                            mail-followup-to
1292                            content-type content-transfer-encoding
1293                            body edit-again summary-buf from)
1294   "Write and send mail/news message with Wanderlust."
1295   (interactive)
1296   (unless (featurep 'wl)
1297     (require 'wl))
1298   (unless wl-init
1299     (wl-load-profile))
1300   (wl-init) ;; returns immediately if already initialized.
1301   (if (interactive-p)
1302       (setq summary-buf (wl-summary-get-buffer (wl-summary-buffer-folder-name))))
1303   (let ((draft-folder (wl-folder-get-elmo-folder wl-draft-folder))
1304         buf-name file-name num wl-demo change-major-mode-hook)
1305     (if (not (elmo-folder-message-file-p draft-folder))
1306         (error "%s folder cannot be used for draft folder" wl-draft-folder))
1307     (setq num (elmo-max-of-list
1308                (or (elmo-folder-list-messages draft-folder) '(0))))
1309     (setq num (+ 1 num))
1310     ;; To get unused buffer name.
1311     (while (get-buffer (concat wl-draft-folder "/" (int-to-string num)))
1312       (setq num (+ 1 num)))
1313     (setq buf-name (find-file-noselect
1314                     (setq file-name
1315                           (elmo-message-file-name
1316                            (wl-folder-get-elmo-folder wl-draft-folder)
1317                            num))))
1318     (if wl-draft-use-frame
1319         (switch-to-buffer-other-frame buf-name)
1320       (switch-to-buffer buf-name))
1321     (set-buffer buf-name)
1322     (if (not (string-match (regexp-quote wl-draft-folder)
1323                            (buffer-name)))
1324         (rename-buffer (concat wl-draft-folder "/" (int-to-string num))))
1325     (if (or (eq wl-draft-reply-buffer-style 'full)
1326             (eq this-command 'wl-draft)
1327             (eq this-command 'wl-summary-write)
1328             (eq this-command 'wl-summary-write-current-folder))
1329         (delete-other-windows))
1330     (auto-save-mode -1)
1331     (wl-draft-mode)
1332     (setq wl-sent-message-via nil)
1333     (if (stringp (or from wl-from))
1334         (insert "From: " (or from wl-from) "\n"))
1335     (and (or (interactive-p)
1336              (eq this-command 'wl-summary-write)
1337              to)
1338          (insert "To: " (or to "") "\n"))
1339     (and cc (insert "Cc: " (or cc "") "\n"))
1340     (insert "Subject: " (or subject "") "\n")
1341     (and newsgroups (insert "Newsgroups: " newsgroups "\n"))
1342     (and mail-followup-to (insert "Mail-Followup-To: " mail-followup-to "\n"))
1343     (and wl-insert-mail-reply-to
1344          (insert "Mail-Reply-To: "
1345                  (wl-address-header-extract-address
1346                   wl-from) "\n"))
1347     (and in-reply-to (insert "In-Reply-To: " in-reply-to "\n"))
1348     (and references (insert "References: " references "\n"))
1349     (insert (funcall wl-generate-mailer-string-function) "\n")
1350     (setq wl-draft-buffer-file-name file-name)
1351     (if mail-default-reply-to
1352         (insert "Reply-To: " mail-default-reply-to "\n"))
1353     (wl-draft-insert-ccs "Bcc: " (or wl-bcc
1354                                (and mail-self-blind (user-login-name))))
1355     (wl-draft-insert-ccs "Fcc: " wl-fcc)
1356     (if wl-organization
1357         (insert "Organization: " wl-organization "\n"))
1358     (and wl-auto-insert-x-face
1359          (file-exists-p wl-x-face-file)
1360          (wl-draft-insert-x-face-field-here))
1361     (if mail-default-headers
1362         (insert mail-default-headers))
1363     (if (not (= (preceding-char) ?\n))
1364         (insert ?\n))
1365     (if edit-again
1366         (let (start)
1367           (setq start (point))
1368           (when content-type
1369             (insert "Content-type: " content-type "\n"))
1370           (when content-transfer-encoding
1371             (insert "Content-Transfer-Encoding: " content-transfer-encoding "\n"))
1372           (if (or content-type content-transfer-encoding)
1373               (insert "\n"))
1374           (and body (insert body))
1375           (save-restriction
1376             (narrow-to-region start (point))
1377             (and edit-again
1378                  (wl-draft-decode-message-in-buffer))
1379             (widen)
1380             (goto-char start)
1381             (put-text-property (point)
1382                                (progn
1383                                  (insert mail-header-separator "\n")
1384                                  (1- (point)))
1385                                'category 'mail-header-separator)))
1386       (put-text-property (point)
1387                          (progn
1388                            (insert mail-header-separator "\n")
1389                            (1- (point)))
1390                          'category 'mail-header-separator)
1391       (and body (insert body)))
1392     (if wl-on-nemacs
1393         (push-mark (point) t)
1394       (push-mark (point) t t))
1395     (as-binary-output-file
1396      (write-region (point-min)(point-max) wl-draft-buffer-file-name
1397                    nil t))
1398     (wl-draft-editor-mode)
1399     (wl-draft-overload-functions)
1400     (wl-highlight-headers 'for-draft)
1401     (goto-char (point-min))
1402     (setq wl-draft-config-exec-flag t)
1403     (if (interactive-p)
1404         (run-hooks 'wl-mail-setup-hook))
1405     (wl-user-agent-compose-internal) ;; user-agent
1406     (cond ((eq this-command 'wl-summary-write-current-newsgroup)
1407            (mail-position-on-field "Subject"))
1408           ((and (interactive-p) (null to))
1409            (mail-position-on-field "To"))
1410           (t
1411            (goto-char (point-max))))
1412     (setq wl-draft-buffer-cur-summary-buffer (or summary-buf
1413                                                  (get-buffer
1414                                                   wl-summary-buffer-name)))
1415     buf-name))
1416
1417 (defsubst wl-draft-insert-ccs (str cc)
1418   (let ((field
1419          (if (functionp cc)
1420              (funcall cc)
1421            cc)))
1422     (if (and field
1423              (null (and wl-draft-delete-myself-from-bcc-fcc
1424                         (elmo-list-member
1425                          (mapcar 'wl-address-header-extract-address
1426                                  (append
1427                                   (wl-parse-addresses (std11-field-body "To"))
1428                                   (wl-parse-addresses (std11-field-body "Cc"))))
1429                          (mapcar 'downcase wl-subscribed-mailing-list)))))
1430         (insert str field "\n"))))
1431
1432 (defun wl-draft-elmo-nntp-send ()
1433   (let ((elmo-nntp-post-pre-hook wl-news-send-pre-hook)
1434         (elmo-nntp-default-user
1435          (or wl-nntp-posting-user elmo-nntp-default-user))
1436         (elmo-nntp-default-server
1437          (or wl-nntp-posting-server elmo-nntp-default-server))
1438         (elmo-nntp-default-port
1439          (or wl-nntp-posting-port elmo-nntp-default-port))
1440         (elmo-nntp-default-stream-type
1441          (or wl-nntp-posting-stream-type elmo-nntp-default-stream-type)))
1442     (if (not (elmo-plugged-p elmo-nntp-default-server elmo-nntp-default-port))
1443         (wl-draft-set-sent-message 'news 'unplugged
1444                                    (cons elmo-nntp-default-server
1445                                          elmo-nntp-default-port))
1446       (elmo-nntp-post elmo-nntp-default-server (current-buffer))
1447       (wl-draft-set-sent-message 'news 'sent)
1448       (wl-draft-write-sendlog 'ok 'nntp elmo-nntp-default-server
1449                               (std11-field-body "Newsgroups")
1450                               (std11-field-body "Message-ID")))))
1451
1452 (defun wl-draft-generate-clone-buffer (name &optional local-variables)
1453   "generate clone of current buffer named NAME."
1454   (let ((editing-buffer (current-buffer)))
1455     (save-excursion
1456       (set-buffer (generate-new-buffer name))
1457       (erase-buffer)
1458       (wl-draft-mode)
1459       (wl-draft-editor-mode)
1460       (insert-buffer editing-buffer)
1461       (message "")
1462       (while local-variables
1463         (make-local-variable (car local-variables))
1464         (set (car local-variables)
1465              (save-excursion
1466                (set-buffer editing-buffer)
1467                (symbol-value (car local-variables))))
1468         (setq local-variables (cdr local-variables)))
1469       (current-buffer))))
1470
1471 (defun wl-draft-reedit (number)
1472   (let ((draft-folder (wl-folder-get-elmo-folder wl-draft-folder))
1473         (wl-draft-reedit t)
1474         buf-name file-name change-major-mode-hook)
1475     (setq file-name (elmo-message-file-name draft-folder number))
1476     (unless (file-exists-p file-name)
1477       (error "File %s does not exist" file-name))
1478     (setq buf-name (find-file-noselect file-name))
1479     (if wl-draft-use-frame
1480         (switch-to-buffer-other-frame buf-name)
1481       (switch-to-buffer buf-name))
1482     (set-buffer buf-name)
1483     (if (not (string-match (regexp-quote wl-draft-folder)
1484                            (buffer-name)))
1485         (rename-buffer (concat wl-draft-folder "/" (buffer-name))))
1486     (auto-save-mode -1)
1487     (wl-draft-mode)
1488     (setq wl-sent-message-via nil)
1489     (setq wl-draft-buffer-file-name file-name)
1490     (wl-draft-config-info-operation number 'load)
1491     (goto-char (point-min))
1492     (or (re-search-forward "\n\n" nil t)
1493         (search-forward (concat mail-header-separator "\n") nil t))
1494     (if wl-on-nemacs
1495         (push-mark (point) t)
1496       (push-mark (point) t t))
1497     (write-region (point-min)(point-max) wl-draft-buffer-file-name
1498                   nil t)
1499     (wl-draft-overload-functions)
1500     (wl-draft-editor-mode)
1501     (wl-highlight-headers 'for-draft)
1502     (run-hooks 'wl-draft-reedit-hook)
1503     (goto-char (point-max))
1504     buf-name
1505     ))
1506
1507 (defmacro wl-draft-body-goto-top ()
1508   (` (progn
1509        (goto-char (point-min))
1510        (if (re-search-forward mail-header-separator nil t)
1511            (forward-char 1)
1512          (goto-char (point-max))))))
1513
1514 (defmacro wl-draft-body-goto-bottom ()
1515   (` (goto-char (point-max))))
1516
1517 (defmacro wl-draft-config-body-goto-header ()
1518   (` (progn
1519        (goto-char (point-min))
1520        (if (re-search-forward mail-header-separator nil t)
1521            (beginning-of-line)
1522          (goto-char (point-max))))))
1523
1524 (defun wl-draft-config-sub-body (content)
1525   (wl-draft-body-goto-top)
1526   (delete-region (point) (point-max))
1527   (if content (insert (eval content))))
1528
1529 (defun wl-draft-config-sub-top (content)
1530   (wl-draft-body-goto-top)
1531   (if content (insert (eval content))))
1532
1533 (defun wl-draft-config-sub-bottom (content)
1534   (wl-draft-body-goto-bottom)
1535   (if content (insert (eval content))))
1536
1537 (defun wl-draft-config-sub-header (content)
1538   (wl-draft-config-body-goto-header)
1539   (if content (insert (concat (eval content) "\n"))))
1540
1541 (defsubst wl-draft-config-sub-file (content)
1542   (let ((coding-system-for-read wl-cs-autoconv)
1543         (file (expand-file-name (eval content))))
1544     (if (file-exists-p file)
1545         (insert-file-contents file)
1546       (error "%s: no exists file" file))))
1547
1548 (defun wl-draft-config-sub-body-file (content)
1549   (wl-draft-body-goto-top)
1550   (delete-region (point) (point-max))
1551   (wl-draft-config-sub-file content))
1552
1553 (defun wl-draft-config-sub-top-file (content)
1554   (wl-draft-body-goto-top)
1555   (wl-draft-config-sub-file content))
1556
1557 (defun wl-draft-config-sub-bottom-file (content)
1558   (wl-draft-body-goto-bottom)
1559   (wl-draft-config-sub-file content))
1560
1561 (defun wl-draft-config-sub-header-file (content)
1562   (wl-draft-config-body-goto-header)
1563   (wl-draft-config-sub-file content))
1564
1565 (defun wl-draft-config-sub-template (content)
1566   (setq wl-draft-config-variables
1567         (wl-template-insert (eval content))))
1568
1569 (defun wl-draft-config-sub-x-face (content)
1570   (if (and (string-match "\\.xbm\\(\\.gz\\)?$" content)
1571            (fboundp 'x-face-insert)) ; x-face.el is installed.
1572       (x-face-insert content)
1573     (wl-draft-replace-field "X-Face" (elmo-get-file-string content t) t)))
1574
1575 (defsubst wl-draft-config-sub-func (field content)
1576   (let (func)
1577     (if (setq func (assq field wl-draft-config-sub-func-alist))
1578         (let (wl-draft-config-variables)
1579           (funcall (cdr func) content)
1580           ;; for wl-draft-config-sub-template
1581           (cons t wl-draft-config-variables)))))
1582
1583 (defsubst wl-draft-config-exec-sub (clist)
1584   (let (config local-variables)
1585     (while clist
1586       (setq config (car clist))
1587       (cond
1588        ((consp config)
1589         (let ((field (car config))
1590               (content (cdr config))
1591               ret-val)
1592           (cond
1593            ((stringp field)
1594             (wl-draft-replace-field field (eval content) t))
1595            ((setq ret-val (wl-draft-config-sub-func field content))
1596             (if (cdr ret-val) ;; for wl-draft-config-sub-template
1597                 (wl-append local-variables (cdr ret-val))))
1598            ((boundp field) ;; variable
1599             (make-local-variable field)
1600             (set field (eval content))
1601             (wl-append local-variables (list field)))
1602            (t
1603             (error "%s: not variable" field)))))
1604        ((or (functionp config)
1605             (and (symbolp config)
1606                  (fboundp config)))
1607         (funcall config))
1608        (t
1609         (error "%s: not supported type" config)))
1610       (setq clist (cdr clist)))
1611     local-variables))
1612
1613 (defun wl-draft-prepared-config-exec (&optional config-alist reply-buf)
1614   "Change headers in draft preparation time."
1615   (interactive)
1616   (unless wl-draft-reedit
1617     (let ((config-alist
1618            (or config-alist
1619                (and (boundp 'wl-draft-prepared-config-alist)
1620                     wl-draft-prepared-config-alist)     ;; For compatible.
1621                wl-draft-config-alist)))
1622       (if config-alist
1623           (wl-draft-config-exec config-alist reply-buf)))))
1624
1625 (defun wl-draft-config-exec (&optional config-alist reply-buf)
1626   "Change headers in draft sending time."
1627   (interactive)
1628   (let ((case-fold-search t)
1629         (alist (or config-alist wl-draft-config-alist))
1630         (reply-buf (or reply-buf (and (buffer-live-p wl-draft-reply-buffer)
1631                                       wl-draft-reply-buffer)))
1632         (local-variables wl-draft-config-variables)
1633         key clist found)
1634     (when (and (or (interactive-p)
1635                    wl-draft-config-exec-flag)
1636                alist)
1637       (save-excursion
1638         (catch 'done
1639           (while alist
1640             (setq key (caar alist)
1641                   clist (cdar alist))
1642             (cond
1643              ((eq key 'reply)
1644               (when (and
1645                      reply-buf
1646                      (save-excursion
1647                        (set-buffer reply-buf)
1648                        (save-restriction
1649                          (std11-narrow-to-header)
1650                          (goto-char (point-min))
1651                          (re-search-forward (car clist) nil t))))
1652                 (wl-draft-config-exec-sub (cdr clist))
1653                 (setq found t)))
1654              ((stringp key)
1655               (when (save-restriction
1656                       (std11-narrow-to-header mail-header-separator)
1657                       (goto-char (point-min))
1658                       (re-search-forward key nil t))
1659                 (wl-append local-variables
1660                            (wl-draft-config-exec-sub clist))
1661                 (setq found t)))
1662              ((eval key)
1663               (wl-append local-variables
1664                          (wl-draft-config-exec-sub clist))
1665               (setq found t)))
1666             (if (and found wl-draft-config-matchone)
1667                 (throw 'done t))
1668             (setq alist (cdr alist))))
1669         (if found
1670             (setq wl-draft-config-exec-flag nil))
1671         (run-hooks 'wl-draft-config-exec-hook)
1672         (put-text-property (point-min)(point-max) 'face nil)
1673         (wl-highlight-message (point-min)(point-max) t)
1674         (setq wl-draft-config-variables
1675               (elmo-uniq-list local-variables))))))
1676
1677 (defun wl-draft-replace-field (field content &optional add)
1678   (save-excursion
1679     (save-restriction
1680       (let ((case-fold-search t)
1681             (inhibit-read-only t) ;; added by teranisi.
1682             beg)
1683         (std11-narrow-to-header mail-header-separator)
1684         (goto-char (point-min))
1685         (if (re-search-forward (concat "^" (regexp-quote field) ":") nil t)
1686             (if content
1687                 ;; replace field
1688                 (progn
1689                   (setq beg (point))
1690                   (re-search-forward "^[^ \t]" nil 'move)
1691                   (beginning-of-line)
1692                   (skip-chars-backward "\n")
1693                   (delete-region beg (point))
1694                   (insert " " content))
1695               ;; delete field
1696               (save-excursion
1697                 (beginning-of-line)
1698                 (setq beg (point)))
1699               (re-search-forward "^[^ \t]" nil 'move)
1700               (beginning-of-line)
1701               (delete-region beg (point)))
1702           (when (and add content)
1703             ;; add field
1704             (goto-char (point-max))
1705             (insert (concat field ": " content "\n"))))))))
1706
1707 (defun wl-draft-config-info-operation (msg operation)
1708   (let* ((msgdb-dir (elmo-folder-msgdb-path (wl-folder-get-elmo-folder
1709                                              wl-draft-folder)))
1710          (filename
1711           (expand-file-name
1712            (format "%s-%d" wl-draft-config-save-filename msg)
1713            msgdb-dir))
1714          element alist variable)
1715     (cond
1716      ((eq operation 'save)
1717       (let ((variables (elmo-uniq-list wl-draft-config-variables)))
1718         (while (setq variable (pop variables))
1719           (when (boundp variable)
1720             (wl-append alist
1721                        (list (cons variable (eval variable))))))
1722         (elmo-object-save filename alist)))
1723      ((eq operation 'load)
1724       (setq alist (elmo-object-load filename))
1725       (while (setq element (pop alist))
1726         (set (make-local-variable (car element)) (cdr element))
1727         (wl-append wl-draft-config-variables (list (car element)))))
1728      ((eq operation 'delete)
1729       (if (file-exists-p filename)
1730           (delete-file filename))))))
1731
1732 (defun wl-draft-queue-info-operation (msg operation
1733                                           &optional add-sent-message-via)
1734   (let* ((msgdb-dir (elmo-folder-msgdb-path
1735                      (wl-folder-get-elmo-folder wl-queue-folder)))
1736          (filename
1737           (expand-file-name
1738            (format "%s-%d" wl-draft-queue-save-filename msg)
1739            msgdb-dir))
1740          element alist variable)
1741     (cond
1742      ((eq operation 'save)
1743       (let ((variables (elmo-uniq-list
1744                         (append wl-draft-queue-save-variables
1745                                 wl-draft-config-variables
1746                                 (list 'wl-draft-fcc-list)))))
1747         (if add-sent-message-via
1748             (push 'wl-sent-message-via variables))
1749         (while (setq variable (pop variables))
1750           (when (boundp variable)
1751             (wl-append alist
1752                        (list (cons variable (eval variable))))))
1753         (elmo-object-save filename alist)))
1754      ((eq operation 'load)
1755       (setq alist (elmo-object-load filename))
1756       (while (setq element (pop alist))
1757         (set (make-local-variable (car element)) (cdr element))))
1758      ((eq operation 'get-sent-via)
1759       (setq alist (elmo-object-load filename))
1760       (cdr (assq 'wl-sent-message-via alist)))
1761      ((eq operation 'delete)
1762       (if (file-exists-p filename)
1763           (delete-file filename))))))
1764
1765 (defun wl-draft-queue-append (wl-sent-message-via)
1766   (if wl-draft-verbose-send
1767       (message "Queuing..."))
1768   (let ((send-buffer (current-buffer))
1769         (folder (wl-folder-get-elmo-folder wl-queue-folder))
1770         (message-id (std11-field-body "Message-ID")))
1771     (if (elmo-folder-append-buffer folder t)
1772         (progn
1773           (wl-draft-queue-info-operation
1774            (car (elmo-folder-status folder))
1775            'save wl-sent-message-via)
1776           (wl-draft-write-sendlog 'ok 'queue nil wl-queue-folder message-id)
1777           (when wl-draft-verbose-send
1778             (setq wl-draft-verbose-msg "Queuing...")
1779             (message "Queuing...done")))
1780       (wl-draft-write-sendlog 'failed 'queue nil wl-queue-folder message-id)
1781       (error "Queuing failed"))))
1782
1783 (defun wl-draft-queue-flush ()
1784   "Flush draft queue."
1785   (interactive)
1786   (let* ((queue-folder (wl-folder-get-elmo-folder wl-queue-folder))
1787          (msgs2 (elmo-folder-list-messages queue-folder))
1788          (i 0)
1789          (performed 0)
1790          (wl-draft-queue-flushing t)
1791          msgs failure len buffer msgid sent-via)
1792     ;; get plugged send message
1793     (while msgs2
1794       (setq sent-via (wl-draft-queue-info-operation (car msgs2) 'get-sent-via))
1795       (catch 'found
1796         (while sent-via
1797           (when (and (eq (nth 1 (car sent-via)) 'unplugged)
1798                      (elmo-plugged-p
1799                       (car (nth 2 (car sent-via)))
1800                       (cdr (nth 2 (car sent-via)))))
1801             (wl-append msgs (list (car msgs2)))
1802             (throw 'found t))
1803           (setq sent-via (cdr sent-via))))
1804       (setq msgs2 (cdr msgs2)))
1805     (when (> (setq len (length msgs)) 0)
1806       (if (elmo-y-or-n-p (format
1807                           "%d message(s) are in the sending queue. Send now?"
1808                           len)
1809                          (not elmo-dop-flush-confirm) t)
1810           (progn
1811             (save-excursion
1812               (setq buffer (get-buffer-create " *wl-draft-queue-flush*"))
1813               (set-buffer buffer)
1814               (while msgs
1815                 ;; reset buffer local variables
1816                 (kill-all-local-variables)
1817                 (erase-buffer)
1818                 (setq i (+ 1 i)
1819                       failure nil)
1820                 (setq wl-sent-message-via nil)
1821                 (wl-draft-queue-info-operation (car msgs) 'load)
1822                 (elmo-message-fetch queue-folder
1823                                     (car msgs)
1824                                     (elmo-make-fetch-strategy 'entire)
1825                                     nil (current-buffer))
1826                 (condition-case err
1827                     (setq failure (funcall
1828                                    wl-draft-queue-flush-send-function
1829                                    (format "Sending (%d/%d)..." i len)))
1830 ;;;               (wl-draft-raw-send nil nil
1831 ;;;                                  (format "Sending (%d/%d)..." i len))
1832                   (error
1833                    (elmo-display-error err t)
1834                    (setq failure t))
1835                   (quit
1836                    (setq failure t)))
1837                 (unless failure
1838                   (elmo-folder-delete-messages
1839                    queue-folder (cons (car msgs) nil))
1840                   (wl-draft-queue-info-operation (car msgs) 'delete)
1841                   (setq performed (+ 1 performed)))
1842                 (setq msgs (cdr msgs)))
1843               (kill-buffer buffer)
1844               (message "%d message(s) are sent." performed)))
1845         (message "%d message(s) are remained to be sent." len))
1846       len)))
1847
1848 (defun wl-jump-to-draft-buffer (&optional arg)
1849   "Jump to the draft if exists."
1850   (interactive "P")
1851   (if arg
1852       (wl-jump-to-draft-folder)
1853     (let ((bufs (buffer-list))
1854           (draft-regexp (concat
1855                          "^" (regexp-quote
1856                               (elmo-localdir-folder-directory-internal
1857                                (wl-folder-get-elmo-folder wl-draft-folder)))))
1858           buf draft-bufs)
1859       (while bufs
1860         (if (and
1861              (setq buf (buffer-file-name (car bufs)))
1862              (string-match draft-regexp buf))
1863             (setq draft-bufs (cons (buffer-name (car bufs)) draft-bufs)))
1864         (setq bufs (cdr bufs)))
1865       (cond
1866        ((null draft-bufs)
1867         (message "No draft buffer exist."))
1868        (t
1869         (setq draft-bufs
1870               (sort draft-bufs (function (lambda (a b) (not (string< a b))))))
1871         (if (setq buf (cdr (member (buffer-name) draft-bufs)))
1872             (setq buf (car buf))
1873           (setq buf (car draft-bufs)))
1874         (switch-to-buffer buf))))))
1875
1876 (defun wl-jump-to-draft-folder ()
1877   (let ((msgs (reverse (elmo-folder-list-messages (wl-folder-get-elmo-folder
1878                                                    wl-draft-folder))))
1879         (mybuf (buffer-name))
1880         msg buf)
1881     (if (not msgs)
1882         (message "No draft message exist.")
1883       (if (string-match (concat "^" wl-draft-folder "/") mybuf)
1884           (setq msg (cadr (memq
1885                            (string-to-int (substring mybuf (match-end 0)))
1886                            msgs))))
1887       (or msg (setq msg (car msgs)))
1888       (if (setq buf (get-buffer (format "%s/%d" wl-draft-folder msg)))
1889           (switch-to-buffer buf)
1890         (wl-draft-reedit msg)))))
1891
1892 (defun wl-draft-highlight-and-recenter (&optional n)
1893   (interactive "P")
1894   (if wl-highlight-body-too
1895       (let ((beg (point-min))
1896             (end (point-max)))
1897         (put-text-property beg end 'face nil)
1898         (wl-highlight-message beg end t)))
1899   (recenter n))
1900
1901 ;;;; user-agent support by Sen Nagata
1902
1903 ;; this appears to be necessarily global...
1904 (defvar wl-user-agent-compose-p nil)
1905 (defvar wl-user-agent-headers-and-body-alist nil)
1906
1907 ;; this should be a generic function for mail-mode -- i wish there was
1908 ;; something like it in sendmail.el
1909 (defun wl-user-agent-insert-header (header-name header-value)
1910   "Insert HEADER-NAME w/ value HEADER-VALUE into a message."
1911   ;; it seems like overriding existing headers is acceptable -- should
1912   ;; we provide an option?
1913   
1914   ;; plan was: unfold header (might be folded), remove existing value, insert
1915   ;;           new value
1916   ;; wl doesn't seem to fold header lines yet anyway :-)
1917   
1918   (let ((kill-whole-line t)
1919         end-of-line)
1920     (mail-position-on-field (capitalize header-name))
1921     (setq end-of-line (point))
1922     (beginning-of-line)
1923     (re-search-forward ":" end-of-line)
1924     (insert (concat " " header-value "\n"))
1925     (kill-line)))
1926
1927 ;; this should be a generic function for mail-mode -- i wish there was
1928 ;; something like it in sendmail.el
1929 ;;
1930 ;; ** haven't dealt w/ case where the body is already set **
1931 (defun wl-user-agent-insert-body (body-text)
1932   "Insert a body of text, BODY-TEXT, into a message."
1933   ;; code defensively... :-P
1934   (goto-char (point-min))
1935   (search-forward mail-header-separator)
1936   (forward-line 1)
1937   (insert body-text))
1938
1939 ;;;###autoload
1940 (defun wl-user-agent-compose (&optional to subject other-headers continue
1941                                         switch-function yank-action
1942                                         send-actions)
1943   "Support the `compose-mail' interface for wl.
1944 Only support for TO, SUBJECT, and OTHER-HEADERS has been implemented.
1945 Support for CONTINUE, YANK-ACTION, and SEND-ACTIONS has not
1946 been implemented yet.  Partial support for SWITCH-FUNCTION now supported."
1947
1948   (unless (featurep 'wl)
1949     (require 'wl))
1950   ;; protect these -- to and subject get bound at some point, so it looks
1951   ;; to be necessary to protect the values used w/in
1952   (let ((wl-user-agent-headers-and-body-alist other-headers)
1953         (wl-draft-use-frame (eq switch-function 'switch-to-buffer-other-frame))
1954         (wl-draft-reply-buffer-style 'split))
1955     (when (eq switch-function 'switch-to-buffer-other-window)
1956       (when (one-window-p t)
1957         (if (window-minibuffer-p) (other-window 1))
1958         (split-window))
1959       (other-window 1))
1960     (if to
1961         (if (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
1962                                    'ignore-case)
1963             (setcdr
1964              (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
1965                                     'ignore-case)
1966              to)
1967           (setq wl-user-agent-headers-and-body-alist
1968                 (cons (cons "to" to)
1969                       wl-user-agent-headers-and-body-alist))))
1970     (if subject
1971         (if (wl-string-match-assoc "subject"
1972                                    wl-user-agent-headers-and-body-alist
1973                                    'ignore-case)
1974             (setcdr
1975              (wl-string-match-assoc "subject"
1976                                     wl-user-agent-headers-and-body-alist
1977                                     'ignore-case)
1978              subject)
1979           (setq wl-user-agent-headers-and-body-alist
1980                 (cons (cons "subject" subject)
1981                       wl-user-agent-headers-and-body-alist))))
1982     ;; i think this is what we want to use...
1983     (unwind-protect
1984         (progn
1985           ;; tell the hook-function to do its stuff
1986           (setq wl-user-agent-compose-p t)
1987           ;; because to get the hooks working, wl-draft has to think it has
1988           ;; been called interactively
1989           (call-interactively 'wl-draft))
1990       (setq wl-user-agent-compose-p nil))))
1991
1992 (defun wl-user-agent-compose-internal ()
1993   "Manipulate headers and/or a body of a draft message."
1994   ;; being called from wl-user-agent-compose?
1995   (if wl-user-agent-compose-p
1996       (progn
1997         ;; insert headers
1998         (let ((headers wl-user-agent-headers-and-body-alist)
1999               (case-fold-search t))
2000           (while headers
2001             ;; skip body
2002             (if (not (string-match "^body$" (car (car headers))))
2003                 (wl-user-agent-insert-header
2004                  (car (car headers)) (cdr (car headers)))
2005               t)
2006             (setq headers (cdr headers))))
2007         ;; highlight headers (from wl-draft in wl-draft.el)
2008         (wl-highlight-headers 'for-draft)
2009         ;; insert body
2010         (if (wl-string-match-assoc "body" wl-user-agent-headers-and-body-alist
2011                                    'ignore-case)
2012             (wl-user-agent-insert-body
2013              (cdr (wl-string-match-assoc
2014                    "body"
2015                    wl-user-agent-headers-and-body-alist 'ignore-case)))))
2016     t))
2017
2018 (require 'product)
2019 (product-provide (provide 'wl-draft) (require 'wl-version))
2020
2021 ;;; wl-draft.el ends here