da07072d354da4fe650fd159674dc4e320c3702f
[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 (with-arg)
260   "Return symbol `wl-draft-reply-*-argument-list' match condition.
261 Check WITH-ARG and From: field."
262   (if (wl-address-user-mail-address-p (or (elmo-field-body "From") ""))
263       (if with-arg
264           'wl-draft-reply-myself-with-argument-list
265         'wl-draft-reply-myself-without-argument-list)
266     (if with-arg
267         'wl-draft-reply-with-argument-list
268       'wl-draft-reply-without-argument-list)))
269
270 (defun wl-draft-reply (buf with-arg summary-buf)
271   "Reply to BUF buffer message.
272 Reply to author if WITH-ARG is non-nil."
273 ;;;(save-excursion
274   (let (r-list
275         to mail-followup-to cc subject in-reply-to references newsgroups
276         from to-alist cc-alist decoder)
277     (set-buffer buf)
278     (setq r-list (symbol-value (wl-draft-reply-list-symbol with-arg)))
279     (catch 'done
280       (while r-list
281         (when (let ((condition (car (car r-list))))
282                 (cond ((stringp condition)
283                        (std11-field-body condition))
284                       ((listp condition)
285                        (catch 'done
286                          (while condition
287                            (if (not (std11-field-body (car condition)))
288                                (throw 'done nil))
289                            (setq condition (cdr condition)))
290                          t))
291                       ((symbolp condition)
292                        (funcall condition))))
293           (let ((r-to-list (nth 0 (cdr (car r-list))))
294                 (r-cc-list (nth 1 (cdr (car r-list))))
295                 (r-ng-list (nth 2 (cdr (car r-list)))))
296             (when (and (member "Followup-To" r-ng-list)
297                        (string= (std11-field-body "Followup-To") "poster"))
298               (setq r-to-list (cons "From" r-to-list))
299               (setq r-ng-list (delete "Followup-To" (copy-sequence r-ng-list))))
300             (setq to (wl-concat-list (cons to
301                                            (elmo-multiple-fields-body-list
302                                             r-to-list))
303                                      ","))
304             (setq cc (wl-concat-list (cons cc
305                                            (elmo-multiple-fields-body-list
306                                             r-cc-list))
307                                      ","))
308             (setq newsgroups (wl-concat-list (cons newsgroups
309                                                    (std11-field-bodies
310                                                     r-ng-list))
311                                              ",")))
312           (throw 'done nil))
313         (setq r-list (cdr r-list)))
314       (error "No match field: check your `%s'"
315              (symbol-name (wl-draft-reply-list-symbol with-arg))))
316     (setq subject (std11-field-body "Subject"))
317     (setq to (wl-parse-addresses to)
318           cc (wl-parse-addresses cc))
319     (with-temp-buffer                   ; to keep raw buffer unibyte.
320       (elmo-set-buffer-multibyte default-enable-multibyte-characters)
321       (setq decoder (mime-find-field-decoder 'Subject 'plain))
322       (setq subject (if (and subject decoder)
323                         (funcall decoder subject) subject))
324       (setq to-alist 
325             (mapcar
326              (lambda (addr)
327                (setq decoder (mime-find-field-decoder 'To 'plain))
328                (cons (nth 1 (std11-extract-address-components addr))
329                      (if decoder (funcall decoder addr) addr)))
330              to))
331       (setq cc-alist 
332             (mapcar
333              (lambda (addr)
334                (setq decoder (mime-find-field-decoder 'Cc 'plain))
335                (cons (nth 1 (std11-extract-address-components addr))
336                      (if decoder (funcall decoder addr) addr)))
337              cc)))
338     (and wl-reply-subject-prefix
339          (setq subject (concat wl-reply-subject-prefix
340                                (wl-draft-strip-subject-re
341                                 (or subject "")))))
342     (setq in-reply-to (std11-field-body "Message-Id"))
343     (setq references (nconc
344                       (std11-field-bodies '("References" "In-Reply-To"))
345                       (list in-reply-to)))
346     (setq to (delq nil (mapcar 'car to-alist)))
347     (setq cc (delq nil (mapcar 'car cc-alist)))
348     ;; if subscribed mailing list is contained in cc or to
349     ;; and myself is contained in cc,
350     ;; delete myself from cc.
351     (setq cc (wl-draft-delete-myself-from-cc to cc))
352     (when wl-insert-mail-followup-to
353       (setq mail-followup-to
354             (wl-draft-make-mail-followup-to (append to cc)))
355       (setq mail-followup-to (wl-delete-duplicates mail-followup-to nil t)))
356     (setq newsgroups (wl-parse newsgroups
357                                "[ \t\f\r\n,]*\\([^ \t\f\r\n,]+\\)")
358           newsgroups (wl-delete-duplicates newsgroups)
359           newsgroups (if newsgroups (mapconcat 'identity newsgroups ",")))
360     (setq to (wl-delete-duplicates to nil t))
361     (setq cc (wl-delete-duplicates
362               (append (wl-delete-duplicates cc nil t)
363                       to (copy-sequence to))
364               t t))
365     (and to (setq to (mapconcat
366                       '(lambda (addr)
367                          (if wl-draft-reply-use-address-with-full-name
368                              (or (cdr (assoc addr to-alist)) addr)
369                            addr))
370                       to ",\n\t")))
371     (and cc (setq cc (mapconcat
372                       '(lambda (addr)
373                          (if wl-draft-reply-use-address-with-full-name
374                              (or (cdr (assoc addr cc-alist)) addr)
375                            addr))
376                       cc ",\n\t")))
377     (and mail-followup-to
378          (setq mail-followup-to
379                (mapconcat
380                 '(lambda (addr)
381                    (if wl-draft-reply-use-address-with-full-name
382                        (or (cdr (assoc addr (append to-alist cc-alist))) addr)
383                      addr))
384                 mail-followup-to ",\n\t")))
385     (and (null to) (setq to cc cc nil))
386     (setq references (delq nil references)
387           references (mapconcat 'identity references " ")
388           references (wl-draft-parse-msg-id-list-string references)
389           references (wl-delete-duplicates references)
390           references (if references
391                          (mapconcat 'identity references "\n\t")))
392     (wl-draft
393      to subject in-reply-to cc references newsgroups mail-followup-to
394      nil nil nil nil summary-buf)
395     (setq wl-draft-reply-buffer buf))
396   (run-hooks 'wl-reply-hook))
397
398 (defun wl-draft-add-references ()
399   (let* ((mes-id (save-excursion
400                    (set-buffer mail-reply-buffer)
401                    (std11-field-body "message-id")))
402          (ref (std11-field-body "References"))
403          (ref-list nil) (st nil))
404     (when (and mes-id ref)
405       (while (string-match "<[^>]+>" ref st)
406         (setq ref-list
407               (cons (substring ref (match-beginning 0) (setq st (match-end 0)))
408                     ref-list)))
409       (when (and ref-list
410                  (member mes-id ref-list))
411         (setq mes-id nil)))
412     (when mes-id
413       (save-excursion
414         (when (mail-position-on-field "References")
415           (forward-line)
416           (while (looking-at "^[ \t]")
417             (forward-line))
418           (setq mes-id (concat "\t" mes-id "\n")))
419         (insert mes-id))
420       t)))
421
422 (defun wl-draft-yank-from-mail-reply-buffer (decode-it
423                                              &optional ignored-fields)
424   (interactive)
425   (save-restriction
426     (narrow-to-region (point)(point))
427     (insert
428      (save-excursion
429        (set-buffer mail-reply-buffer)
430        (when decode-it
431          (decode-mime-charset-region (point-min) (point-max)
432                                      wl-mime-charset))
433        (buffer-substring-no-properties
434         (point-min) (point-max))))
435     (when ignored-fields
436       (goto-char (point-min))
437       (wl-draft-delete-fields ignored-fields))
438     (goto-char (point-max))
439     (push-mark)
440     (goto-char (point-min)))
441   (let ((beg (point)))
442     (cond (mail-citation-hook (run-hooks 'mail-citation-hook))
443           (mail-yank-hooks (run-hooks 'mail-yank-hooks))
444           (t (and wl-draft-cite-func
445                   (funcall wl-draft-cite-func)))) ; default cite
446     (run-hooks 'wl-draft-cited-hook)
447     (when (and wl-draft-add-references
448                (wl-draft-add-references))
449       (wl-highlight-headers 'for-draft)) ; highlight when added References:
450     (when wl-highlight-body-too
451       (wl-highlight-body-region beg (point-max)))))
452
453 (defun wl-draft-confirm ()
454   "Confirm send message."
455   (interactive)
456   (y-or-n-p (format "Send current draft as %s? "
457                     (cond ((and (wl-message-mail-p) (wl-message-news-p))
458                            "Mail and News")
459                           ((wl-message-mail-p) "Mail")
460                           ((wl-message-news-p) "News")))))
461
462 (defun wl-message-news-p ()
463   "If exist valid Newsgroups field, return non-nil."
464   (std11-field-body "Newsgroups"))
465
466 (defun wl-message-field-exists-p (field)
467   "If FIELD exist and FIELD value is not empty, return non-nil."
468   (let ((value (std11-field-body field)))
469     (and value
470          (not (string= value "")))))
471
472 (defun wl-message-mail-p ()
473   "If exist To, Cc or Bcc field, return non-nil."
474   (or (wl-message-field-exists-p "To")
475       (wl-message-field-exists-p "Cc")
476       (wl-message-field-exists-p "Bcc")
477 ;;; This may be needed..
478 ;;;   (wl-message-field-exists-p "Fcc")
479       ))
480
481 (defun wl-draft-open-file (&optional file)
482   "Open FILE for edit."
483   (interactive)
484 ;;;(interactive "*fFile to edit: ")
485   (wl-draft-edit-string (elmo-get-file-string
486                          (or file
487                              (read-file-name "File to edit: "
488                                              (or wl-tmp-dir "~/"))))))
489
490 (defun wl-draft-edit-string (string)
491   (let ((cur-buf (current-buffer))
492         (tmp-buf (get-buffer-create " *wl-draft-edit-string*"))
493         to subject in-reply-to cc references newsgroups mail-followup-to
494         content-type content-transfer-encoding
495         body-beg buffer-read-only
496         )
497     (set-buffer tmp-buf)
498     (erase-buffer)
499     (insert string)
500     (setq to (std11-field-body "To"))
501     (setq to (and to
502                   (eword-decode-string
503                    (decode-mime-charset-string
504                     to
505                     wl-mime-charset))))
506     (setq subject (std11-field-body "Subject"))
507     (setq subject (and subject
508                        (eword-decode-string
509                         (decode-mime-charset-string
510                          subject
511                          wl-mime-charset))))
512     (setq in-reply-to (std11-field-body "In-Reply-To"))
513     (setq cc (std11-field-body "Cc"))
514     (setq cc (and cc
515                   (eword-decode-string
516                    (decode-mime-charset-string
517                     cc
518                     wl-mime-charset))))
519     (setq references (std11-field-body "References"))
520     (setq newsgroups (std11-field-body "Newsgroups"))
521     (setq mail-followup-to (std11-field-body "Mail-Followup-To"))
522     (setq content-type (std11-field-body "Content-Type"))
523     (setq content-transfer-encoding (std11-field-body "Content-Transfer-Encoding"))
524     (goto-char (point-min))
525     (or (re-search-forward "\n\n" nil t)
526         (search-forward (concat mail-header-separator "\n") nil t))
527     (unwind-protect
528         (set-buffer
529          (wl-draft to subject in-reply-to cc references newsgroups
530                    mail-followup-to
531                    content-type content-transfer-encoding
532                    (buffer-substring (point) (point-max))
533                    'edit-again
534                    ))
535       (and to (mail-position-on-field "To"))
536       (delete-other-windows)
537       (kill-buffer tmp-buf)))
538   (setq buffer-read-only nil) ;;??
539   (run-hooks 'wl-draft-reedit-hook))
540
541 (defun wl-draft-insert-current-message (dummy)
542   (interactive)
543   (let ((mail-reply-buffer (wl-message-get-original-buffer))
544         mail-citation-hook mail-yank-hooks
545         wl-draft-add-references wl-draft-cite-func)
546     (if (eq 0
547             (save-excursion
548               (set-buffer mail-reply-buffer)
549               (buffer-size)))
550         (error "No current message")
551       (wl-draft-yank-from-mail-reply-buffer nil
552                                             wl-ignored-forwarded-headers))))
553
554 (defun wl-draft-insert-get-message (dummy)
555   (let ((fld (completing-read
556               "Folder name: "
557               (if (memq 'read-folder wl-use-folder-petname)
558                   (wl-folder-get-entity-with-petname)
559                 wl-folder-entity-hashtb)
560               nil nil wl-default-spec
561               'wl-read-folder-hist))
562         (number (call-interactively
563                  (function (lambda (num)
564                              (interactive "nNumber: ")
565                              num))))
566         (mail-reply-buffer (get-buffer-create "*wl-draft-insert-get-message*"))
567         mail-citation-hook mail-yank-hooks
568         wl-draft-cite-func)
569     (unwind-protect
570         (progn
571           (save-excursion
572             (elmo-read-msg-with-cache fld number mail-reply-buffer nil))
573           (wl-draft-yank-from-mail-reply-buffer nil))
574       (kill-buffer mail-reply-buffer))))
575
576 ;;
577 ;; default body citation func
578 ;;
579 (defun wl-default-draft-cite ()
580   (let ((mail-yank-ignored-headers "[^:]+:")
581         (mail-yank-prefix "> ")
582         (summary-buf wl-current-summary-buffer)
583         (message-buf (get-buffer (wl-current-message-buffer)))
584         from date cite-title num entity)
585     (if (and summary-buf
586              (buffer-live-p summary-buf)
587              message-buf
588              (buffer-live-p message-buf))
589         (progn
590           (save-excursion
591             (set-buffer summary-buf)
592             (setq num
593                   (save-excursion
594                     (set-buffer message-buf)
595                     wl-message-buffer-cur-number))
596             (setq entity (assoc (cdr (assq num
597                                            (elmo-msgdb-get-number-alist
598                                             wl-summary-buffer-msgdb)))
599                                 (elmo-msgdb-get-overview
600                                  wl-summary-buffer-msgdb)))
601             (setq from (elmo-msgdb-overview-entity-get-from entity))
602             (setq date (elmo-msgdb-overview-entity-get-date entity)))
603           (setq cite-title (format "At %s,\n%s wrote:"
604                                    (or date "some time ago")
605                                    (wl-summary-from-func-internal
606                                     (or from "you"))))))
607     (and cite-title
608          (insert cite-title "\n"))
609     (mail-indent-citation)))
610
611 (defvar wl-draft-buffer nil "Draft buffer to yank content")
612 (defun wl-draft-yank-to-draft-buffer (buffer)
613   "Yank BUFFER content to `wl-draft-buffer'."
614   (set-buffer wl-draft-buffer)
615   (let ((mail-reply-buffer buffer))
616     (wl-draft-yank-from-mail-reply-buffer nil)
617     (kill-buffer buffer)))
618
619 (defun wl-draft-yank-original (&optional arg)
620   "Yank original message."
621   (interactive "P")
622   (if arg
623       (let (buf mail-reply-buffer)
624         (elmo-set-work-buf
625          (yank)
626          (setq buf (current-buffer)))
627         (setq mail-reply-buffer buf)
628         (wl-draft-yank-from-mail-reply-buffer nil))
629     (wl-draft-yank-current-message-entity)))
630
631 (defun wl-draft-hide (editing-buffer)
632   "Hide the editing draft buffer if possible."
633   (interactive)
634   (when (and editing-buffer
635              (buffer-live-p editing-buffer))
636     (set-buffer editing-buffer)
637     (let ((sum-buf wl-draft-buffer-cur-summary-buffer)
638           fld-buf sum-win fld-win)
639       (if (and wl-draft-use-frame
640                (> (length (visible-frame-list)) 1))
641           ;; hide draft frame
642           (delete-frame)
643         ;; hide draft window
644         (or (one-window-p)
645             (delete-window)))
646       ;; stay folder window if required
647       (when wl-stay-folder-window
648         (if (setq fld-buf (get-buffer wl-folder-buffer-name))
649             (if (setq fld-win (get-buffer-window fld-buf))
650                 (select-window fld-win)
651               (if wl-draft-resume-folder-window ;; resume folder window
652                   (switch-to-buffer fld-buf)))))
653       (if (buffer-live-p sum-buf)
654           (if (setq sum-win (get-buffer-window sum-buf t))
655               ;; if Summary is on the frame, select it.
656               (select-window sum-win)
657             ;; if summary is not on the frame, switch to it.
658             (if (and wl-stay-folder-window
659                      (or wl-draft-resume-folder-window fld-win))
660                 (wl-folder-select-buffer sum-buf)
661               (switch-to-buffer sum-buf)))))))
662
663 (defun wl-draft-delete (editing-buffer)
664   "kill the editing draft buffer and delete the file corresponds to it."
665   (save-excursion
666     (when editing-buffer
667       (set-buffer editing-buffer)
668       (if wl-draft-buffer-file-name
669           (progn
670             (if (file-exists-p wl-draft-buffer-file-name)
671                 (delete-file wl-draft-buffer-file-name))
672             (let ((msg (and wl-draft-buffer-file-name
673                             (string-match "[0-9]+$" wl-draft-buffer-file-name)
674                             (string-to-int
675                              (elmo-match-string 0 wl-draft-buffer-file-name)))))
676               (wl-draft-config-info-operation msg 'delete))))
677       (set-buffer-modified-p nil)               ; force kill
678       (kill-buffer editing-buffer))))
679
680 (defun wl-draft-kill (&optional force-kill)
681   "Kill current draft buffer and quit editing."
682   (interactive "P")
683   (save-excursion
684     (when (and (or (eq major-mode 'wl-draft-mode)
685                    (eq major-mode 'mail-mode))
686                (or force-kill
687                    (y-or-n-p "Kill Current Draft?")))
688       (let ((cur-buf (current-buffer)))
689         (wl-draft-hide cur-buf)
690         (wl-draft-delete cur-buf)))
691     (message "")))
692
693 (defun wl-draft-fcc ()
694   "Add a new FCC field, with file name completion."
695   (interactive)
696   (or (mail-position-on-field "fcc" t)  ;Put new field after exiting FCC.
697       (mail-position-on-field "to"))
698   (insert "\nFCC: "))
699
700 ;; function for wl-sent-message-via
701
702 (defmacro wl-draft-sent-message-p (type)
703   (` (eq (nth 1 (assq (, type) wl-sent-message-via)) 'sent)))
704
705 (defmacro wl-draft-set-sent-message (type result &optional server-port)
706   (` (let ((element (assq (, type) wl-sent-message-via)))
707        (if element
708            (unless (eq (nth 1 element) (, result))
709              (setcdr element (list (, result) (, server-port)))
710              (setq wl-sent-message-modified t))
711          (push (list (, type) (, result) (, server-port)) wl-sent-message-via)
712          (setq wl-sent-message-modified t)))))
713
714 (defun wl-draft-sent-message-results ()
715   (let ((results wl-sent-message-via)
716         unplugged-via sent-via)
717     (while results
718       (cond ((eq (nth 1 (car results)) 'unplugged)
719              (push (caar results) unplugged-via))
720             ((eq (nth 1 (car results)) 'sent)
721              (push (caar results) sent-via)))
722       (setq results (cdr results)))
723     (list unplugged-via sent-via)))
724
725 (defun wl-draft-write-sendlog (status proto server to id)
726   "Write send log file, if `wl-draft-sendlog' is non-nil."
727   (when wl-draft-sendlog
728     (save-excursion
729       (let* ((tmp-buf (get-buffer-create " *wl-draft-sendlog*"))
730              (filename (expand-file-name wl-draft-sendlog-filename
731                                          elmo-msgdb-dir))
732              (filesize (nth 7 (file-attributes filename)))
733              (server (if server (concat " server=" server) ""))
734              (to (if to (cond
735                          ((memq proto '(fcc queue))
736                           (format " folder=\"%s\"" to))
737                          ((eq proto 'nntp)
738                           (format " ng=<%s>" to))
739                          (t
740                           (concat " to="
741                                   (mapconcat
742                                    'identity
743                                    (mapcar '(lambda(x) (format "<%s>" x)) to)
744                                    ","))))
745                    ""))
746              (id (if id (concat " id=" id) ""))
747              (time (wl-sendlog-time)))
748         (set-buffer tmp-buf)
749         (erase-buffer)
750         (insert (format "%s proto=%s stat=%s%s%s%s\n"
751                         time proto status server to id))
752         (if (and wl-draft-sendlog-max-size filesize
753                  (> filesize wl-draft-sendlog-max-size))
754             (rename-file filename (concat filename ".old") t))
755         (if (file-writable-p filename)
756             (write-region (point-min) (point-max)
757                           filename t 'no-msg)
758           (message (format "%s is not writable." filename)))
759         (kill-buffer tmp-buf)))))
760
761 (defun wl-draft-get-header-delimiter (&optional delete)
762   ;; If DELETE is non-nil, replace the header delimiter with a blank line
763   (let (delimline)
764     (goto-char (point-min))
765     (when (re-search-forward
766            (concat "^" (regexp-quote mail-header-separator) "$\\|^$") nil t)
767       (replace-match "")
768       (if delete
769           (forward-char -1))
770       (setq delimline (point-marker)))
771     delimline))
772
773 (defun wl-draft-send-mail-with-qmail ()
774   "Pass the prepared message buffer to qmail-inject.
775 Refer to the documentation for the variable `send-mail-function'
776 to find out how to use this."
777   (if (and wl-draft-qmail-send-plugged
778            (not (elmo-plugged-p)))
779       (wl-draft-set-sent-message 'mail 'unplugged)
780     ;; send the message
781     (let ((id (std11-field-body "Message-ID"))
782           (to (std11-field-body "To")))
783       (case
784           (as-binary-process
785            (apply
786             'call-process-region 1 (point-max) wl-qmail-inject-program
787             nil nil nil
788             wl-qmail-inject-args))
789         ;; qmail-inject doesn't say anything on it's stdout/stderr,
790         ;; we have to look at the retval instead
791         (0   (progn
792                (wl-draft-set-sent-message 'mail 'sent)
793                (wl-draft-write-sendlog 'ok 'qmail nil (list to) id)))
794         (1   (error "qmail-inject reported permanent failure"))
795         (111 (error "qmail-inject reported transient failure"))
796         ;; should never happen
797         (t   (error "qmail-inject reported unknown failure"))))))
798
799 (defun wl-draft-parse-msg-id-list-string (string)
800   "Get msg-id list from STRING."
801   (let ((parsed (std11-parse-msg-ids-string string))
802         tokens msg-id msg-id-list)
803     (while parsed
804       (setq msg-id nil)
805       (when (eq (car (car parsed)) 'msg-id)
806         (setq tokens (cdr (car parsed)))
807         (while tokens
808           (if (or (eq (car (car tokens)) 'atom)
809                   (eq (car (car tokens)) 'specials))
810               (setq msg-id (concat msg-id (cdr (car tokens)))))
811           (setq tokens (cdr tokens))))
812       (if msg-id (setq msg-id-list (cons (concat "<" msg-id ">")
813                                          msg-id-list)))
814       (setq parsed (cdr parsed)))
815     (nreverse msg-id-list)))
816
817 (defun wl-draft-parse-mailbox-list (field &optional remove-group-list)
818   "Get mailbox list of FIELD from current buffer.
819 The buffer is expected to be narrowed to just the headers of the message.
820 If optional argument REMOVE-GROUP-LIST is non-nil, remove group list content
821 from current buffer."
822   (save-excursion
823     (let ((case-fold-search t)
824           (inhibit-read-only t)
825           addresses address
826           mailbox-list beg seq has-group-list)
827       (goto-char (point-min))
828       (while (re-search-forward (concat "^" (regexp-quote field) "[\t ]*:")
829                                 nil t)
830         (setq beg (point))
831         (re-search-forward "^[^ \t]" nil 'move)
832         (beginning-of-line)
833         (skip-chars-backward "\n")
834         (setq seq (std11-lexical-analyze
835                    (buffer-substring-no-properties beg (point))))
836         (setq addresses (std11-parse-addresses seq))
837         (while addresses
838           (cond ((eq (car (car addresses)) 'group)
839                  (setq has-group-list t)
840                  (setq mailbox-list
841                        (nconc mailbox-list
842                               (mapcar
843                                'std11-address-string
844                                (nth 2 (car addresses))))))
845                 ((eq (car (car addresses)) 'mailbox)
846                  (setq address (nth 1 (car addresses)))
847                  (setq mailbox-list
848                        (nconc mailbox-list
849                               (list
850                                (std11-addr-to-string
851                                 (if (eq (car address) 'phrase-route-addr)
852                                     (nth 2 address)
853                                   (cdr address))))))))
854           (setq addresses (cdr addresses)))
855         (when (and remove-group-list has-group-list)
856           (delete-region beg (point))
857           (insert (wl-address-string-without-group-list-contents seq))))
858       mailbox-list)))
859
860 (defun wl-draft-deduce-address-list (buffer header-start header-end)
861   "Get address list suitable for smtp RCPT TO:<address>.
862 Group list content is removed if `wl-draft-remove-group-list-contents' is
863 non-nil."
864   (let ((fields        '("to" "cc" "bcc"))
865         (resent-fields '("resent-to" "resent-cc" "resent-bcc"))
866         (case-fold-search t)
867         addrs recipients)
868     (save-excursion
869       (save-restriction
870         (narrow-to-region header-start header-end)
871         (goto-char (point-min))
872         (save-excursion
873           (if (re-search-forward "^resent-to[\t ]*:" nil t)
874               (setq fields resent-fields)))
875         (while fields
876           (setq recipients
877                 (nconc recipients
878                        (wl-draft-parse-mailbox-list
879                         (car fields)
880                         wl-draft-remove-group-list-contents)))
881           (setq fields (cdr fields)))
882         recipients))))
883
884 (static-if (fboundp 'smtp-send-buffer)
885 (defun wl-draft-smtp-send-buffer (sender recipients buffer id)
886   (wl-smtp-extension-bind
887    (condition-case err
888        (smtp-send-buffer sender recipients (current-buffer))
889      (error
890       (wl-draft-write-sendlog 'failed 'smtp smtp-server
891                               recipients id)
892       (signal (car err) (cdr err))))))
893 (defun wl-draft-smtp-send-buffer (sender recipients buffer id)
894   (as-binary-process
895    (wl-smtp-extension-bind
896     (let ((err (smtp-via-smtp sender recipients
897                               (current-buffer))))
898       (when (not (eq err t))
899         (wl-draft-write-sendlog 'failed 'smtp smtp-server
900                                 recipients id)
901         (error "Sending failed; SMTP protocol error:%s" err))))))
902 ;; end of static-if
903 )
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               (when recipients
964                 (wl-draft-smtp-send-buffer sender recipients (current-buffer)
965                                            id)
966                 (wl-draft-set-sent-message 'mail 'sent)
967                 (wl-draft-write-sendlog
968                  'ok 'smtp smtp-server recipients id))))
969         (if (bufferp errbuf)
970             (kill-buffer errbuf))))))
971
972 (defun wl-draft-send-mail-with-pop-before-smtp ()
973   "Send the prepared message buffer with POP-before-SMTP."
974   (require 'elmo-pop3)
975   (condition-case ()
976       (let ((session (elmo-pop3-get-session
977                       (list 'pop3
978                             (or wl-pop-before-smtp-user
979                                 elmo-default-pop3-user)
980                             (or wl-pop-before-smtp-authenticate-type
981                                 elmo-default-pop3-authenticate-type)
982                             (or wl-pop-before-smtp-server
983                                 elmo-default-pop3-server)
984                             (or wl-pop-before-smtp-port
985                                 elmo-default-pop3-port)
986                             (or wl-pop-before-smtp-stream-type
987                                 elmo-default-pop3-stream-type)))))
988         (when session (elmo-network-close-session session)))
989     (error))
990   (wl-draft-send-mail-with-smtp))
991
992 (defun wl-draft-insert-required-fields (&optional force-msgid)
993   "Insert Message-ID, Date, and From field.
994 If FORCE-MSGID, ignore 'wl-insert-message-id'."
995   ;; Insert Message-Id field...
996   (goto-char (point-min))
997   (when (and (or force-msgid
998                  wl-insert-message-id)
999              (not (re-search-forward "^Message-ID[ \t]*:" nil t)))
1000     (insert (concat "Message-ID: "
1001                     (wl-draft-make-message-id-string)
1002                     "\n")))
1003   ;; Insert date field.
1004   (goto-char (point-min))
1005   (or (re-search-forward "^Date[ \t]*:" nil t)
1006       (wl-draft-insert-date-field))
1007   ;; Insert from field.
1008   (goto-char (point-min))
1009   (or (re-search-forward "^From[ \t]*:" nil t)
1010       (wl-draft-insert-from-field)))
1011
1012 (defun wl-draft-normal-send-func (editing-buffer kill-when-done)
1013   "Send the message in the current buffer."
1014   (save-restriction
1015     (std11-narrow-to-header mail-header-separator)
1016     (wl-draft-insert-required-fields)
1017     ;; Delete null fields.
1018     (goto-char (point-min))
1019     (while (re-search-forward "^[^ \t\n:]+:[ \t]*\n" nil t)
1020       (replace-match ""))
1021     ;; ignore any blank lines in the header
1022     (while (re-search-forward "\n\n\n*" nil t)
1023       (replace-match "\n")))
1024   (run-hooks 'wl-mail-send-pre-hook) ;; X-PGP-Sig, Cancel-Lock
1025   (wl-draft-dispatch-message)
1026   (when kill-when-done
1027     ;; hide editing-buffer.
1028     (wl-draft-hide editing-buffer)
1029     ;; delete editing-buffer and its file.
1030     (wl-draft-delete editing-buffer)))
1031
1032 (defun wl-draft-dispatch-message (&optional mes-string)
1033   "Send the message in the current buffer.  Not modified the header fields."
1034   (let (delimline)
1035     (if (and wl-draft-verbose-send mes-string)
1036         (message mes-string))
1037     ;; get fcc folders.
1038     (setq delimline (wl-draft-get-header-delimiter t))
1039     (unless wl-draft-fcc-list
1040       (setq wl-draft-fcc-list (wl-draft-get-fcc-list delimline)))
1041     ;;
1042     (setq wl-sent-message-modified nil)
1043     (unwind-protect
1044         (progn
1045           (if (and (wl-message-mail-p)
1046                    (not (wl-draft-sent-message-p 'mail)))
1047               (funcall wl-draft-send-mail-func))
1048           (if (and (wl-message-news-p)
1049                    (not (wl-draft-sent-message-p 'news))
1050                    (not (wl-message-field-exists-p "Resent-to")))
1051               (funcall wl-draft-send-news-func)))
1052       ;;
1053       (let* ((status (wl-draft-sent-message-results))
1054              (unplugged-via (car status))
1055              (sent-via (nth 1 status)))
1056         ;; If one sent, process fcc folder.
1057         (if (and sent-via wl-draft-fcc-list)
1058             (progn
1059               (wl-draft-do-fcc (wl-draft-get-header-delimiter) wl-draft-fcc-list)
1060               (setq wl-draft-fcc-list nil))
1061           (if wl-draft-use-cache
1062               (let ((id (std11-field-body "Message-ID"))
1063                     (elmo-enable-disconnected-operation t))
1064                 (elmo-cache-save id nil nil nil))))
1065         ;; If one unplugged, append queue.
1066         (when (and unplugged-via
1067                    wl-sent-message-modified)
1068           (if wl-draft-enable-queuing
1069               (wl-draft-queue-append wl-sent-message-via)
1070             (error "Unplugged")))
1071         (when wl-draft-verbose-send
1072           (if (and unplugged-via sent-via);; combined message
1073               (progn
1074                 (setq wl-draft-verbose-msg
1075                       (format "Sending%s and Queuing%s..."
1076                               sent-via unplugged-via))
1077                 (message (concat wl-draft-verbose-msg "done")))
1078             (if mes-string
1079                 (message (concat mes-string
1080                                  (if sent-via "done" "failed")))))))))
1081   (not wl-sent-message-modified)) ;; return value
1082
1083 (defun wl-draft-raw-send (&optional kill-when-done force-pre-hook mes-string)
1084   "Force send current buffer as raw message."
1085   (interactive)
1086   (save-excursion
1087     (let (wl-interactive-send
1088 ;;;       wl-draft-verbose-send
1089           (wl-mail-send-pre-hook (and force-pre-hook wl-mail-send-pre-hook))
1090 ;;;       wl-news-send-pre-hook
1091           mail-send-hook
1092           mail-send-actions)
1093       (wl-draft-send kill-when-done mes-string))))
1094
1095 (defun wl-draft-clone-local-variables ()
1096   (let ((locals (buffer-local-variables))
1097         result)
1098     (while locals
1099       (when (and (consp (car locals))
1100                  (car (car locals))
1101                  (string-match wl-draft-clone-local-variable-regexp
1102                                (symbol-name (car (car locals)))))
1103         (wl-append result (list (car (car locals)))))
1104       (setq locals (cdr locals)))
1105     result))
1106
1107 (defun wl-draft-send (&optional kill-when-done mes-string)
1108   "Send current draft message.
1109 If optional argument is non-nil, current draft buffer is killed"
1110   (interactive)
1111   ;; Don't call this explicitly.
1112   ;; Added to 'wl-draft-send-hook (by teranisi)
1113   ;; (wl-draft-config-exec)
1114   (run-hooks 'wl-draft-send-hook)
1115   (when (or (not wl-interactive-send)
1116             (y-or-n-p "Send current draft. OK?"))
1117     (let ((send-mail-function 'wl-draft-raw-send)
1118           (editing-buffer (current-buffer))
1119           (sending-buffer (wl-draft-generate-clone-buffer
1120                            " *wl-draft-sending-buffer*"
1121                            (append wl-draft-config-variables
1122                                    (wl-draft-clone-local-variables))))
1123           (wl-draft-verbose-msg nil)
1124           err)
1125       (unwind-protect
1126           (save-excursion (set-buffer sending-buffer)
1127             (if (and (not (wl-message-mail-p))
1128                      (not (wl-message-news-p)))
1129                 (error "No recipient is specified"))
1130             (expand-abbrev) ; for mail-abbrevs
1131             (run-hooks 'mail-send-hook) ; translate buffer
1132             (if wl-draft-verbose-send
1133                 (message (or mes-string "Sending...")))
1134             (funcall wl-draft-send-func editing-buffer kill-when-done)
1135             ;; Now perform actions on successful sending.
1136             (while mail-send-actions
1137               (condition-case ()
1138                   (apply (car (car mail-send-actions))
1139                          (cdr (car mail-send-actions)))
1140                 (error))
1141               (setq mail-send-actions (cdr mail-send-actions)))
1142             (if (or (eq major-mode 'wl-draft-mode)
1143                     (eq major-mode 'mail-mode))
1144                 (local-set-key "\C-c\C-s" 'wl-draft-send)) ; override
1145             (if wl-draft-verbose-send
1146                 (message (concat (or wl-draft-verbose-msg
1147                                      mes-string "Sending...")
1148                                  "done"))))
1149         ;; kill sending buffer, anyway.
1150         (and (buffer-live-p sending-buffer)
1151              (kill-buffer sending-buffer))))))
1152
1153 (defun wl-draft-save ()
1154   "Save current draft."
1155   (interactive)
1156   (save-buffer)
1157   (wl-draft-config-info-operation
1158    (and (string-match "[0-9]+$" wl-draft-buffer-file-name)
1159         (string-to-int
1160          (elmo-match-string 0 wl-draft-buffer-file-name)))
1161    'save))
1162
1163 (defun wl-draft-mimic-kill-buffer ()
1164   "Kill the current (draft) buffer with query."
1165   (interactive)
1166   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
1167                                       (buffer-name))))
1168         wl-draft-use-frame)
1169     (if (or (not bufname)
1170             (string-equal bufname "")
1171             (string-equal bufname (buffer-name)))
1172         (wl-draft-save-and-exit)
1173       (kill-buffer bufname))))
1174
1175 (defun wl-draft-save-and-exit ()
1176   "Save current draft and exit current draft mode."
1177   (interactive)
1178   (wl-draft-save)
1179   (let ((editing-buffer (current-buffer)))
1180     (wl-draft-hide editing-buffer)
1181     (kill-buffer editing-buffer)))
1182   
1183 (defun wl-draft-send-and-exit ()
1184   "Send current draft message and kill it."
1185   (interactive)
1186   (wl-draft-send t))
1187
1188 (defun wl-draft-send-from-toolbar ()
1189   (interactive)
1190   (let ((wl-interactive-send t))
1191     (wl-draft-send-and-exit)))
1192
1193 (defun wl-draft-delete-field (field &optional delimline)
1194   (wl-draft-delete-fields (regexp-quote field) delimline))
1195
1196 (defun wl-draft-delete-fields (regexp &optional delimline)
1197   (save-restriction
1198     (unless delimline
1199       (if (search-forward "\n\n" nil t)
1200           (setq delimline (point))
1201         (setq delimline (point-max))))
1202     (narrow-to-region (point-min) delimline)
1203     (goto-char (point-min))
1204     (let ((regexp (concat "^" regexp ":"))
1205           (case-fold-search t)
1206           last)
1207       (while (not (eobp))
1208         (if (looking-at regexp)
1209             (progn
1210               (delete-region
1211                (point)
1212                (progn
1213                  (forward-line 1)
1214                  (if (re-search-forward "^[^ \t]" nil t)
1215                      (goto-char (match-beginning 0))
1216                    (point-max)))))
1217           (forward-line 1)
1218           (if (re-search-forward "^[^ \t]" nil t)
1219               (goto-char (match-beginning 0))
1220             (point-max)))))))
1221
1222 (defun wl-draft-get-fcc-list (header-end)
1223   (let (fcc-list
1224         (case-fold-search t))
1225     (or (markerp header-end) (error "header-end must be a marker"))
1226     (save-excursion
1227       (goto-char (point-min))
1228       (while (re-search-forward "^FCC:[ \t]*" header-end t)
1229         (setq fcc-list
1230               (cons (buffer-substring-no-properties
1231                      (point)
1232                      (progn
1233                        (end-of-line)
1234                        (skip-chars-backward " \t")
1235                        (point)))
1236                     fcc-list))
1237         (save-match-data
1238           (wl-folder-confirm-existence (eword-decode-string (car fcc-list))))
1239         (delete-region (match-beginning 0)
1240                        (progn (forward-line 1) (point)))))
1241     fcc-list))
1242
1243 (defun wl-draft-do-fcc (header-end &optional fcc-list)
1244   (let ((send-mail-buffer (current-buffer))
1245         (tembuf (generate-new-buffer " fcc output"))
1246         (case-fold-search t)
1247         beg end)
1248     (or (markerp header-end) (error "header-end must be a marker"))
1249     (save-excursion
1250       (unless fcc-list
1251         (setq fcc-list (wl-draft-get-fcc-list header-end)))
1252       (set-buffer tembuf)
1253       (erase-buffer)
1254       ;; insert just the headers to avoid moving the gap more than
1255       ;; necessary (the message body could be arbitrarily huge.)
1256       (insert-buffer-substring send-mail-buffer 1 header-end)
1257       (wl-draft-insert-required-fields t)
1258       (goto-char (point-max))
1259       (insert-buffer-substring send-mail-buffer header-end)
1260       (let ((id (std11-field-body "Message-ID"))
1261             (elmo-enable-disconnected-operation t)
1262             cache-saved)
1263         (while fcc-list
1264           (unless (or cache-saved
1265                       (elmo-folder-plugged-p (car fcc-list)))
1266             (elmo-cache-save id nil nil nil) ;; for disconnected operation
1267             (setq cache-saved t))
1268           (if (elmo-append-msg (eword-decode-string (car fcc-list))
1269                                (buffer-substring
1270                                 (point-min) (point-max))
1271                                id)
1272               (wl-draft-write-sendlog 'ok 'fcc nil (car fcc-list) id)
1273             (wl-draft-write-sendlog 'failed 'fcc nil (car fcc-list) id))
1274           (setq fcc-list (cdr fcc-list)))))
1275     (kill-buffer tembuf)))
1276
1277 (defun wl-draft-on-field-p ()
1278   (if (< (point)
1279          (save-excursion
1280            (goto-char (point-min))
1281            (search-forward (concat "\n" mail-header-separator "\n") nil 0)
1282            (point)))
1283       (if (bolp)
1284           (if (bobp)
1285               t
1286             (save-excursion
1287               (forward-line -1)
1288               (if (or (looking-at ".*,[ \t]?$")
1289                       (looking-at "^[^ \t]+:[ \t]+.*:$")); group list name
1290                   nil t)))
1291         (let ((pos (point)))
1292           (save-excursion
1293             (beginning-of-line)
1294             (if (looking-at "^[ \t]")
1295                 nil
1296               (if (re-search-forward ":" pos t) nil t)))))))
1297
1298 (defun wl-draft-random-alphabet ()
1299   (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)))
1300     (nth (abs (% (random) 26)) alphabet)))
1301
1302 ;;;###autoload
1303 (defun wl-draft (&optional to subject in-reply-to cc references newsgroups
1304                            mail-followup-to
1305                            content-type content-transfer-encoding
1306                            body edit-again summary-buf)
1307   "Write and send mail/news message with Wanderlust."
1308   (interactive)
1309   (unless (featurep 'wl)
1310     (require 'wl))
1311   (unless wl-init
1312     (wl-load-profile))
1313   (wl-init 'wl-draft) ;; returns immediately if already initialized.
1314   (if (interactive-p)
1315       (setq summary-buf (wl-summary-get-buffer wl-summary-buffer-folder-name)))
1316   (let ((draft-folder-spec (elmo-folder-get-spec wl-draft-folder))
1317         buf-name file-name num wl-demo change-major-mode-hook)
1318     (if (not (eq (car draft-folder-spec) 'localdir))
1319         (error "%s folder cannot be used for draft folder" wl-draft-folder))
1320     (setq num (elmo-max-of-list (or (elmo-list-folder wl-draft-folder) '(0))))
1321     (setq num (+ 1 num))
1322     ;; To get unused buffer name.
1323     (while (get-buffer (concat wl-draft-folder "/" (int-to-string num)))
1324       (setq num (+ 1 num)))
1325     (setq buf-name (find-file-noselect
1326                     (setq file-name
1327                           (elmo-get-msg-filename wl-draft-folder
1328                                                  num))))
1329     (if wl-draft-use-frame
1330         (switch-to-buffer-other-frame buf-name)
1331       (switch-to-buffer buf-name))
1332     (set-buffer buf-name)
1333     (if (not (string-match (regexp-quote wl-draft-folder)
1334                            (buffer-name)))
1335         (rename-buffer (concat wl-draft-folder "/" (int-to-string num))))
1336     (if (or (eq wl-draft-reply-buffer-style 'full)
1337             (eq this-command 'wl-draft)
1338             (eq this-command 'wl-summary-write)
1339             (eq this-command 'wl-summary-write-current-newsgroup))
1340         (delete-other-windows))
1341     (auto-save-mode -1)
1342     (wl-draft-mode)
1343     (setq wl-sent-message-via nil)
1344     (if (stringp wl-from)
1345         (insert "From: " wl-from "\n"))
1346     (and (or (interactive-p)
1347              (eq this-command 'wl-summary-write)
1348              to)
1349          (insert "To: " (or to "") "\n"))
1350     (and cc (insert "Cc: " (or cc "") "\n"))
1351     (insert "Subject: " (or subject "") "\n")
1352     (and newsgroups (insert "Newsgroups: " newsgroups "\n"))
1353     (and mail-followup-to (insert "Mail-Followup-To: " mail-followup-to "\n"))
1354     (and wl-insert-mail-reply-to
1355          (insert "Mail-Reply-To: "
1356                  (wl-address-header-extract-address
1357                   wl-from) "\n"))
1358     (and in-reply-to (insert "In-Reply-To: " in-reply-to "\n"))
1359     (and references (insert "References: " references "\n"))
1360     (insert (funcall wl-generate-mailer-string-func)
1361             "\n")
1362     (setq wl-draft-buffer-file-name file-name)
1363     (if mail-default-reply-to
1364         (insert "Reply-To: " mail-default-reply-to "\n"))
1365     (if (or wl-bcc mail-self-blind)
1366         (insert "Bcc: " (or wl-bcc (user-login-name)) "\n"))
1367     (if wl-fcc
1368         (insert "FCC: " (if (functionp wl-fcc) (funcall wl-fcc) wl-fcc) "\n"))
1369     (if wl-organization
1370         (insert "Organization: " wl-organization "\n"))
1371     (and wl-auto-insert-x-face
1372          (file-exists-p wl-x-face-file)
1373          (wl-draft-insert-x-face-field-here))
1374     (if mail-default-headers
1375         (insert mail-default-headers))
1376     (if (not (= (preceding-char) ?\n))
1377         (insert ?\n))
1378     (if edit-again
1379         (let (start)
1380           (setq start (point))
1381           (when content-type
1382             (insert "Content-type: " content-type "\n"))
1383           (when content-transfer-encoding
1384             (insert "Content-Transfer-encoding: " content-transfer-encoding "\n"))
1385           (if (or content-type content-transfer-encoding)
1386               (insert "\n"))
1387           (and body (insert body))
1388           (save-restriction
1389             (narrow-to-region start (point))
1390             (and edit-again
1391                  (wl-draft-decode-message-in-buffer))
1392             (widen)
1393             (goto-char start)
1394             (put-text-property (point)
1395                                (progn
1396                                  (insert mail-header-separator "\n")
1397                                  (1- (point)))
1398                                'category 'mail-header-separator)))
1399       (put-text-property (point)
1400                          (progn
1401                            (insert mail-header-separator "\n")
1402                            (1- (point)))
1403                          'category 'mail-header-separator)
1404       (and body (insert body)))
1405     (if wl-on-nemacs
1406         (push-mark (point) t)
1407       (push-mark (point) t t))
1408     (as-binary-output-file
1409      (write-region (point-min)(point-max) wl-draft-buffer-file-name
1410                    nil t))
1411     (wl-draft-editor-mode)
1412     (wl-draft-overload-functions)
1413     (wl-highlight-headers 'for-draft)
1414     (goto-char (point-min))
1415     (setq wl-draft-config-exec-flag t)
1416     (if (interactive-p)
1417         (run-hooks 'wl-mail-setup-hook))
1418     (wl-user-agent-compose-internal) ;; user-agent
1419     (cond ((eq this-command 'wl-summary-write-current-newsgroup)
1420            (mail-position-on-field "Subject"))
1421           ((and (interactive-p) (null to))
1422            (mail-position-on-field "To"))
1423           (t
1424            (goto-char (point-max))))
1425     (setq wl-draft-buffer-cur-summary-buffer (or summary-buf
1426                                                  (get-buffer
1427                                                   wl-summary-buffer-name)))
1428     buf-name))
1429
1430 (defun wl-draft-elmo-nntp-send ()
1431   (let ((elmo-nntp-post-pre-hook wl-news-send-pre-hook)
1432         (elmo-default-nntp-user
1433          (or wl-nntp-posting-user elmo-default-nntp-user))
1434         (elmo-default-nntp-server
1435          (or wl-nntp-posting-server elmo-default-nntp-server))
1436         (elmo-default-nntp-port
1437          (or wl-nntp-posting-port elmo-default-nntp-port))
1438         (elmo-default-nntp-stream-type
1439          (or wl-nntp-posting-stream-type elmo-default-nntp-stream-type)))
1440     (if (not (elmo-plugged-p elmo-default-nntp-server elmo-default-nntp-port))
1441         (wl-draft-set-sent-message 'news 'unplugged
1442                                    (cons elmo-default-nntp-server
1443                                          elmo-default-nntp-port))
1444       (elmo-nntp-post elmo-default-nntp-server (current-buffer))
1445       (wl-draft-set-sent-message 'news 'sent)
1446       (wl-draft-write-sendlog 'ok 'nntp elmo-default-nntp-server
1447                               (std11-field-body "Newsgroups")
1448                               (std11-field-body "Message-ID")))))
1449
1450 (defun wl-draft-generate-clone-buffer (name &optional local-variables)
1451   "generate clone of current buffer named NAME."
1452   (let ((editing-buffer (current-buffer)))
1453     (save-excursion
1454       (set-buffer (generate-new-buffer name))
1455       (erase-buffer)
1456       (wl-draft-mode)
1457       (wl-draft-editor-mode)
1458       (insert-buffer editing-buffer)
1459       (message "")
1460       (while local-variables
1461         (make-local-variable (car local-variables))
1462         (set (car local-variables)
1463              (save-excursion
1464                (set-buffer editing-buffer)
1465                (symbol-value (car local-variables))))
1466         (setq local-variables (cdr local-variables)))
1467       (current-buffer))))
1468
1469 (defun wl-draft-reedit (number)
1470   (let ((draft-folder-spec (elmo-folder-get-spec wl-draft-folder))
1471         (wl-draft-reedit t)
1472         buf-name file-name change-major-mode-hook)
1473     (setq file-name (expand-file-name
1474                      (int-to-string number)
1475                      (expand-file-name
1476                       (nth 1 draft-folder-spec)
1477                       elmo-localdir-folder-path)))
1478     (unless (file-exists-p file-name)
1479       (error "File %s does not exist" file-name))
1480     (setq buf-name (find-file-noselect file-name))
1481     (if wl-draft-use-frame
1482         (switch-to-buffer-other-frame buf-name)
1483       (switch-to-buffer buf-name))
1484     (set-buffer buf-name)
1485     (if (not (string-match (regexp-quote wl-draft-folder)
1486                            (buffer-name)))
1487         (rename-buffer (concat wl-draft-folder "/" (buffer-name))))
1488     (auto-save-mode -1)
1489     (wl-draft-mode)
1490     (setq wl-sent-message-via nil)
1491     (setq wl-draft-buffer-file-name file-name)
1492     (wl-draft-config-info-operation number 'load)
1493     (goto-char (point-min))
1494     (or (re-search-forward "\n\n" nil t)
1495         (search-forward (concat mail-header-separator "\n") nil t))
1496     (if wl-on-nemacs
1497         (push-mark (point) t)
1498       (push-mark (point) t t))
1499     (write-region (point-min)(point-max) wl-draft-buffer-file-name
1500                   nil t)
1501     (wl-draft-overload-functions)
1502     (wl-draft-editor-mode)
1503     (wl-highlight-headers 'for-draft)
1504     (run-hooks 'wl-draft-reedit-hook)
1505     (goto-char (point-max))
1506     buf-name
1507     ))
1508
1509 (defmacro wl-draft-body-goto-top ()
1510   (` (progn
1511        (goto-char (point-min))
1512        (if (re-search-forward mail-header-separator nil t)
1513            (forward-char 1)
1514          (goto-char (point-max))))))
1515
1516 (defmacro wl-draft-body-goto-bottom ()
1517   (` (goto-char (point-max))))
1518
1519 (defmacro wl-draft-config-body-goto-header ()
1520   (` (progn
1521        (goto-char (point-min))
1522        (if (re-search-forward mail-header-separator nil t)
1523            (beginning-of-line)
1524          (goto-char (point-max))))))
1525
1526 (defun wl-draft-config-sub-body (content)
1527   (wl-draft-body-goto-top)
1528   (delete-region (point) (point-max))
1529   (if content (insert (eval content))))
1530
1531 (defun wl-draft-config-sub-top (content)
1532   (wl-draft-body-goto-top)
1533   (if content (insert (eval content))))
1534
1535 (defun wl-draft-config-sub-bottom (content)
1536   (wl-draft-body-goto-bottom)
1537   (if content (insert (eval content))))
1538
1539 (defun wl-draft-config-sub-header (content)
1540   (wl-draft-config-body-goto-header)
1541   (if content (insert (concat (eval content) "\n"))))
1542
1543 (defsubst wl-draft-config-sub-file (content)
1544   (let ((coding-system-for-read wl-cs-autoconv)
1545         (file (expand-file-name (eval content))))
1546     (if (file-exists-p file)
1547         (insert-file-contents file)
1548       (error "%s: no exists file" file))))
1549
1550 (defun wl-draft-config-sub-body-file (content)
1551   (wl-draft-body-goto-top)
1552   (delete-region (point) (point-max))
1553   (wl-draft-config-sub-file content))
1554
1555 (defun wl-draft-config-sub-top-file (content)
1556   (wl-draft-body-goto-top)
1557   (wl-draft-config-sub-file content))
1558
1559 (defun wl-draft-config-sub-bottom-file (content)
1560   (wl-draft-body-goto-bottom)
1561   (wl-draft-config-sub-file content))
1562
1563 (defun wl-draft-config-sub-header-file (content)
1564   (wl-draft-config-body-goto-header)
1565   (wl-draft-config-sub-file content))
1566
1567 (defun wl-draft-config-sub-template (content)
1568   (setq wl-draft-config-variables
1569         (wl-template-insert (eval content))))
1570
1571 (defun wl-draft-config-sub-x-face (content)
1572   (if (and (string-match "\\.xbm\\(\\.gz\\)?$" content)
1573            (fboundp 'x-face-insert)) ; x-face.el is installed.
1574       (x-face-insert content)
1575     (wl-draft-replace-field "X-Face" (elmo-get-file-string content t) t)))
1576
1577 (defsubst wl-draft-config-sub-func (field content)
1578   (let (func)
1579     (if (setq func (assq field wl-draft-config-sub-func-alist))
1580         (let (wl-draft-config-variables)
1581           (funcall (cdr func) content)
1582           ;; for wl-draft-config-sub-template
1583           (cons t wl-draft-config-variables)))))
1584
1585 (defsubst wl-draft-config-exec-sub (clist)
1586   (let (config local-variables)
1587     (while clist
1588       (setq config (car clist))
1589       (cond
1590        ((consp config)
1591         (let ((field (car config))
1592               (content (cdr config))
1593               ret-val)
1594           (cond
1595            ((stringp field)
1596             (wl-draft-replace-field field (eval content) t))
1597            ((setq ret-val (wl-draft-config-sub-func field content))
1598             (if (cdr ret-val) ;; for wl-draft-config-sub-template
1599                 (wl-append local-variables (cdr ret-val))))
1600            ((boundp field) ;; variable
1601             (make-local-variable field)
1602             (set field (eval content))
1603             (wl-append local-variables (list field)))
1604            (t
1605             (error "%s: not variable" field)))))
1606        ((or (functionp config)
1607             (and (symbolp config)
1608                  (fboundp config)))
1609         (funcall config))
1610        (t
1611         (error "%s: not supported type" config)))
1612       (setq clist (cdr clist)))
1613     local-variables))
1614
1615 (defun wl-draft-prepared-config-exec (&optional config-alist reply-buf)
1616   "Change headers in draft preparation time."
1617   (interactive)
1618   (unless wl-draft-reedit
1619     (let ((config-alist
1620            (or config-alist
1621                (and (boundp 'wl-draft-prepared-config-alist)
1622                     wl-draft-prepared-config-alist)     ;; For compatible.
1623                wl-draft-config-alist)))
1624       (if config-alist
1625           (wl-draft-config-exec config-alist reply-buf)))))
1626
1627 (defun wl-draft-config-exec (&optional config-alist reply-buf)
1628   "Change headers in draft sending time."
1629   (interactive)
1630   (let ((case-fold-search t)
1631         (alist (or config-alist wl-draft-config-alist))
1632         (reply-buf (or reply-buf (and (buffer-live-p wl-draft-reply-buffer)
1633                                       wl-draft-reply-buffer)))
1634         (local-variables wl-draft-config-variables)
1635         key clist found)
1636     (when (and (or (interactive-p)
1637                    wl-draft-config-exec-flag)
1638                alist)
1639       (save-excursion
1640         (catch 'done
1641           (while alist
1642             (setq key (caar alist)
1643                   clist (cdar alist))
1644             (cond
1645              ((eq key 'reply)
1646               (when (and
1647                      reply-buf
1648                      (save-excursion
1649                        (set-buffer reply-buf)
1650                        (save-restriction
1651                          (std11-narrow-to-header)
1652                          (goto-char (point-min))
1653                          (re-search-forward (car clist) nil t))))
1654                 (wl-draft-config-exec-sub (cdr clist))
1655                 (setq found t)))
1656              ((stringp key)
1657               (when (save-restriction
1658                       (std11-narrow-to-header mail-header-separator)
1659                       (goto-char (point-min))
1660                       (re-search-forward key nil t))
1661                 (wl-append local-variables
1662                            (wl-draft-config-exec-sub clist))
1663                 (setq found t)))
1664              ((eval key)
1665               (wl-append local-variables
1666                          (wl-draft-config-exec-sub clist))
1667               (setq found t)))
1668             (if (and found wl-draft-config-matchone)
1669                 (throw 'done t))
1670             (setq alist (cdr alist))))
1671         (if found
1672             (setq wl-draft-config-exec-flag nil))
1673         (run-hooks 'wl-draft-config-exec-hook)
1674         (put-text-property (point-min)(point-max) 'face nil)
1675         (wl-highlight-message (point-min)(point-max) t)
1676         (setq wl-draft-config-variables
1677               (elmo-uniq-list local-variables))))))
1678
1679 (defun wl-draft-replace-field (field content &optional add)
1680   (save-excursion
1681     (save-restriction
1682       (let ((case-fold-search t)
1683             (inhibit-read-only t) ;; added by teranisi.
1684             beg)
1685         (std11-narrow-to-header mail-header-separator)
1686         (goto-char (point-min))
1687         (if (re-search-forward (concat "^" (regexp-quote field) ":") nil t)
1688             (if content
1689                 ;; replace field
1690                 (progn
1691                   (setq beg (point))
1692                   (re-search-forward "^[^ \t]" nil 'move)
1693                   (beginning-of-line)
1694                   (skip-chars-backward "\n")
1695                   (delete-region beg (point))
1696                   (insert " " content))
1697               ;; delete field
1698               (save-excursion
1699                 (beginning-of-line)
1700                 (setq beg (point)))
1701               (re-search-forward "^[^ \t]" nil 'move)
1702               (beginning-of-line)
1703               (delete-region beg (point)))
1704           (when (and add content)
1705             ;; add field
1706             (goto-char (point-max))
1707             (insert (concat field ": " content "\n"))))))))
1708
1709 (defun wl-draft-config-info-operation (msg operation)
1710   (let* ((msgdb-dir (elmo-msgdb-expand-path 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-msgdb-expand-path wl-queue-folder))
1736          (filename
1737           (expand-file-name
1738            (format "%s-%d" wl-draft-queue-save-filename msg)
1739            msgdb-dir))
1740          element alist variable)
1741     (cond
1742      ((eq operation 'save)
1743       (let ((variables (elmo-uniq-list
1744                         (append wl-draft-queue-save-variables
1745                                 wl-draft-config-variables
1746                                 (list 'wl-draft-fcc-list)))))
1747         (if add-sent-message-via
1748             (push 'wl-sent-message-via variables))
1749         (while (setq variable (pop variables))
1750           (when (boundp variable)
1751             (wl-append alist
1752                        (list (cons variable (eval variable))))))
1753         (elmo-object-save filename alist)))
1754      ((eq operation 'load)
1755       (setq alist (elmo-object-load filename))
1756       (while (setq element (pop alist))
1757         (set (make-local-variable (car element)) (cdr element))))
1758      ((eq operation 'get-sent-via)
1759       (setq alist (elmo-object-load filename))
1760       (cdr (assq 'wl-sent-message-via alist)))
1761      ((eq operation 'delete)
1762       (if (file-exists-p filename)
1763           (delete-file filename))))))
1764
1765 (defun wl-draft-queue-append (wl-sent-message-via)
1766   (if wl-draft-verbose-send
1767       (message "Queuing..."))
1768   (let ((send-buffer (current-buffer))
1769         (message-id (std11-field-body "Message-ID")))
1770     (if (elmo-append-msg wl-queue-folder
1771                          (buffer-substring (point-min) (point-max))
1772                          message-id)
1773         (progn
1774           (if message-id
1775               (elmo-dop-lock-message message-id))
1776           (wl-draft-queue-info-operation
1777            (car (elmo-max-of-folder wl-queue-folder))
1778            'save wl-sent-message-via)
1779           (wl-draft-write-sendlog 'ok 'queue nil wl-queue-folder message-id)
1780           (when wl-draft-verbose-send
1781             (setq wl-draft-verbose-msg "Queuing...")
1782             (message "Queuing...done")))
1783       (wl-draft-write-sendlog 'failed 'queue nil wl-queue-folder message-id)
1784       (error "Queuing failed"))))
1785
1786 (defun wl-draft-queue-flush ()
1787   "Flush draft queue."
1788   (interactive)
1789   (let ((msgs2 (elmo-list-folder wl-queue-folder))
1790         (i 0)
1791         (performed 0)
1792         (wl-draft-queue-flushing t)
1793         msgs failure len buffer msgid sent-via)
1794     ;; get plugged send message
1795     (while msgs2
1796       (setq sent-via (wl-draft-queue-info-operation (car msgs2) 'get-sent-via))
1797       (catch 'found
1798         (while sent-via
1799           (when (and (eq (nth 1 (car sent-via)) 'unplugged)
1800                      (elmo-plugged-p
1801                       (car (nth 2 (car sent-via)))
1802                       (cdr (nth 2 (car sent-via)))))
1803             (wl-append msgs (list (car msgs2)))
1804             (throw 'found t))
1805           (setq sent-via (cdr sent-via))))
1806       (setq msgs2 (cdr msgs2)))
1807     (when (> (setq len (length msgs)) 0)
1808       (if (elmo-y-or-n-p (format
1809                           "%d message(s) are in the sending queue. Send now?"
1810                           len)
1811                          (not elmo-dop-flush-confirm) t)
1812           (progn
1813             (save-excursion
1814               (setq buffer (get-buffer-create " *wl-draft-queue-flush*"))
1815               (set-buffer buffer)
1816               (while msgs
1817                 ;; reset buffer local variables
1818                 (kill-all-local-variables)
1819                 (erase-buffer)
1820                 (setq i (+ 1 i)
1821                       failure nil)
1822                 (setq wl-sent-message-via nil)
1823                 (wl-draft-queue-info-operation (car msgs) 'load)
1824                 (elmo-read-msg-no-cache wl-queue-folder (car msgs)
1825                                         (current-buffer))
1826                 (condition-case err
1827                     (setq failure (funcall
1828                                    wl-draft-queue-flush-send-func
1829                                    (format "Sending (%d/%d)..." i len)))
1830 ;;;               (wl-draft-raw-send nil nil
1831 ;;;                                  (format "Sending (%d/%d)..." i len))
1832                   (error
1833                    (elmo-display-error err t)
1834                    (setq failure t))
1835                   (quit
1836                    (setq failure t)))
1837                 (unless failure
1838                   (elmo-delete-msgs wl-queue-folder (cons (car msgs) nil))
1839                   (wl-draft-queue-info-operation (car msgs) 'delete)
1840                   (elmo-dop-unlock-message (std11-field-body "Message-ID"))
1841                   (setq performed (+ 1 performed)))
1842                 (setq msgs (cdr msgs)))
1843               (kill-buffer buffer)
1844               (message "%d message(s) are sent." performed)))
1845         (message "%d message(s) are remained to be sent." len))
1846       len)))
1847
1848 (defun wl-jump-to-draft-buffer (&optional arg)
1849   "Jump to the draft if exists."
1850   (interactive "P")
1851   (if arg
1852       (wl-jump-to-draft-folder)
1853     (let ((bufs (buffer-list))
1854           (draft-regexp (concat
1855                          "^" (regexp-quote
1856                               (expand-file-name
1857                                (nth 1 (elmo-folder-get-spec wl-draft-folder))
1858                                (expand-file-name
1859                                 elmo-localdir-folder-path)))))
1860           buf draft-bufs)
1861       (while bufs
1862         (if (and
1863              (setq buf (buffer-file-name (car bufs)))
1864              (string-match draft-regexp buf))
1865             (setq draft-bufs (cons (buffer-name (car bufs)) draft-bufs)))
1866         (setq bufs (cdr bufs)))
1867       (cond
1868        ((null draft-bufs)
1869         (message "No draft buffer exist."))
1870        (t
1871         (setq draft-bufs
1872               (sort draft-bufs (function (lambda (a b) (not (string< a b))))))
1873         (if (setq buf (cdr (member (buffer-name) draft-bufs)))
1874             (setq buf (car buf))
1875           (setq buf (car draft-bufs)))
1876         (switch-to-buffer buf))))))
1877
1878 (defun wl-jump-to-draft-folder ()
1879   (let ((msgs (reverse (elmo-list-folder 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