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