7a3f01a7f27988c49819d8381bed952eb7288c2b
[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      (save-excursion
428        (set-buffer mail-reply-buffer)
429        (when decode-it
430          (decode-mime-charset-region (point-min) (point-max)
431                                      wl-mime-charset))
432        (buffer-substring-no-properties
433         (point-min) (point-max))))
434     (when ignored-fields
435       (goto-char (point-min))
436       (wl-draft-delete-fields ignored-fields))
437     (goto-char (point-max))
438     (push-mark)
439     (goto-char (point-min)))
440   (let ((beg (point)))
441     (cond (mail-citation-hook (run-hooks 'mail-citation-hook))
442           (mail-yank-hooks (run-hooks 'mail-yank-hooks))
443           (wl-draft-cite-function (funcall wl-draft-cite-function))) ; default cite
444     (run-hooks 'wl-draft-cited-hook)
445     (when (and wl-draft-add-references
446                (wl-draft-add-references))
447       (wl-highlight-headers 'for-draft)) ; highlight when added References:
448     (when wl-highlight-body-too
449       (wl-highlight-body-region beg (point-max)))))
450
451 (defun wl-draft-confirm ()
452   "Confirm send message."
453   (interactive)
454   (y-or-n-p (format "Send current draft as %s? "
455                     (cond ((and (wl-message-mail-p) (wl-message-news-p))
456                            "Mail and News")
457                           ((wl-message-mail-p) "Mail")
458                           ((wl-message-news-p) "News")))))
459
460 (defun wl-message-news-p ()
461   "If exist valid Newsgroups field, return non-nil."
462   (std11-field-body "Newsgroups"))
463
464 (defun wl-message-field-exists-p (field)
465   "If FIELD exist and FIELD value is not empty, return non-nil."
466   (let ((value (std11-field-body field)))
467     (and value
468          (not (string= value "")))))
469
470 (defun wl-message-mail-p ()
471   "If exist To, Cc or Bcc field, return non-nil."
472   (or (wl-message-field-exists-p "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     (setq date (std11-fetch-field "date"))
599     (if (and summary-buf
600              (buffer-live-p summary-buf)
601              message-buf
602              (buffer-live-p message-buf))
603         (progn
604           (save-excursion
605             (set-buffer summary-buf)
606             (setq num
607                   (save-excursion
608                     (set-buffer message-buf)
609                     wl-message-buffer-cur-number))
610             (setq entity (elmo-msgdb-overview-get-entity
611                           num (wl-summary-buffer-msgdb)))
612             (setq from (elmo-msgdb-overview-entity-get-from entity)))
613           (setq cite-title (format "At %s,\n%s wrote:"
614                                    (or date "some time ago")
615                                    (wl-summary-from-func-internal
616                                     (or from "you"))))))
617     (and cite-title
618          (insert cite-title "\n"))
619     (mail-indent-citation)))
620
621 (defvar wl-draft-buffer nil "Draft buffer to yank content")
622 (defun wl-draft-yank-to-draft-buffer (buffer)
623   "Yank BUFFER content to `wl-draft-buffer'."
624   (set-buffer wl-draft-buffer)
625   (let ((mail-reply-buffer buffer))
626     (wl-draft-yank-from-mail-reply-buffer nil)
627     (kill-buffer buffer)))
628
629 (defun wl-draft-yank-original (&optional arg)
630   "Yank original message."
631   (interactive "P")
632   (if arg
633       (let (buf mail-reply-buffer)
634         (elmo-set-work-buf
635          (yank)
636          (setq buf (current-buffer)))
637         (setq mail-reply-buffer buf)
638         (wl-draft-yank-from-mail-reply-buffer nil))
639     (wl-draft-yank-current-message-entity)))
640
641 (defun wl-draft-hide (editing-buffer)
642   "Hide the editing draft buffer if possible."
643   (interactive)
644   (when (and editing-buffer
645              (buffer-live-p editing-buffer))
646     (set-buffer editing-buffer)
647     (let ((sum-buf wl-draft-buffer-cur-summary-buffer)
648           fld-buf sum-win fld-win)
649       (if (and wl-draft-use-frame
650                (> (length (visible-frame-list)) 1))
651           ;; hide draft frame
652           (delete-frame)
653         ;; hide draft window
654         (or (one-window-p)
655             (delete-window)))
656       ;; stay folder window if required
657       (when wl-stay-folder-window
658         (if (setq fld-buf (get-buffer wl-folder-buffer-name))
659             (if (setq fld-win (get-buffer-window fld-buf))
660                 (select-window fld-win)
661               (if wl-draft-resume-folder-window ;; resume folder window
662                   (switch-to-buffer fld-buf)))))
663       (if (buffer-live-p sum-buf)
664           (if (setq sum-win (get-buffer-window sum-buf t))
665               ;; if Summary is on the frame, select it.
666               (select-window sum-win)
667             ;; if summary is not on the frame, switch to it.
668             (if (and wl-stay-folder-window
669                      (or wl-draft-resume-folder-window fld-win))
670                 (wl-folder-select-buffer sum-buf)
671               (switch-to-buffer sum-buf)))))))
672
673 (defun wl-draft-delete (editing-buffer)
674   "kill the editing draft buffer and delete the file corresponds to it."
675   (save-excursion
676     (when editing-buffer
677       (set-buffer editing-buffer)
678       (if wl-draft-buffer-file-name
679           (progn
680             (if (file-exists-p wl-draft-buffer-file-name)
681                 (delete-file wl-draft-buffer-file-name))
682             (let ((msg (and wl-draft-buffer-file-name
683                             (string-match "[0-9]+$" wl-draft-buffer-file-name)
684                             (string-to-int
685                              (match-string 0 wl-draft-buffer-file-name)))))
686               (wl-draft-config-info-operation msg 'delete))))
687       (set-buffer-modified-p nil)               ; force kill
688       (kill-buffer editing-buffer))))
689
690 (defun wl-draft-kill (&optional force-kill)
691   "Kill current draft buffer and quit editing."
692   (interactive "P")
693   (save-excursion
694     (when (and (or (eq major-mode 'wl-draft-mode)
695                    (eq major-mode 'mail-mode))
696                (or force-kill
697                    (y-or-n-p "Kill Current Draft?")))
698       (let ((cur-buf (current-buffer)))
699         (wl-draft-hide cur-buf)
700         (wl-draft-delete cur-buf)))
701     (message "")))
702
703 (defun wl-draft-fcc ()
704   "Add a new Fcc field, with file name completion."
705   (interactive)
706   (or (mail-position-on-field "fcc" t)  ;Put new field after exiting Fcc.
707       (mail-position-on-field "to"))
708   (insert "\nFcc: "))
709
710 ;; function for wl-sent-message-via
711
712 (defmacro wl-draft-sent-message-p (type)
713   (` (eq (nth 1 (assq (, type) wl-sent-message-via)) 'sent)))
714
715 (defmacro wl-draft-set-sent-message (type result &optional server-port)
716   (` (let ((element (assq (, type) wl-sent-message-via)))
717        (if element
718            (unless (eq (nth 1 element) (, result))
719              (setcdr element (list (, result) (, server-port)))
720              (setq wl-sent-message-modified t))
721          (push (list (, type) (, result) (, server-port)) wl-sent-message-via)
722          (setq wl-sent-message-modified t)))))
723
724 (defun wl-draft-sent-message-results ()
725   (let ((results wl-sent-message-via)
726         unplugged-via sent-via)
727     (while results
728       (cond ((eq (nth 1 (car results)) 'unplugged)
729              (push (caar results) unplugged-via))
730             ((eq (nth 1 (car results)) 'sent)
731              (push (caar results) sent-via)))
732       (setq results (cdr results)))
733     (list unplugged-via sent-via)))
734
735 (defun wl-draft-write-sendlog (status proto server to id)
736   "Write send log file, if `wl-draft-sendlog' is non-nil."
737   (when wl-draft-sendlog
738     (save-excursion
739       (let* ((tmp-buf (get-buffer-create " *wl-draft-sendlog*"))
740              (filename (expand-file-name wl-draft-sendlog-filename
741                                          elmo-msgdb-dir))
742              (filesize (nth 7 (file-attributes filename)))
743              (server (if server (concat " server=" server) ""))
744              (to (if to (cond
745                          ((memq proto '(fcc queue))
746                           (format " folder=\"%s\"" to))
747                          ((eq proto 'nntp)
748                           (format " ng=<%s>" to))
749                          (t
750                           (concat " to="
751                                   (mapconcat
752                                    'identity
753                                    (mapcar '(lambda(x) (format "<%s>" x)) to)
754                                    ","))))
755                    ""))
756              (id (if id (concat " id=" id) ""))
757              (time (wl-sendlog-time)))
758         (set-buffer tmp-buf)
759         (erase-buffer)
760         (insert (format "%s proto=%s stat=%s%s%s%s\n"
761                         time proto status server to id))
762         (if (and wl-draft-sendlog-max-size filesize
763                  (> filesize wl-draft-sendlog-max-size))
764             (rename-file filename (concat filename ".old") t))
765         (if (file-writable-p filename)
766             (write-region (point-min) (point-max)
767                           filename t 'no-msg)
768           (message (format "%s is not writable." filename)))
769         (kill-buffer tmp-buf)))))
770
771 (defun wl-draft-get-header-delimiter (&optional delete)
772   ;; If DELETE is non-nil, replace the header delimiter with a blank line
773   (let (delimline)
774     (goto-char (point-min))
775     (when (re-search-forward
776            (concat "^" (regexp-quote mail-header-separator) "$\\|^$") nil t)
777       (replace-match "")
778       (if delete
779           (forward-char -1))
780       (setq delimline (point-marker)))
781     delimline))
782
783 (defun wl-draft-send-mail-with-qmail ()
784   "Pass the prepared message buffer to qmail-inject.
785 Refer to the documentation for the variable `send-mail-function'
786 to find out how to use this."
787   (if (and wl-draft-qmail-send-plugged
788            (not (elmo-plugged-p)))
789       (wl-draft-set-sent-message 'mail 'unplugged)
790     ;; send the message
791     (let ((id (std11-field-body "Message-ID"))
792           (to (std11-field-body "To")))
793       (case
794           (as-binary-process
795            (apply
796             'call-process-region 1 (point-max) wl-qmail-inject-program
797             nil nil nil
798             wl-qmail-inject-args))
799         ;; qmail-inject doesn't say anything on it's stdout/stderr,
800         ;; we have to look at the retval instead
801         (0   (progn
802                (wl-draft-set-sent-message 'mail 'sent)
803                (wl-draft-write-sendlog 'ok 'qmail nil (list to) id)))
804         (1   (error "qmail-inject reported permanent failure"))
805         (111 (error "qmail-inject reported transient failure"))
806         ;; should never happen
807         (t   (error "qmail-inject reported unknown failure"))))))
808
809 (defun wl-draft-parse-msg-id-list-string (string)
810   "Get msg-id list from STRING."
811   (let (msg-id-list)
812     (dolist (parsed-id (std11-parse-msg-ids-string string))
813       (when (eq (car parsed-id) 'msg-id)
814         (setq msg-id-list (cons (std11-msg-id-string parsed-id)
815                                 msg-id-list))))
816     (nreverse msg-id-list)))
817
818 (defun wl-draft-parse-mailbox-list (field &optional remove-group-list)
819   "Get mailbox list of FIELD from current buffer.
820 The buffer is expected to be narrowed to just the headers of the message.
821 If optional argument REMOVE-GROUP-LIST is non-nil, remove group list content
822 from current buffer."
823   (save-excursion
824     (let ((case-fold-search t)
825           (inhibit-read-only t)
826           addresses address
827           mailbox-list beg seq has-group-list)
828       (goto-char (point-min))
829       (while (re-search-forward (concat "^" (regexp-quote field) "[\t ]*:")
830                                 nil t)
831         (setq beg (point))
832         (re-search-forward "^[^ \t]" nil 'move)
833         (beginning-of-line)
834         (skip-chars-backward "\n")
835         (setq seq (std11-lexical-analyze
836                    (buffer-substring-no-properties beg (point))))
837         (setq addresses (std11-parse-addresses seq))
838         (while addresses
839           (cond ((eq (car (car addresses)) 'group)
840                  (setq has-group-list t)
841                  (setq mailbox-list
842                        (nconc mailbox-list
843                               (mapcar
844                                'std11-address-string
845                                (nth 2 (car addresses))))))
846                 ((eq (car (car addresses)) 'mailbox)
847                  (setq address (nth 1 (car addresses)))
848                  (setq mailbox-list
849                        (nconc mailbox-list
850                               (list
851                                (std11-addr-to-string
852                                 (if (eq (car address) 'phrase-route-addr)
853                                     (nth 2 address)
854                                   (cdr address))))))))
855           (setq addresses (cdr addresses)))
856         (when (and remove-group-list has-group-list)
857           (delete-region beg (point))
858           (insert (wl-address-string-without-group-list-contents seq))))
859       mailbox-list)))
860
861 (defun wl-draft-deduce-address-list (buffer header-start header-end)
862   "Get address list suitable for smtp RCPT TO:<address>.
863 Group list content is removed if `wl-draft-remove-group-list-contents' is
864 non-nil."
865   (let ((fields        '("to" "cc" "bcc"))
866         (resent-fields '("resent-to" "resent-cc" "resent-bcc"))
867         (case-fold-search t)
868         addrs recipients)
869     (save-excursion
870       (save-restriction
871         (narrow-to-region header-start header-end)
872         (goto-char (point-min))
873         (save-excursion
874           (if (re-search-forward "^resent-to[\t ]*:" nil t)
875               (setq fields resent-fields)))
876         (while fields
877           (setq recipients
878                 (nconc recipients
879                        (wl-draft-parse-mailbox-list
880                         (car fields)
881                         wl-draft-remove-group-list-contents)))
882           (setq fields (cdr fields)))
883         recipients))))
884
885 ;;
886 ;; from Semi-gnus
887 ;;
888 (defun wl-draft-send-mail-with-smtp ()
889   "Send the prepared message buffer with SMTP."
890   (require 'smtp)
891   (let* ((errbuf (if mail-interactive
892                      (generate-new-buffer " smtp errors")
893                    0))
894          (case-fold-search t)
895          (default-case-fold-search t)
896          (sender (or wl-envelope-from
897                      (wl-address-header-extract-address wl-from)))
898          (delimline (save-excursion
899                       (goto-char (point-min))
900                       (re-search-forward
901                        (concat "^" (regexp-quote mail-header-separator)
902                                "$\\|^$") nil t)
903                       (point-marker)))
904          (smtp-server
905           (or wl-smtp-posting-server
906               ;; Compatibility stuff for FLIM 1.12.5 or earlier.
907               ;; They don't accept a function as the value of `smtp-server'.
908               (if (functionp smtp-server)
909                   (funcall
910                    smtp-server
911                    sender
912                    ;; no harm..
913                    (let (wl-draft-remove-group-list-contents)
914                      (wl-draft-deduce-address-list
915                       (current-buffer) (point-min) delimline)))
916                 (or smtp-server "localhost"))))
917          (smtp-service (or wl-smtp-posting-port smtp-service))
918          (smtp-local-domain (or smtp-local-domain wl-local-domain))
919          (id (std11-field-body "message-id"))
920          recipients)
921     (if (not (elmo-plugged-p smtp-server smtp-service))
922         (wl-draft-set-sent-message 'mail 'unplugged
923                                    (cons smtp-server smtp-service))
924       (unwind-protect
925           (save-excursion
926             ;; Instead of `smtp-deduce-address-list'.
927             (setq recipients (wl-draft-deduce-address-list
928                               (current-buffer) (point-min) delimline))
929             (unless recipients (error "No recipients"))
930             ;; Insert an extra newline if we need it to work around
931             ;; Sun's bug that swallows newlines.
932             (goto-char (1+ delimline))
933             (if (eval mail-mailer-swallows-blank-line)
934                 (newline))
935 ;;;         (run-hooks 'wl-mail-send-pre-hook)
936             (if mail-interactive
937                 (save-excursion
938                   (set-buffer errbuf)
939                   (erase-buffer)))
940             (wl-draft-delete-field "bcc" delimline)
941             (wl-draft-delete-field "resent-bcc" delimline)
942             (let (process-connection-type)
943               (as-binary-process
944                (when recipients
945                  (wl-smtp-extension-bind
946                   (condition-case err
947                       (smtp-send-buffer sender recipients (current-buffer))
948                     (error
949                      (wl-draft-write-sendlog 'failed 'smtp smtp-server
950                                              recipients id)
951                      (signal (car err) (cdr err)))))
952                  (wl-draft-set-sent-message 'mail 'sent)
953                  (wl-draft-write-sendlog
954                   'ok 'smtp smtp-server recipients id)))))
955         (if (bufferp errbuf)
956             (kill-buffer errbuf))))))
957
958 (defun wl-draft-send-mail-with-pop-before-smtp ()
959   "Send the prepared message buffer with POP-before-SMTP."
960   (require 'elmo-pop3)
961   (condition-case ()
962       (let ((session (elmo-pop3-get-session
963                       (list 'pop3
964                             (or wl-pop-before-smtp-user
965                                 elmo-pop3-default-user)
966                             (or wl-pop-before-smtp-authenticate-type
967                                 elmo-pop3-default-authenticate-type)
968                             (or wl-pop-before-smtp-server
969                                 elmo-pop3-default-server)
970                             (or wl-pop-before-smtp-port
971                                 elmo-pop3-default-port)
972                             (or wl-pop-before-smtp-stream-type
973                                 elmo-pop3-default-stream-type)))))
974         (when session (elmo-network-close-session session)))
975     (error))
976   (wl-draft-send-mail-with-smtp))
977
978 (defun wl-draft-insert-required-fields (&optional force-msgid)
979   "Insert Message-ID, Date, and From field.
980 If FORCE-MSGID, ignore 'wl-insert-message-id'."
981   ;; Insert Message-Id field...
982   (goto-char (point-min))
983   (when (and (or force-msgid
984                  wl-insert-message-id)
985              (not (re-search-forward "^Message-ID[ \t]*:" nil t)))
986     (insert (concat "Message-ID: "
987                     (wl-draft-make-message-id-string)
988                     "\n")))
989   ;; Insert date field.
990   (goto-char (point-min))
991   (or (re-search-forward "^Date[ \t]*:" nil t)
992       (wl-draft-insert-date-field))
993   ;; Insert from field.
994   (goto-char (point-min))
995   (or (re-search-forward "^From[ \t]*:" nil t)
996       (wl-draft-insert-from-field)))
997
998 (defun wl-draft-normal-send-func (editing-buffer kill-when-done)
999   "Send the message in the current buffer."
1000   (save-restriction
1001     (std11-narrow-to-header mail-header-separator)
1002     (wl-draft-insert-required-fields)
1003     ;; Delete null fields.
1004     (goto-char (point-min))
1005     (while (re-search-forward "^[^ \t\n:]+:[ \t]*\n" nil t)
1006       (replace-match ""))
1007     ;; ignore any blank lines in the header
1008     (while (re-search-forward "\n\n\n*" nil t)
1009       (replace-match "\n")))
1010   (run-hooks 'wl-mail-send-pre-hook) ;; X-PGP-Sig, Cancel-Lock
1011   (wl-draft-dispatch-message)
1012   (when kill-when-done
1013     ;; hide editing-buffer.
1014     (wl-draft-hide editing-buffer)
1015     ;; delete editing-buffer and its file.
1016     (wl-draft-delete editing-buffer)))
1017
1018 (defun wl-draft-dispatch-message (&optional mes-string)
1019   "Send the message in the current buffer.  Not modified the header fields."
1020   (let (delimline)
1021     (if (and wl-draft-verbose-send mes-string)
1022         (message mes-string))
1023     ;; get fcc folders.
1024     (setq delimline (wl-draft-get-header-delimiter t))
1025     (unless wl-draft-fcc-list
1026       (setq wl-draft-fcc-list (wl-draft-get-fcc-list delimline)))
1027     ;;
1028     (setq wl-sent-message-modified nil)
1029     (unwind-protect
1030         (progn
1031           (if (and (wl-message-mail-p)
1032                    (not (wl-draft-sent-message-p 'mail)))
1033               (funcall wl-draft-send-mail-function))
1034           (if (and (wl-message-news-p)
1035                    (not (wl-draft-sent-message-p 'news))
1036                    (not (wl-message-field-exists-p "Resent-to")))
1037               (funcall wl-draft-send-news-function)))
1038       ;;
1039       (let* ((status (wl-draft-sent-message-results))
1040              (unplugged-via (car status))
1041              (sent-via (nth 1 status)))
1042         ;; If one sent, process fcc folder.
1043         (if (and sent-via wl-draft-fcc-list)
1044             (progn
1045               (wl-draft-do-fcc (wl-draft-get-header-delimiter) wl-draft-fcc-list)
1046               (setq wl-draft-fcc-list nil)))
1047         (if wl-draft-use-cache
1048             (let ((id (std11-field-body "Message-ID"))
1049                   (elmo-enable-disconnected-operation t))
1050                 (elmo-file-cache-save id nil)))
1051         ;; If one unplugged, append queue.
1052         (when (and unplugged-via
1053                    wl-sent-message-modified)
1054           (if wl-draft-enable-queuing
1055               (wl-draft-queue-append wl-sent-message-via)
1056             (error "Unplugged")))
1057         (when wl-draft-verbose-send
1058           (if (and unplugged-via sent-via);; combined message
1059               (progn
1060                 (setq wl-draft-verbose-msg
1061                       (format "Sending%s and Queuing%s..."
1062                               sent-via unplugged-via))
1063                 (message (concat wl-draft-verbose-msg "done")))
1064             (if mes-string
1065                 (message (concat mes-string
1066                                  (if sent-via "done" "failed")))))))))
1067   (not wl-sent-message-modified)) ;; return value
1068
1069 (defun wl-draft-raw-send (&optional kill-when-done force-pre-hook mes-string)
1070   "Force send current buffer as raw message."
1071   (interactive)
1072   (save-excursion
1073     (let (wl-interactive-send
1074 ;;;       wl-draft-verbose-send
1075           (wl-mail-send-pre-hook (and force-pre-hook wl-mail-send-pre-hook))
1076 ;;;       wl-news-send-pre-hook
1077           mail-send-hook
1078           mail-send-actions)
1079       (wl-draft-send kill-when-done mes-string))))
1080
1081 (defun wl-draft-clone-local-variables ()
1082   (let ((locals (buffer-local-variables))
1083         result)
1084     (while locals
1085       (when (and (consp (car locals))
1086                  (car (car locals))
1087                  (string-match wl-draft-clone-local-variable-regexp
1088                                (symbol-name (car (car locals)))))
1089         (wl-append result (list (car (car locals)))))
1090       (setq locals (cdr locals)))
1091     result))
1092
1093 (defun wl-draft-send (&optional kill-when-done mes-string)
1094   "Send current draft message.
1095 If optional argument is non-nil, current draft buffer is killed"
1096   (interactive)
1097   ;; Don't call this explicitly.
1098   ;; Added to 'wl-draft-send-hook (by teranisi)
1099   ;; (wl-draft-config-exec)
1100   (run-hooks 'wl-draft-send-hook)
1101   (when (or (not wl-interactive-send)
1102             (y-or-n-p "Send current draft. OK?"))
1103     (let ((send-mail-function 'wl-draft-raw-send)
1104           (editing-buffer (current-buffer))
1105           (sending-buffer (wl-draft-generate-clone-buffer
1106                            " *wl-draft-sending-buffer*"
1107                            (append wl-draft-config-variables
1108                                    (wl-draft-clone-local-variables))))
1109           (wl-draft-verbose-msg nil)
1110           err)
1111       (unwind-protect
1112           (save-excursion (set-buffer sending-buffer)
1113             (if (and (not (wl-message-mail-p))
1114                      (not (wl-message-news-p)))
1115                 (error "No recipient is specified"))
1116             (expand-abbrev) ; for mail-abbrevs
1117             (run-hooks 'mail-send-hook) ; translate buffer
1118             (if wl-draft-verbose-send
1119                 (message (or mes-string "Sending...")))
1120             (funcall wl-draft-send-function editing-buffer kill-when-done)
1121             ;; Now perform actions on successful sending.
1122             (while mail-send-actions
1123               (condition-case ()
1124                   (apply (car (car mail-send-actions))
1125                          (cdr (car mail-send-actions)))
1126                 (error))
1127               (setq mail-send-actions (cdr mail-send-actions)))
1128 ;;          (if (or (eq major-mode 'wl-draft-mode)
1129 ;;                  (eq major-mode 'mail-mode))
1130 ;;              (local-set-key "\C-c\C-s" 'wl-draft-send)) ; override
1131             (if wl-draft-verbose-send
1132                 (message (concat (or wl-draft-verbose-msg
1133                                      mes-string "Sending...")
1134                                  "done"))))
1135         ;; kill sending buffer, anyway.
1136         (and (buffer-live-p sending-buffer)
1137              (kill-buffer sending-buffer))))))
1138
1139 (defun wl-draft-save ()
1140   "Save current draft."
1141   (interactive)
1142   (save-buffer)
1143   (wl-draft-config-info-operation
1144    (and (string-match "[0-9]+$" wl-draft-buffer-file-name)
1145         (string-to-int
1146          (match-string 0 wl-draft-buffer-file-name)))
1147    'save))
1148
1149 (defun wl-draft-mimic-kill-buffer ()
1150   "Kill the current (draft) buffer with query."
1151   (interactive)
1152   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
1153                                       (buffer-name))))
1154         wl-draft-use-frame)
1155     (if (or (not bufname)
1156             (string-equal bufname "")
1157             (string-equal bufname (buffer-name)))
1158         (wl-draft-save-and-exit)
1159       (kill-buffer bufname))))
1160
1161 (defun wl-draft-save-and-exit ()
1162   "Save current draft and exit current draft mode."
1163   (interactive)
1164   (wl-draft-save)
1165   (let ((editing-buffer (current-buffer)))
1166     (wl-draft-hide editing-buffer)
1167     (kill-buffer editing-buffer)))
1168   
1169 (defun wl-draft-send-and-exit ()
1170   "Send current draft message and kill it."
1171   (interactive)
1172   (wl-draft-send t))
1173
1174 (defun wl-draft-send-from-toolbar ()
1175   (interactive)
1176   (let ((wl-interactive-send t))
1177     (wl-draft-send-and-exit)))
1178
1179 (defun wl-draft-delete-field (field &optional delimline)
1180   (wl-draft-delete-fields (regexp-quote field) delimline))
1181
1182 (defun wl-draft-delete-fields (regexp &optional delimline)
1183   (save-restriction
1184     (unless delimline
1185       (if (search-forward "\n\n" nil t)
1186           (setq delimline (point))
1187         (setq delimline (point-max))))
1188     (narrow-to-region (point-min) delimline)
1189     (goto-char (point-min))
1190     (let ((regexp (concat "^" regexp ":"))
1191           (case-fold-search t)
1192           last)
1193       (while (not (eobp))
1194         (if (looking-at regexp)
1195             (progn
1196               (delete-region
1197                (point)
1198                (progn
1199                  (forward-line 1)
1200                  (if (re-search-forward "^[^ \t]" nil t)
1201                      (goto-char (match-beginning 0))
1202                    (point-max)))))
1203           (forward-line 1)
1204           (if (re-search-forward "^[^ \t]" nil t)
1205               (goto-char (match-beginning 0))
1206             (point-max)))))))
1207
1208 (defun wl-draft-get-fcc-list (header-end)
1209   (let (fcc-list
1210         (case-fold-search t))
1211     (or (markerp header-end) (error "header-end must be a marker"))
1212     (save-excursion
1213       (goto-char (point-min))
1214       (while (re-search-forward "^Fcc:[ \t]*" header-end t)
1215         (setq fcc-list
1216               (cons (buffer-substring-no-properties
1217                      (point)
1218                      (progn
1219                        (end-of-line)
1220                        (skip-chars-backward " \t")
1221                        (point)))
1222                     fcc-list))
1223         (save-match-data
1224           (wl-folder-confirm-existence
1225            (wl-folder-get-elmo-folder (eword-decode-string (car fcc-list)))))
1226         (delete-region (match-beginning 0)
1227                        (progn (forward-line 1) (point)))))
1228     fcc-list))
1229
1230 (defun wl-draft-do-fcc (header-end &optional fcc-list)
1231   (let ((send-mail-buffer (current-buffer))
1232         (tembuf (generate-new-buffer " fcc output"))
1233         (case-fold-search t)
1234         beg end)
1235     (or (markerp header-end) (error "header-end must be a marker"))
1236     (save-excursion
1237       (unless fcc-list
1238         (setq fcc-list (wl-draft-get-fcc-list header-end)))
1239       (set-buffer tembuf)
1240       (erase-buffer)
1241       ;; insert just the headers to avoid moving the gap more than
1242       ;; necessary (the message body could be arbitrarily huge.)
1243       (insert-buffer-substring send-mail-buffer 1 header-end)
1244       (wl-draft-insert-required-fields t)
1245       (goto-char (point-max))
1246       (insert-buffer-substring send-mail-buffer header-end)
1247       (let ((id (std11-field-body "Message-ID"))
1248             (elmo-enable-disconnected-operation t)
1249             cache-saved)
1250         (while fcc-list
1251           (unless (or cache-saved
1252                       (elmo-folder-plugged-p
1253                        (wl-folder-get-elmo-folder (car fcc-list))))
1254             (elmo-file-cache-save id nil) ;; for disconnected operation
1255             (setq cache-saved t))
1256           (if (elmo-folder-append-buffer
1257                (wl-folder-get-elmo-folder
1258                 (eword-decode-string (car fcc-list)))
1259                id)
1260               (wl-draft-write-sendlog 'ok 'fcc nil (car fcc-list) id)
1261             (wl-draft-write-sendlog 'failed 'fcc nil (car fcc-list) id))
1262           (setq fcc-list (cdr fcc-list)))))
1263     (kill-buffer tembuf)))
1264
1265 (defun wl-draft-on-field-p ()
1266   (if (< (point)
1267          (save-excursion
1268            (goto-char (point-min))
1269            (search-forward (concat "\n" mail-header-separator "\n") nil 0)
1270            (point)))
1271       (if (bolp)
1272           (if (bobp)
1273               t
1274             (save-excursion
1275               (forward-line -1)
1276               (if (or (looking-at ".*,[ \t]?$")
1277                       (looking-at "^[^ \t]+:[ \t]+.*:$")); group list name
1278                   nil t)))
1279         (let ((pos (point)))
1280           (save-excursion
1281             (beginning-of-line)
1282             (if (looking-at "^[ \t]")
1283                 nil
1284               (if (re-search-forward ":" pos t) nil t)))))))
1285
1286 (defun wl-draft-random-alphabet ()
1287   (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)))
1288     (nth (abs (% (random) 26)) alphabet)))
1289
1290 ;;;###autoload
1291 (defun wl-draft (&optional to subject in-reply-to cc references newsgroups
1292                            mail-followup-to
1293                            content-type content-transfer-encoding
1294                            body edit-again summary-buf from)
1295   "Write and send mail/news message with Wanderlust."
1296   (interactive)
1297   (unless (featurep 'wl)
1298     (require 'wl))
1299   (unless wl-init
1300     (wl-load-profile))
1301   (wl-init) ;; returns immediately if already initialized.
1302   (if (interactive-p)
1303       (setq summary-buf (wl-summary-get-buffer (wl-summary-buffer-folder-name))))
1304   (let ((draft-folder (wl-folder-get-elmo-folder wl-draft-folder))
1305         buf-name file-name num wl-demo change-major-mode-hook)
1306     (if (not (elmo-folder-message-file-p draft-folder))
1307         (error "%s folder cannot be used for draft folder" wl-draft-folder))
1308     (setq num (elmo-max-of-list
1309                (or (elmo-folder-list-messages draft-folder) '(0))))
1310     (setq num (+ 1 num))
1311     ;; To get unused buffer name.
1312     (while (get-buffer (concat wl-draft-folder "/" (int-to-string num)))
1313       (setq num (+ 1 num)))
1314     (setq buf-name (find-file-noselect
1315                     (setq file-name
1316                           (elmo-message-file-name
1317                            (wl-folder-get-elmo-folder wl-draft-folder)
1318                            num))))
1319     (if wl-draft-use-frame
1320         (switch-to-buffer-other-frame buf-name)
1321       (switch-to-buffer buf-name))
1322     (set-buffer buf-name)
1323     (if (not (string-match (regexp-quote wl-draft-folder)
1324                            (buffer-name)))
1325         (rename-buffer (concat wl-draft-folder "/" (int-to-string num))))
1326     (if (or (eq wl-draft-reply-buffer-style 'full)
1327             (eq this-command 'wl-draft)
1328             (eq this-command 'wl-summary-write)
1329             (eq this-command 'wl-summary-write-current-folder))
1330         (delete-other-windows))
1331     (auto-save-mode -1)
1332     (wl-draft-mode)
1333     (setq wl-sent-message-via nil)
1334     (if (stringp (or from wl-from))
1335         (insert "From: " (or from wl-from) "\n"))
1336     (and (or (interactive-p)
1337              (eq this-command 'wl-summary-write)
1338              to)
1339          (insert "To: " (or to "") "\n"))
1340     (and cc (insert "Cc: " (or cc "") "\n"))
1341     (insert "Subject: " (or subject "") "\n")
1342     (and newsgroups (insert "Newsgroups: " newsgroups "\n"))
1343     (and mail-followup-to (insert "Mail-Followup-To: " mail-followup-to "\n"))
1344     (and wl-insert-mail-reply-to
1345          (insert "Mail-Reply-To: "
1346                  (wl-address-header-extract-address
1347                   wl-from) "\n"))
1348     (and in-reply-to (insert "In-Reply-To: " in-reply-to "\n"))
1349     (and references (insert "References: " references "\n"))
1350     (insert (funcall wl-generate-mailer-string-function) "\n")
1351     (setq wl-draft-buffer-file-name file-name)
1352     (if mail-default-reply-to
1353         (insert "Reply-To: " mail-default-reply-to "\n"))
1354     (wl-draft-insert-ccs "Bcc: " (or wl-bcc
1355                                (and mail-self-blind (user-login-name))))
1356     (wl-draft-insert-ccs "Fcc: " wl-fcc)
1357     (if wl-organization
1358         (insert "Organization: " wl-organization "\n"))
1359     (and wl-auto-insert-x-face
1360          (file-exists-p wl-x-face-file)
1361          (wl-draft-insert-x-face-field-here))
1362     (if mail-default-headers
1363         (insert mail-default-headers))
1364     (if (not (= (preceding-char) ?\n))
1365         (insert ?\n))
1366     (if edit-again
1367         (let (start)
1368           (setq start (point))
1369           (when content-type
1370             (insert "Content-type: " content-type "\n"))
1371           (when content-transfer-encoding
1372             (insert "Content-Transfer-Encoding: " content-transfer-encoding "\n"))
1373           (if (or content-type content-transfer-encoding)
1374               (insert "\n"))
1375           (and body (insert body))
1376           (save-restriction
1377             (narrow-to-region start (point))
1378             (and edit-again
1379                  (wl-draft-decode-message-in-buffer))
1380             (widen)
1381             (goto-char start)
1382             (put-text-property (point)
1383                                (progn
1384                                  (insert mail-header-separator "\n")
1385                                  (1- (point)))
1386                                'category 'mail-header-separator)))
1387       (put-text-property (point)
1388                          (progn
1389                            (insert mail-header-separator "\n")
1390                            (1- (point)))
1391                          'category 'mail-header-separator)
1392       (and body (insert body)))
1393     (if wl-on-nemacs
1394         (push-mark (point) t)
1395       (push-mark (point) t t))
1396     (as-binary-output-file
1397      (write-region (point-min)(point-max) wl-draft-buffer-file-name
1398                    nil t))
1399     (wl-draft-editor-mode)
1400     (wl-draft-overload-functions)
1401     (wl-highlight-headers 'for-draft)
1402     (goto-char (point-min))
1403     (setq wl-draft-config-exec-flag t)
1404     (if (interactive-p)
1405         (run-hooks 'wl-mail-setup-hook))
1406     (wl-user-agent-compose-internal) ;; user-agent
1407     (cond ((eq this-command 'wl-summary-write-current-newsgroup)
1408            (mail-position-on-field "Subject"))
1409           ((and (interactive-p) (null to))
1410            (mail-position-on-field "To"))
1411           (t
1412            (goto-char (point-max))))
1413     (setq wl-draft-buffer-cur-summary-buffer (or summary-buf
1414                                                  (get-buffer
1415                                                   wl-summary-buffer-name)))
1416     buf-name))
1417
1418 (defsubst wl-draft-insert-ccs (str cc)
1419   (let ((field
1420          (if (functionp cc)
1421              (funcall cc)
1422            cc)))
1423     (if (and field
1424              (null (and wl-draft-delete-myself-from-bcc-fcc
1425                         (elmo-list-member
1426                          (mapcar 'wl-address-header-extract-address
1427                                  (append
1428                                   (wl-parse-addresses (std11-field-body "To"))
1429                                   (wl-parse-addresses (std11-field-body "Cc"))))
1430                          (mapcar 'downcase wl-subscribed-mailing-list)))))
1431         (insert str field "\n"))))
1432
1433 (defun wl-draft-elmo-nntp-send ()
1434   (let ((elmo-nntp-post-pre-hook wl-news-send-pre-hook)
1435         (elmo-nntp-default-user
1436          (or wl-nntp-posting-user elmo-nntp-default-user))
1437         (elmo-nntp-default-server
1438          (or wl-nntp-posting-server elmo-nntp-default-server))
1439         (elmo-nntp-default-port
1440          (or wl-nntp-posting-port elmo-nntp-default-port))
1441         (elmo-nntp-default-stream-type
1442          (or wl-nntp-posting-stream-type elmo-nntp-default-stream-type)))
1443     (if (not (elmo-plugged-p elmo-nntp-default-server elmo-nntp-default-port))
1444         (wl-draft-set-sent-message 'news 'unplugged
1445                                    (cons elmo-nntp-default-server
1446                                          elmo-nntp-default-port))
1447       (elmo-nntp-post elmo-nntp-default-server (current-buffer))
1448       (wl-draft-set-sent-message 'news 'sent)
1449       (wl-draft-write-sendlog 'ok 'nntp elmo-nntp-default-server
1450                               (std11-field-body "Newsgroups")
1451                               (std11-field-body "Message-ID")))))
1452
1453 (defun wl-draft-generate-clone-buffer (name &optional local-variables)
1454   "generate clone of current buffer named NAME."
1455   (let ((editing-buffer (current-buffer)))
1456     (save-excursion
1457       (set-buffer (generate-new-buffer name))
1458       (erase-buffer)
1459       (wl-draft-mode)
1460       (wl-draft-editor-mode)
1461       (insert-buffer editing-buffer)
1462       (message "")
1463       (while local-variables
1464         (make-local-variable (car local-variables))
1465         (set (car local-variables)
1466              (save-excursion
1467                (set-buffer editing-buffer)
1468                (symbol-value (car local-variables))))
1469         (setq local-variables (cdr local-variables)))
1470       (current-buffer))))
1471
1472 (defun wl-draft-reedit (number)
1473   (let ((draft-folder (wl-folder-get-elmo-folder wl-draft-folder))
1474         (wl-draft-reedit t)
1475         buf-name file-name change-major-mode-hook)
1476     (setq file-name (elmo-message-file-name draft-folder number))
1477     (unless (file-exists-p file-name)
1478       (error "File %s does not exist" file-name))
1479     (setq buf-name (find-file-noselect file-name))
1480     (if wl-draft-use-frame
1481         (switch-to-buffer-other-frame buf-name)
1482       (switch-to-buffer buf-name))
1483     (set-buffer buf-name)
1484     (if (not (string-match (regexp-quote wl-draft-folder)
1485                            (buffer-name)))
1486         (rename-buffer (concat wl-draft-folder "/" (buffer-name))))
1487     (auto-save-mode -1)
1488     (wl-draft-mode)
1489     (setq wl-sent-message-via nil)
1490     (setq wl-draft-buffer-file-name file-name)
1491     (wl-draft-config-info-operation number 'load)
1492     (goto-char (point-min))
1493     (or (re-search-forward "\n\n" nil t)
1494         (search-forward (concat mail-header-separator "\n") nil t))
1495     (if wl-on-nemacs
1496         (push-mark (point) t)
1497       (push-mark (point) t t))
1498     (write-region (point-min)(point-max) wl-draft-buffer-file-name
1499                   nil t)
1500     (wl-draft-overload-functions)
1501     (wl-draft-editor-mode)
1502     (wl-highlight-headers 'for-draft)
1503     (run-hooks 'wl-draft-reedit-hook)
1504     (goto-char (point-max))
1505     buf-name
1506     ))
1507
1508 (defmacro wl-draft-body-goto-top ()
1509   (` (progn
1510        (goto-char (point-min))
1511        (if (re-search-forward mail-header-separator nil t)
1512            (forward-char 1)
1513          (goto-char (point-max))))))
1514
1515 (defmacro wl-draft-body-goto-bottom ()
1516   (` (goto-char (point-max))))
1517
1518 (defmacro wl-draft-config-body-goto-header ()
1519   (` (progn
1520        (goto-char (point-min))
1521        (if (re-search-forward mail-header-separator nil t)
1522            (beginning-of-line)
1523          (goto-char (point-max))))))
1524
1525 (defun wl-draft-config-sub-body (content)
1526   (wl-draft-body-goto-top)
1527   (delete-region (point) (point-max))
1528   (if content (insert (eval content))))
1529
1530 (defun wl-draft-config-sub-top (content)
1531   (wl-draft-body-goto-top)
1532   (if content (insert (eval content))))
1533
1534 (defun wl-draft-config-sub-bottom (content)
1535   (wl-draft-body-goto-bottom)
1536   (if content (insert (eval content))))
1537
1538 (defun wl-draft-config-sub-header (content)
1539   (wl-draft-config-body-goto-header)
1540   (if content (insert (concat (eval content) "\n"))))
1541
1542 (defsubst wl-draft-config-sub-file (content)
1543   (let ((coding-system-for-read wl-cs-autoconv)
1544         (file (expand-file-name (eval content))))
1545     (if (file-exists-p file)
1546         (insert-file-contents file)
1547       (error "%s: no exists file" file))))
1548
1549 (defun wl-draft-config-sub-body-file (content)
1550   (wl-draft-body-goto-top)
1551   (delete-region (point) (point-max))
1552   (wl-draft-config-sub-file content))
1553
1554 (defun wl-draft-config-sub-top-file (content)
1555   (wl-draft-body-goto-top)
1556   (wl-draft-config-sub-file content))
1557
1558 (defun wl-draft-config-sub-bottom-file (content)
1559   (wl-draft-body-goto-bottom)
1560   (wl-draft-config-sub-file content))
1561
1562 (defun wl-draft-config-sub-header-file (content)
1563   (wl-draft-config-body-goto-header)
1564   (wl-draft-config-sub-file content))
1565
1566 (defun wl-draft-config-sub-template (content)
1567   (setq wl-draft-config-variables
1568         (wl-template-insert (eval content))))
1569
1570 (defun wl-draft-config-sub-x-face (content)
1571   (if (and (string-match "\\.xbm\\(\\.gz\\)?$" content)
1572            (fboundp 'x-face-insert)) ; x-face.el is installed.
1573       (x-face-insert content)
1574     (wl-draft-replace-field "X-Face" (elmo-get-file-string content t) t)))
1575
1576 (defsubst wl-draft-config-sub-func (field content)
1577   (let (func)
1578     (if (setq func (assq field wl-draft-config-sub-func-alist))
1579         (let (wl-draft-config-variables)
1580           (funcall (cdr func) content)
1581           ;; for wl-draft-config-sub-template
1582           (cons t wl-draft-config-variables)))))
1583
1584 (defsubst wl-draft-config-exec-sub (clist)
1585   (let (config local-variables)
1586     (while clist
1587       (setq config (car clist))
1588       (cond
1589        ((consp config)
1590         (let ((field (car config))
1591               (content (cdr config))
1592               ret-val)
1593           (cond
1594            ((stringp field)
1595             (wl-draft-replace-field field (eval content) t))
1596            ((setq ret-val (wl-draft-config-sub-func field content))
1597             (if (cdr ret-val) ;; for wl-draft-config-sub-template
1598                 (wl-append local-variables (cdr ret-val))))
1599            ((boundp field) ;; variable
1600             (make-local-variable field)
1601             (set field (eval content))
1602             (wl-append local-variables (list field)))
1603            (t
1604             (error "%s: not variable" field)))))
1605        ((or (functionp config)
1606             (and (symbolp config)
1607                  (fboundp config)))
1608         (funcall config))
1609        (t
1610         (error "%s: not supported type" config)))
1611       (setq clist (cdr clist)))
1612     local-variables))
1613
1614 (defun wl-draft-prepared-config-exec (&optional config-alist reply-buf)
1615   "Change headers in draft preparation time."
1616   (interactive)
1617   (unless wl-draft-reedit
1618     (let ((config-alist
1619            (or config-alist
1620                (and (boundp 'wl-draft-prepared-config-alist)
1621                     wl-draft-prepared-config-alist)     ;; For compatible.
1622                wl-draft-config-alist)))
1623       (if config-alist
1624           (wl-draft-config-exec config-alist reply-buf)))))
1625
1626 (defun wl-draft-config-exec (&optional config-alist reply-buf)
1627   "Change headers in draft sending time."
1628   (interactive)
1629   (let ((case-fold-search t)
1630         (alist (or config-alist wl-draft-config-alist))
1631         (reply-buf (or reply-buf (and (buffer-live-p wl-draft-reply-buffer)
1632                                       wl-draft-reply-buffer)))
1633         (local-variables wl-draft-config-variables)
1634         key clist found)
1635     (when (and (or (interactive-p)
1636                    wl-draft-config-exec-flag)
1637                alist)
1638       (save-excursion
1639         (catch 'done
1640           (while alist
1641             (setq key (caar alist)
1642                   clist (cdar alist))
1643             (cond
1644              ((eq key 'reply)
1645               (when (and
1646                      reply-buf
1647                      (save-excursion
1648                        (set-buffer reply-buf)
1649                        (save-restriction
1650                          (std11-narrow-to-header)
1651                          (goto-char (point-min))
1652                          (re-search-forward (car clist) nil t))))
1653                 (wl-draft-config-exec-sub (cdr clist))
1654                 (setq found t)))
1655              ((stringp key)
1656               (when (save-restriction
1657                       (std11-narrow-to-header mail-header-separator)
1658                       (goto-char (point-min))
1659                       (re-search-forward key nil t))
1660                 (wl-append local-variables
1661                            (wl-draft-config-exec-sub clist))
1662                 (setq found t)))
1663              ((eval key)
1664               (wl-append local-variables
1665                          (wl-draft-config-exec-sub clist))
1666               (setq found t)))
1667             (if (and found wl-draft-config-matchone)
1668                 (throw 'done t))
1669             (setq alist (cdr alist))))
1670         (if found
1671             (setq wl-draft-config-exec-flag nil))
1672         (run-hooks 'wl-draft-config-exec-hook)
1673         (put-text-property (point-min)(point-max) 'face nil)
1674         (wl-highlight-message (point-min)(point-max) t)
1675         (setq wl-draft-config-variables
1676               (elmo-uniq-list local-variables))))))
1677
1678 (defun wl-draft-replace-field (field content &optional add)
1679   (save-excursion
1680     (save-restriction
1681       (let ((case-fold-search t)
1682             (inhibit-read-only t) ;; added by teranisi.
1683             beg)
1684         (std11-narrow-to-header mail-header-separator)
1685         (goto-char (point-min))
1686         (if (re-search-forward (concat "^" (regexp-quote field) ":") nil t)
1687             (if content
1688                 ;; replace field
1689                 (progn
1690                   (setq beg (point))
1691                   (re-search-forward "^[^ \t]" nil 'move)
1692                   (beginning-of-line)
1693                   (skip-chars-backward "\n")
1694                   (delete-region beg (point))
1695                   (insert " " content))
1696               ;; delete field
1697               (save-excursion
1698                 (beginning-of-line)
1699                 (setq beg (point)))
1700               (re-search-forward "^[^ \t]" nil 'move)
1701               (beginning-of-line)
1702               (delete-region beg (point)))
1703           (when (and add content)
1704             ;; add field
1705             (goto-char (point-max))
1706             (insert (concat field ": " content "\n"))))))))
1707
1708 (defun wl-draft-config-info-operation (msg operation)
1709   (let* ((msgdb-dir (elmo-folder-msgdb-path (wl-folder-get-elmo-folder
1710                                              wl-draft-folder)))
1711          (filename
1712           (expand-file-name
1713            (format "%s-%d" wl-draft-config-save-filename msg)
1714            msgdb-dir))
1715          element alist variable)
1716     (cond
1717      ((eq operation 'save)
1718       (let ((variables (elmo-uniq-list wl-draft-config-variables)))
1719         (while (setq variable (pop variables))
1720           (when (boundp variable)
1721             (wl-append alist
1722                        (list (cons variable (eval variable))))))
1723         (elmo-object-save filename alist)))
1724      ((eq operation 'load)
1725       (setq alist (elmo-object-load filename))
1726       (while (setq element (pop alist))
1727         (set (make-local-variable (car element)) (cdr element))
1728         (wl-append wl-draft-config-variables (list (car element)))))
1729      ((eq operation 'delete)
1730       (if (file-exists-p filename)
1731           (delete-file filename))))))
1732
1733 (defun wl-draft-queue-info-operation (msg operation
1734                                           &optional add-sent-message-via)
1735   (let* ((msgdb-dir (elmo-folder-msgdb-path
1736                      (wl-folder-get-elmo-folder wl-queue-folder)))
1737          (filename
1738           (expand-file-name
1739            (format "%s-%d" wl-draft-queue-save-filename msg)
1740            msgdb-dir))
1741          element alist variable)
1742     (cond
1743      ((eq operation 'save)
1744       (let ((variables (elmo-uniq-list
1745                         (append wl-draft-queue-save-variables
1746                                 wl-draft-config-variables
1747                                 (list 'wl-draft-fcc-list)))))
1748         (if add-sent-message-via
1749             (push 'wl-sent-message-via variables))
1750         (while (setq variable (pop variables))
1751           (when (boundp variable)
1752             (wl-append alist
1753                        (list (cons variable (eval variable))))))
1754         (elmo-object-save filename alist)))
1755      ((eq operation 'load)
1756       (setq alist (elmo-object-load filename))
1757       (while (setq element (pop alist))
1758         (set (make-local-variable (car element)) (cdr element))))
1759      ((eq operation 'get-sent-via)
1760       (setq alist (elmo-object-load filename))
1761       (cdr (assq 'wl-sent-message-via alist)))
1762      ((eq operation 'delete)
1763       (if (file-exists-p filename)
1764           (delete-file filename))))))
1765
1766 (defun wl-draft-queue-append (wl-sent-message-via)
1767   (if wl-draft-verbose-send
1768       (message "Queuing..."))
1769   (let ((send-buffer (current-buffer))
1770         (folder (wl-folder-get-elmo-folder wl-queue-folder))
1771         (message-id (std11-field-body "Message-ID")))
1772     (if (elmo-folder-append-buffer folder t)
1773         (progn
1774           (wl-draft-queue-info-operation
1775            (car (elmo-folder-status folder))
1776            'save wl-sent-message-via)
1777           (wl-draft-write-sendlog 'ok 'queue nil wl-queue-folder message-id)
1778           (when wl-draft-verbose-send
1779             (setq wl-draft-verbose-msg "Queuing...")
1780             (message "Queuing...done")))
1781       (wl-draft-write-sendlog 'failed 'queue nil wl-queue-folder message-id)
1782       (error "Queuing failed"))))
1783
1784 (defun wl-draft-queue-flush ()
1785   "Flush draft queue."
1786   (interactive)
1787   (let* ((queue-folder (wl-folder-get-elmo-folder wl-queue-folder))
1788          (msgs2 (elmo-folder-list-messages queue-folder))
1789          (i 0)
1790          (performed 0)
1791          (wl-draft-queue-flushing t)
1792          msgs failure len buffer msgid sent-via)
1793     ;; get plugged send message
1794     (while msgs2
1795       (setq sent-via (wl-draft-queue-info-operation (car msgs2) 'get-sent-via))
1796       (catch 'found
1797         (while sent-via
1798           (when (and (eq (nth 1 (car sent-via)) 'unplugged)
1799                      (elmo-plugged-p
1800                       (car (nth 2 (car sent-via)))
1801                       (cdr (nth 2 (car sent-via)))))
1802             (wl-append msgs (list (car msgs2)))
1803             (throw 'found t))
1804           (setq sent-via (cdr sent-via))))
1805       (setq msgs2 (cdr msgs2)))
1806     (when (> (setq len (length msgs)) 0)
1807       (if (elmo-y-or-n-p (format
1808                           "%d message(s) are in the sending queue. Send now?"
1809                           len)
1810                          (not elmo-dop-flush-confirm) t)
1811           (progn
1812             (save-excursion
1813               (setq buffer (get-buffer-create " *wl-draft-queue-flush*"))
1814               (set-buffer buffer)
1815               (while msgs
1816                 ;; reset buffer local variables
1817                 (kill-all-local-variables)
1818                 (erase-buffer)
1819                 (setq i (+ 1 i)
1820                       failure nil)
1821                 (setq wl-sent-message-via nil)
1822                 (wl-draft-queue-info-operation (car msgs) 'load)
1823                 (elmo-message-fetch queue-folder
1824                                     (car msgs)
1825                                     (elmo-make-fetch-strategy 'entire)
1826                                     nil (current-buffer))
1827                 (condition-case err
1828                     (setq failure (funcall
1829                                    wl-draft-queue-flush-send-function
1830                                    (format "Sending (%d/%d)..." i len)))
1831 ;;;               (wl-draft-raw-send nil nil
1832 ;;;                                  (format "Sending (%d/%d)..." i len))
1833                   (error
1834                    (elmo-display-error err t)
1835                    (setq failure t))
1836                   (quit
1837                    (setq failure t)))
1838                 (unless failure
1839                   (elmo-folder-delete-messages
1840                    queue-folder (cons (car msgs) nil))
1841                   (wl-draft-queue-info-operation (car msgs) 'delete)
1842                   (setq performed (+ 1 performed)))
1843                 (setq msgs (cdr msgs)))
1844               (kill-buffer buffer)
1845               (message "%d message(s) are sent." performed)))
1846         (message "%d message(s) are remained to be sent." len))
1847       len)))
1848
1849 (defun wl-jump-to-draft-buffer (&optional arg)
1850   "Jump to the draft if exists."
1851   (interactive "P")
1852   (if arg
1853       (wl-jump-to-draft-folder)
1854     (let ((bufs (buffer-list))
1855           (draft-regexp (concat
1856                          "^" (regexp-quote
1857                               (elmo-localdir-folder-directory-internal
1858                                (wl-folder-get-elmo-folder wl-draft-folder)))))
1859           buf draft-bufs)
1860       (while bufs
1861         (if (and
1862              (setq buf (buffer-file-name (car bufs)))
1863              (string-match draft-regexp buf))
1864             (setq draft-bufs (cons (buffer-name (car bufs)) draft-bufs)))
1865         (setq bufs (cdr bufs)))
1866       (cond
1867        ((null draft-bufs)
1868         (message "No draft buffer exist."))
1869        (t
1870         (setq draft-bufs
1871               (sort draft-bufs (function (lambda (a b) (not (string< a b))))))
1872         (if (setq buf (cdr (member (buffer-name) draft-bufs)))
1873             (setq buf (car buf))
1874           (setq buf (car draft-bufs)))
1875         (switch-to-buffer buf))))))
1876
1877 (defun wl-jump-to-draft-folder ()
1878   (let ((msgs (reverse (elmo-folder-list-messages (wl-folder-get-elmo-folder
1879                                                    wl-draft-folder))))
1880         (mybuf (buffer-name))
1881         msg buf)
1882     (if (not msgs)
1883         (message "No draft message exist.")
1884       (if (string-match (concat "^" wl-draft-folder "/") mybuf)
1885           (setq msg (cadr (memq
1886                            (string-to-int (substring mybuf (match-end 0)))
1887                            msgs))))
1888       (or msg (setq msg (car msgs)))
1889       (if (setq buf (get-buffer (format "%s/%d" wl-draft-folder msg)))
1890           (switch-to-buffer buf)
1891         (wl-draft-reedit msg)))))
1892
1893 (defun wl-draft-highlight-and-recenter (&optional n)
1894   (interactive "P")
1895   (if wl-highlight-body-too
1896       (let ((beg (point-min))
1897             (end (point-max)))
1898         (put-text-property beg end 'face nil)
1899         (wl-highlight-message beg end t)))
1900   (recenter n))
1901
1902 ;;;; user-agent support by Sen Nagata
1903
1904 ;; this appears to be necessarily global...
1905 (defvar wl-user-agent-compose-p nil)
1906 (defvar wl-user-agent-headers-and-body-alist nil)
1907
1908 ;; this should be a generic function for mail-mode -- i wish there was
1909 ;; something like it in sendmail.el
1910 (defun wl-user-agent-insert-header (header-name header-value)
1911   "Insert HEADER-NAME w/ value HEADER-VALUE into a message."
1912   ;; it seems like overriding existing headers is acceptable -- should
1913   ;; we provide an option?
1914   
1915   ;; plan was: unfold header (might be folded), remove existing value, insert
1916   ;;           new value
1917   ;; wl doesn't seem to fold header lines yet anyway :-)
1918   
1919   (let ((kill-whole-line t)
1920         end-of-line)
1921     (mail-position-on-field (capitalize header-name))
1922     (setq end-of-line (point))
1923     (beginning-of-line)
1924     (re-search-forward ":" end-of-line)
1925     (insert (concat " " header-value "\n"))
1926     (kill-line)))
1927
1928 ;; this should be a generic function for mail-mode -- i wish there was
1929 ;; something like it in sendmail.el
1930 ;;
1931 ;; ** haven't dealt w/ case where the body is already set **
1932 (defun wl-user-agent-insert-body (body-text)
1933   "Insert a body of text, BODY-TEXT, into a message."
1934   ;; code defensively... :-P
1935   (goto-char (point-min))
1936   (search-forward mail-header-separator)
1937   (forward-line 1)
1938   (insert body-text))
1939
1940 ;;;###autoload
1941 (defun wl-user-agent-compose (&optional to subject other-headers continue
1942                                         switch-function yank-action
1943                                         send-actions)
1944   "Support the `compose-mail' interface for wl.
1945 Only support for TO, SUBJECT, and OTHER-HEADERS has been implemented.
1946 Support for CONTINUE, YANK-ACTION, and SEND-ACTIONS has not
1947 been implemented yet.  Partial support for SWITCH-FUNCTION now supported."
1948
1949   (unless (featurep 'wl)
1950     (require 'wl))
1951   ;; protect these -- to and subject get bound at some point, so it looks
1952   ;; to be necessary to protect the values used w/in
1953   (let ((wl-user-agent-headers-and-body-alist other-headers)
1954         (wl-draft-use-frame (eq switch-function 'switch-to-buffer-other-frame))
1955         (wl-draft-reply-buffer-style 'split))
1956     (when (eq switch-function 'switch-to-buffer-other-window)
1957       (when (one-window-p t)
1958         (if (window-minibuffer-p) (other-window 1))
1959         (split-window))
1960       (other-window 1))
1961     (if to
1962         (if (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
1963                                    'ignore-case)
1964             (setcdr
1965              (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
1966                                     'ignore-case)
1967              to)
1968           (setq wl-user-agent-headers-and-body-alist
1969                 (cons (cons "to" to)
1970                       wl-user-agent-headers-and-body-alist))))
1971     (if subject
1972         (if (wl-string-match-assoc "subject"
1973                                    wl-user-agent-headers-and-body-alist
1974                                    'ignore-case)
1975             (setcdr
1976              (wl-string-match-assoc "subject"
1977                                     wl-user-agent-headers-and-body-alist
1978                                     'ignore-case)
1979              subject)
1980           (setq wl-user-agent-headers-and-body-alist
1981                 (cons (cons "subject" subject)
1982                       wl-user-agent-headers-and-body-alist))))
1983     ;; i think this is what we want to use...
1984     (unwind-protect
1985         (progn
1986           ;; tell the hook-function to do its stuff
1987           (setq wl-user-agent-compose-p t)
1988           ;; because to get the hooks working, wl-draft has to think it has
1989           ;; been called interactively
1990           (call-interactively 'wl-draft))
1991       (setq wl-user-agent-compose-p nil))))
1992
1993 (defun wl-user-agent-compose-internal ()
1994   "Manipulate headers and/or a body of a draft message."
1995   ;; being called from wl-user-agent-compose?
1996   (if wl-user-agent-compose-p
1997       (progn
1998         ;; insert headers
1999         (let ((headers wl-user-agent-headers-and-body-alist)
2000               (case-fold-search t))
2001           (while headers
2002             ;; skip body
2003             (if (not (string-match "^body$" (car (car headers))))
2004                 (wl-user-agent-insert-header
2005                  (car (car headers)) (cdr (car headers)))
2006               t)
2007             (setq headers (cdr headers))))
2008         ;; highlight headers (from wl-draft in wl-draft.el)
2009         (wl-highlight-headers 'for-draft)
2010         ;; insert body
2011         (if (wl-string-match-assoc "body" wl-user-agent-headers-and-body-alist
2012                                    'ignore-case)
2013             (wl-user-agent-insert-body
2014              (cdr (wl-string-match-assoc
2015                    "body"
2016                    wl-user-agent-headers-and-body-alist 'ignore-case)))))
2017     t))
2018
2019 (require 'product)
2020 (product-provide (provide 'wl-draft) (require 'wl-version))
2021
2022 ;;; wl-draft.el ends here