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