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