* wl-draft.el (wl-draft-send-mail-with-smtp): Fix logic
[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       (kill-buffer tmp-buf))
622     ;; Set cursor point to the top.
623     (goto-char (point-min))
624     (search-forward (concat mail-header-separator "\n") nil t)
625     (run-hooks 'wl-draft-reedit-hook)
626     (and to (mail-position-on-field "To"))))
627
628 (defun wl-draft-insert-current-message (dummy)
629   (interactive)
630   (let (original-buffer
631         mail-reply-buffer
632         mail-citation-hook mail-yank-hooks
633         wl-draft-add-references wl-draft-add-in-reply-to
634         wl-draft-cite-function)
635     (with-current-buffer wl-draft-buffer-cur-summary-buffer
636       (with-current-buffer wl-message-buffer
637         (setq original-buffer (wl-message-get-original-buffer))
638         (if (zerop
639              (with-current-buffer original-buffer
640                (buffer-size)))
641             (error "No current message"))))
642     (setq mail-reply-buffer original-buffer)
643     (wl-draft-yank-from-mail-reply-buffer
644      nil
645      wl-ignored-forwarded-headers)))
646
647 (defun wl-draft-insert-get-message (dummy)
648   (let ((fld (completing-read
649               "Folder name: "
650               (if (memq 'read-folder wl-use-folder-petname)
651                   (wl-folder-get-entity-with-petname)
652                 wl-folder-entity-hashtb)
653               nil nil wl-default-spec
654               'wl-read-folder-hist))
655         (number (call-interactively
656                  (function (lambda (num)
657                              (interactive "nNumber: ")
658                              num))))
659         (mail-reply-buffer (get-buffer-create "*wl-draft-insert-get-message*"))
660         mail-citation-hook mail-yank-hooks
661         wl-draft-cite-function)
662     (unwind-protect
663         (progn
664           (elmo-message-fetch (wl-folder-get-elmo-folder fld)
665                               number
666                               ;; No cache.
667                               (elmo-make-fetch-strategy 'entire)
668                               nil mail-reply-buffer)
669           (wl-draft-yank-from-mail-reply-buffer nil))
670       (kill-buffer mail-reply-buffer))))
671
672 ;;
673 ;; default body citation func
674 ;;
675 (defun wl-default-draft-cite ()
676   (let ((mail-yank-ignored-headers "[^:]+:")
677         (mail-yank-prefix "> ")
678         (summary-buf wl-current-summary-buffer)
679         (message-buf (get-buffer (wl-current-message-buffer)))
680         from date cite-title num entity)
681     (if (and summary-buf
682              (buffer-live-p summary-buf)
683              message-buf
684              (buffer-live-p message-buf))
685         (progn
686           (with-current-buffer summary-buf
687             (let ((elmo-mime-charset wl-summary-buffer-mime-charset))
688               (setq num (save-excursion
689                           (set-buffer message-buf)
690                           wl-message-buffer-cur-number))
691               (setq entity (elmo-msgdb-overview-get-entity
692                             num (wl-summary-buffer-msgdb)))
693               (setq date (elmo-msgdb-overview-entity-get-date entity))
694               (setq from (elmo-msgdb-overview-entity-get-from entity))))
695           (setq cite-title (format "At %s,\n%s wrote:"
696                                    (or date "some time ago")
697                                    (if wl-default-draft-cite-decorate-author
698                                        (funcall wl-summary-from-function
699                                                 (or from "you"))
700                                      (or from "you"))))))
701     (and cite-title
702          (insert cite-title "\n"))
703     (mail-indent-citation)))
704
705 (defvar wl-draft-buffer nil "Draft buffer to yank content")
706 (defun wl-draft-yank-to-draft-buffer (buffer)
707   "Yank BUFFER content to `wl-draft-buffer'."
708   (set-buffer wl-draft-buffer)
709   (let ((mail-reply-buffer buffer))
710     (wl-draft-yank-from-mail-reply-buffer nil)
711     (kill-buffer buffer)))
712
713 (defun wl-draft-yank-original (&optional arg)
714   "Yank original message."
715   (interactive "P")
716   (if arg
717       (let (buf mail-reply-buffer)
718         (elmo-set-work-buf
719          (yank)
720          (setq buf (current-buffer)))
721         (setq mail-reply-buffer buf)
722         (wl-draft-yank-from-mail-reply-buffer nil))
723     (wl-draft-yank-current-message-entity)))
724
725 (defun wl-draft-hide (editing-buffer)
726   "Hide the editing draft buffer if possible."
727   (when (and editing-buffer
728              (buffer-live-p editing-buffer))
729     (set-buffer editing-buffer)
730     (let ((sum-buf wl-draft-buffer-cur-summary-buffer)
731           fld-buf sum-win fld-win)
732       (if (and wl-draft-use-frame
733                (> (length (visible-frame-list)) 1))
734           ;; hide draft frame
735           (delete-frame)
736         ;; hide draft window
737         (or (one-window-p)
738             (delete-window))
739         ;; stay folder window if required
740         (when wl-stay-folder-window
741           (if (setq fld-buf (get-buffer wl-folder-buffer-name))
742               (if (setq fld-win (get-buffer-window fld-buf))
743                   (select-window fld-win)
744                 (if wl-draft-resume-folder-window ;; resume folder window
745                     (switch-to-buffer fld-buf)))))
746         (if (buffer-live-p sum-buf)
747             (if (setq sum-win (get-buffer-window sum-buf t))
748                 ;; if Summary is on the frame, select it.
749                 (select-window sum-win)
750               ;; if summary is not on the frame, switch to it.
751               (if (and wl-stay-folder-window
752                        (or wl-draft-resume-folder-window fld-win))
753                   (wl-folder-select-buffer sum-buf)
754                 (switch-to-buffer sum-buf))))))))
755
756 (defun wl-draft-delete (editing-buffer)
757   "kill the editing draft buffer and delete the file corresponds to it."
758   (save-excursion
759     (when editing-buffer
760       (set-buffer editing-buffer)
761       (if wl-draft-buffer-file-name
762           (progn
763             (if (file-exists-p wl-draft-buffer-file-name)
764                 (delete-file wl-draft-buffer-file-name))
765             (let ((msg (and wl-draft-buffer-file-name
766                             (string-match "[0-9]+$" wl-draft-buffer-file-name)
767                             (string-to-int
768                              (match-string 0 wl-draft-buffer-file-name)))))
769               (wl-draft-config-info-operation msg 'delete))))
770       (set-buffer-modified-p nil)               ; force kill
771       (kill-buffer editing-buffer))))
772
773 (defun wl-draft-kill (&optional force-kill)
774   "Kill current draft buffer and quit editing."
775   (interactive "P")
776   (save-excursion
777     (when (and (or (eq major-mode 'wl-draft-mode)
778                    (eq major-mode 'mail-mode))
779                (or force-kill
780                    (y-or-n-p "Kill Current Draft? ")))
781       (let ((cur-buf (current-buffer)))
782         (wl-draft-hide cur-buf)
783         (wl-draft-delete cur-buf)))
784     (message "")))
785
786 (defun wl-draft-fcc ()
787   "Add a new Fcc field, with file name completion."
788   (interactive)
789   (or (mail-position-on-field "fcc" t)  ;Put new field after exiting Fcc.
790       (mail-position-on-field "to"))
791   (insert "\nFcc: "))
792
793 ;; Imported from message.el.
794 (defun wl-draft-elide-region (b e)
795   "Elide the text in the region.
796 An ellipsis (from `wl-draft-elide-ellipsis') will be inserted where the
797 text was killed."
798   (interactive "r")
799   (kill-region b e)
800   (insert wl-draft-elide-ellipsis))
801
802 ;; Imported from message.el.
803 (defun wl-draft-beginning-of-line (&optional n)
804   "Move point to beginning of header value or to beginning of line."
805   (interactive "p")
806   (let ((zrs 'zmacs-region-stays))
807     (when (and (interactive-p) (boundp zrs))
808       (set zrs t)))
809   (if (wl-draft-point-in-header-p)
810       (let* ((here (point))
811              (bol (progn (beginning-of-line n) (point)))
812              (eol (line-end-position))
813              (eoh (and (looking-at "[^ \t]")
814                        (re-search-forward ": *" eol t))))
815         (if (and eoh (or (> here eoh) (= here bol)))
816             (goto-char eoh)
817           (goto-char bol)))
818     (beginning-of-line n)))
819
820 (defun wl-draft-point-in-header-p ()
821   "Return t if point is in the header."
822   (save-excursion
823     (let ((p (point)))
824       (goto-char (point-min))
825       (not (re-search-forward
826             (concat "^" (regexp-quote mail-header-separator) "\n")
827             p t)))))
828
829 ;; function for wl-sent-message-via
830
831 (defmacro wl-draft-sent-message-p (type)
832   (` (eq (nth 1 (assq (, type) wl-sent-message-via)) 'sent)))
833
834 (defmacro wl-draft-set-sent-message (type result &optional server-port)
835   (` (let ((element (assq (, type) wl-sent-message-via)))
836        (if element
837            (unless (eq (nth 1 element) (, result))
838              (setcdr element (list (, result) (, server-port)))
839              (setq wl-sent-message-modified t))
840          (push (list (, type) (, result) (, server-port)) wl-sent-message-via)
841          (setq wl-sent-message-modified t)))))
842
843 (defun wl-draft-sent-message-results ()
844   (let ((results wl-sent-message-via)
845         unplugged-via sent-via)
846     (while results
847       (cond ((eq (nth 1 (car results)) 'unplugged)
848              (push (caar results) unplugged-via))
849             ((eq (nth 1 (car results)) 'sent)
850              (push (caar results) sent-via)))
851       (setq results (cdr results)))
852     (list unplugged-via sent-via)))
853
854 (defun wl-draft-write-sendlog (status proto server to id)
855   "Write send log file, if `wl-draft-sendlog' is non-nil."
856   (when wl-draft-sendlog
857     (with-temp-buffer
858       (let* ((filename (expand-file-name wl-draft-sendlog-filename
859                                          elmo-msgdb-directory))
860              (filesize (nth 7 (file-attributes filename)))
861              (server (if server (concat " server=" server) ""))
862              (to (if to (cond
863                          ((memq proto '(fcc queue))
864                           (format " folder=\"%s\"" to))
865                          ((eq proto 'nntp)
866                           (format " ng=<%s>" to))
867                          (t
868                           (concat " to="
869                                   (mapconcat
870                                    'identity
871                                    (mapcar '(lambda(x) (format "<%s>" x)) to)
872                                    ","))))
873                    ""))
874              (id (if id (concat " id=" id) ""))
875              (time (format-time-string "%Y/%m/%d %T")))
876         (insert (format "%s proto=%s stat=%s%s%s%s\n"
877                         time proto status server to id))
878         (if (and wl-draft-sendlog-max-size filesize
879                  (> filesize wl-draft-sendlog-max-size))
880             (rename-file filename (concat filename ".old") t))
881         (if (file-writable-p filename)
882             (write-region-as-binary (point-min) (point-max)
883                                     filename t 'no-msg)
884           (message "%s is not writable." filename))))))
885
886 (defun wl-draft-get-header-delimiter (&optional delete)
887   ;; If DELETE is non-nil, replace the header delimiter with a blank line
888   (let (delimline)
889     (goto-char (point-min))
890     (when (re-search-forward
891            (concat "^" (regexp-quote mail-header-separator) "$\\|^$") nil t)
892       (replace-match "")
893       (if delete
894           (forward-char -1))
895       (setq delimline (point-marker)))
896     delimline))
897
898 (defun wl-draft-send-mail-with-qmail ()
899   "Pass the prepared message buffer to qmail-inject.
900 Refer to the documentation for the variable `send-mail-function'
901 to find out how to use this."
902   (if (and wl-draft-qmail-send-plugged
903            (not (elmo-plugged-p)))
904       (wl-draft-set-sent-message 'mail 'unplugged)
905     ;; send the message
906     (run-hooks 'wl-mail-send-pre-hook) ;; X-PGP-Sig, Cancel-Lock
907     (let ((id (std11-field-body "Message-ID"))
908           (to (std11-field-body "To")))
909       (case
910           (as-binary-process
911            (apply
912             'call-process-region 1 (point-max) wl-qmail-inject-program
913             nil nil nil
914             wl-qmail-inject-args))
915         ;; qmail-inject doesn't say anything on it's stdout/stderr,
916         ;; we have to look at the retval instead
917         (0   (progn
918                (wl-draft-set-sent-message 'mail 'sent)
919                (wl-draft-write-sendlog 'ok 'qmail nil (list to) id)))
920         (1   (error "`qmail-inject' reported permanent failure"))
921         (111 (error "`qmail-inject' reported transient failure"))
922         ;; should never happen
923         (t   (error "`qmail-inject' reported unknown failure"))))))
924
925 (defun wl-draft-parse-msg-id-list-string (string)
926   "Get msg-id list from STRING."
927   (let (msg-id-list)
928     (dolist (parsed-id (std11-parse-msg-ids-string string))
929       (when (eq (car parsed-id) 'msg-id)
930         (setq msg-id-list (cons (std11-msg-id-string parsed-id)
931                                 msg-id-list))))
932     (nreverse msg-id-list)))
933
934 (defun wl-draft-eword-encode-address-list (string &optional column)
935   "Encode header field STRING as list of address, and return the result.
936 Cause an error when STRING contains invalid address.
937 Optional argument COLUMN is start-position of the field."
938   (car (eword-encode-rword-list
939         (or column eword-encode-default-start-column)
940         (eword-encode-addresses-to-rword-list
941          (wl-draft-std11-parse-addresses (std11-lexical-analyze string))))))
942
943 (defun wl-draft-std11-parse-addresses (lal)
944   (let ((ret (std11-parse-address lal)))
945     (when (and (not (and (eq (length lal) 1)
946                          (eq (car (car lal)) 'spaces)))
947                (null ret))
948       (error "Error while parsing address"))
949     (if ret
950         (let ((dest (list (car ret))))
951           (setq lal (cdr ret))
952           (while (and (setq ret (std11-parse-ascii-token lal))
953                       (string-equal (cdr (assq 'specials (car ret))) ",")
954                       (setq ret (std11-parse-address (cdr ret)))
955                       )
956             (setq dest (cons (car ret) dest))
957             (setq lal (cdr ret)))
958           (while (eq 'spaces (car (car lal)))
959             (setq lal (cdr lal)))
960           (if lal (error "Error while parsing address"))
961           (nreverse dest)))))
962
963 (defun wl-draft-parse-mailbox-list (field &optional remove-group-list)
964   "Get mailbox list of FIELD from current buffer.
965 The buffer is expected to be narrowed to just the headers of the message.
966 If optional argument REMOVE-GROUP-LIST is non-nil, remove group list content
967 from current buffer."
968   (save-excursion
969     (let ((case-fold-search t)
970           (inhibit-read-only t)
971           addresses address
972           mailbox-list beg seq has-group-list)
973       (goto-char (point-min))
974       (while (re-search-forward (concat "^" (regexp-quote field) "[\t ]*:")
975                                 nil t)
976         (setq beg (point))
977         (re-search-forward "^[^ \t]" nil 'move)
978         (beginning-of-line)
979         (skip-chars-backward "\n")
980         (setq seq (std11-lexical-analyze
981                    (buffer-substring-no-properties beg (point))))
982         (setq addresses (wl-draft-std11-parse-addresses seq))
983         (while addresses
984           (cond ((eq (car (car addresses)) 'group)
985                  (setq has-group-list t)
986                  (setq mailbox-list
987                        (nconc mailbox-list
988                               (mapcar
989                                'std11-address-string
990                                (nth 2 (car addresses))))))
991                 ((eq (car (car addresses)) 'mailbox)
992                  (setq address (nth 1 (car addresses)))
993                  (setq mailbox-list
994                        (nconc mailbox-list
995                               (list
996                                (std11-addr-to-string
997                                 (if (eq (car address) 'phrase-route-addr)
998                                     (nth 2 address)
999                                   (cdr address))))))))
1000           (setq addresses (cdr addresses)))
1001         (when (and remove-group-list has-group-list)
1002           (delete-region beg (point))
1003           (insert (wl-address-string-without-group-list-contents seq))))
1004       mailbox-list)))
1005
1006 (defun wl-draft-deduce-address-list (buffer header-start header-end)
1007   "Get address list suitable for smtp RCPT TO:<address>.
1008 Group list content is removed if `wl-draft-remove-group-list-contents' is
1009 non-nil."
1010   (let ((fields (if (and wl-draft-doing-mime-bcc
1011                          wl-draft-disable-bcc-for-mime-bcc)
1012                     '("to" "cc")
1013                   '("to" "cc" "bcc")))
1014         (resent-fields '("resent-to" "resent-cc" "resent-bcc"))
1015         (case-fold-search t)
1016         addrs recipients)
1017     (save-excursion
1018       (save-restriction
1019         (narrow-to-region header-start header-end)
1020         (goto-char (point-min))
1021         (save-excursion
1022           (if (re-search-forward "^resent-to[\t ]*:" nil t)
1023               (setq fields resent-fields)))
1024         (while fields
1025           (setq recipients
1026                 (nconc recipients
1027                        (wl-draft-parse-mailbox-list
1028                         (car fields)
1029                         wl-draft-remove-group-list-contents)))
1030           (setq fields (cdr fields)))
1031         recipients))))
1032
1033 ;;
1034 ;; from Semi-gnus
1035 ;;
1036 (defun wl-draft-send-mail-with-smtp ()
1037   "Send the prepared message buffer with SMTP."
1038   (require 'smtp)
1039   (let* ((errbuf (if mail-interactive
1040                      (generate-new-buffer " smtp errors")
1041                    0))
1042          (case-fold-search t)
1043          (default-case-fold-search t)
1044          (sender (or wl-envelope-from
1045                      (wl-address-header-extract-address wl-from)))
1046          (delimline (save-excursion
1047                       (goto-char (point-min))
1048                       (re-search-forward
1049                        (concat "^" (regexp-quote mail-header-separator)
1050                                "$\\|^$") nil t)
1051                       (point-marker)))
1052          (smtp-server
1053           (or wl-smtp-posting-server smtp-server "localhost"))
1054          (smtp-service (or wl-smtp-posting-port smtp-service))
1055          (smtp-local-domain (or smtp-local-domain wl-local-domain))
1056          (id (std11-field-body "message-id"))
1057          recipients)
1058     (if (not (elmo-plugged-p smtp-server smtp-service))
1059         (wl-draft-set-sent-message 'mail 'unplugged
1060                                    (cons smtp-server smtp-service))
1061       (unwind-protect
1062           (save-excursion
1063             ;; Instead of `smtp-deduce-address-list'.
1064             (setq recipients (wl-draft-deduce-address-list
1065                               (current-buffer) (point-min) delimline))
1066             (unless recipients (error "No recipients"))
1067             ;; Insert an extra newline if we need it to work around
1068             ;; Sun's bug that swallows newlines.
1069             (goto-char (1+ delimline))
1070             (if (eval mail-mailer-swallows-blank-line)
1071                 (newline))
1072             (run-hooks 'wl-mail-send-pre-hook) ;; X-PGP-Sig, Cancel-Lock
1073             (if mail-interactive
1074                 (save-excursion
1075                   (set-buffer errbuf)
1076                   (erase-buffer)))
1077             (wl-draft-delete-field "bcc" delimline)
1078             (wl-draft-delete-field "resent-bcc" delimline)
1079             (let (process-connection-type)
1080               (as-binary-process
1081                (when recipients
1082                  (wl-smtp-extension-bind
1083                   (condition-case err
1084                       (smtp-send-buffer sender recipients (current-buffer))
1085                     (error
1086                      (wl-draft-write-sendlog 'failed 'smtp smtp-server
1087                                              recipients id)
1088                      (if (and (eq (car err) 'smtp-response-error)
1089                               (= (nth 1 err) 535))
1090                          (elmo-remove-passwd
1091                           (wl-smtp-password-key
1092                            smtp-sasl-user-name
1093                            (car smtp-sasl-mechanisms)
1094                            smtp-server)))
1095                      (signal (car err) (cdr err)))))
1096                  (wl-draft-set-sent-message 'mail 'sent)
1097                  (wl-draft-write-sendlog
1098                   'ok 'smtp smtp-server recipients id)))))
1099         (if (bufferp errbuf)
1100             (kill-buffer errbuf))))))
1101
1102 (defun wl-draft-send-mail-with-pop-before-smtp ()
1103   "Send the prepared message buffer with POP-before-SMTP."
1104   (require 'elmo-pop3)
1105   (let ((session
1106          (luna-make-entity
1107           'elmo-pop3-folder
1108           :user   (or wl-pop-before-smtp-user
1109                       elmo-pop3-default-user)
1110           :server (or wl-pop-before-smtp-server
1111                       elmo-pop3-default-server)
1112           :port   (or wl-pop-before-smtp-port
1113                       elmo-pop3-default-port)
1114           :auth   (or wl-pop-before-smtp-authenticate-type
1115                       elmo-pop3-default-authenticate-type)
1116           :stream-type (or wl-pop-before-smtp-stream-type
1117                            elmo-pop3-default-stream-type))))
1118     (condition-case error
1119         (progn
1120           (elmo-pop3-get-session session)
1121           (when session (elmo-network-close-session session)))
1122       (error
1123        (elmo-network-close-session session)
1124        (unless (string= (nth 1 error) "Unplugged")
1125          (signal (car error)(cdr error))))))
1126   (wl-draft-send-mail-with-smtp))
1127
1128 (defun wl-draft-insert-required-fields (&optional force-msgid)
1129   "Insert Message-ID, Date, and From field.
1130 If FORCE-MSGID, insert message-id regardless of `wl-insert-message-id'."
1131   ;; Insert Message-Id field...
1132   (goto-char (point-min))
1133   (when (and (or force-msgid
1134                  wl-insert-message-id)
1135              (not (re-search-forward "^Message-ID[ \t]*:" nil t)))
1136     (insert (concat "Message-ID: "
1137                     (funcall wl-message-id-function)
1138                     "\n")))
1139   ;; Insert date field.
1140   (goto-char (point-min))
1141   (or (re-search-forward "^Date[ \t]*:" nil t)
1142       (wl-draft-insert-date-field))
1143   ;; Insert from field.
1144   (goto-char (point-min))
1145   (or (re-search-forward "^From[ \t]*:" nil t)
1146       (wl-draft-insert-from-field)))
1147
1148 (defun wl-draft-normal-send-func (editing-buffer kill-when-done)
1149   "Send the message in the current buffer."
1150   (save-restriction
1151     (std11-narrow-to-header mail-header-separator)
1152     (wl-draft-insert-required-fields)
1153     ;; Delete null fields.
1154     (goto-char (point-min))
1155     (while (re-search-forward "^[^ \t\n:]+:[ \t]*\n" nil t)
1156       (replace-match ""))
1157     ;; ignore any blank lines in the header
1158     (while (re-search-forward "\n\n\n*" nil t)
1159       (replace-match "\n")))
1160 ;;;  (run-hooks 'wl-mail-send-pre-hook) ;; X-PGP-Sig, Cancel-Lock
1161   (wl-draft-dispatch-message)
1162   (when kill-when-done
1163     ;; hide editing-buffer.
1164     (wl-draft-hide editing-buffer)
1165     ;; delete editing-buffer and its file.
1166     (wl-draft-delete editing-buffer)))
1167
1168 (defun wl-draft-dispatch-message (&optional mes-string)
1169   "Send the message in the current buffer.  Not modified the header fields."
1170   (let (delimline mime-bcc)
1171     (if (and wl-draft-verbose-send mes-string)
1172         (message mes-string))
1173     ;; get fcc folders.
1174     (setq delimline (wl-draft-get-header-delimiter t))
1175     (unless wl-draft-fcc-list
1176       (setq wl-draft-fcc-list (wl-draft-get-fcc-list delimline)))
1177     ;;
1178     (setq wl-sent-message-modified nil)
1179     (unwind-protect
1180         (progn
1181           (if (and (wl-message-mail-p)
1182                    (not (wl-draft-sent-message-p 'mail)))
1183               (if (or (not (or wl-draft-force-queuing
1184                                wl-draft-force-queuing-mail))
1185                       (memq 'mail wl-sent-message-queued))
1186                   (progn
1187                     (setq mime-bcc (wl-draft-mime-bcc-field))
1188                     (funcall wl-draft-send-mail-function)
1189                     (when (not (zerop (length mime-bcc)))
1190                       (wl-draft-do-mime-bcc mime-bcc)))
1191                 (push 'mail wl-sent-message-queued)
1192                 (wl-draft-set-sent-message 'mail 'unplugged)))
1193           (if (and (wl-message-news-p)
1194                    (not (wl-draft-sent-message-p 'news))
1195                    (not (wl-message-field-exists-p "Resent-to")))
1196               (if (or (not (or wl-draft-force-queuing
1197                                wl-draft-force-queuing-news))
1198                       (memq 'news wl-sent-message-queued))
1199                   (funcall wl-draft-send-news-function)
1200                 (push 'news wl-sent-message-queued)
1201                 (wl-draft-set-sent-message 'news 'unplugged))))
1202       (let* ((status (wl-draft-sent-message-results))
1203              (unplugged-via (car status))
1204              (sent-via (nth 1 status)))
1205         ;; If one sent, process fcc folder.
1206         (if (and sent-via wl-draft-fcc-list)
1207             (progn
1208               (wl-draft-do-fcc (wl-draft-get-header-delimiter)
1209                                wl-draft-fcc-list)
1210               (setq wl-draft-fcc-list nil)))
1211         (if wl-draft-use-cache
1212             (let ((id (std11-field-body "Message-ID"))
1213                   (elmo-enable-disconnected-operation t))
1214               (elmo-file-cache-save (elmo-file-cache-get-path id)
1215                                     nil)))
1216         ;; If one unplugged, append queue.
1217         (when (and unplugged-via
1218                    wl-sent-message-modified)
1219           (if wl-draft-enable-queuing
1220               (progn
1221                 (wl-draft-queue-append wl-sent-message-via)
1222                 (setq wl-sent-message-modified 'requeue))
1223             (error "Unplugged")))
1224         (when wl-draft-verbose-send
1225           (if (and unplugged-via sent-via);; combined message
1226               (progn
1227                 (setq wl-draft-verbose-msg
1228                       (format "Sending%s and Queuing%s..."
1229                               sent-via unplugged-via))
1230                 (message (concat wl-draft-verbose-msg "done")))
1231             (if mes-string
1232                 (message (concat mes-string
1233                                  (if sent-via "done" "failed")))))))))
1234   (not wl-sent-message-modified)) ;; return value
1235
1236 (defun wl-draft-raw-send (&optional kill-when-done force-pre-hook mes-string)
1237   "Force send current buffer as raw message."
1238   (interactive)
1239   (save-excursion
1240     (let (wl-interactive-send
1241 ;;;       wl-draft-verbose-send
1242           (wl-mail-send-pre-hook (and force-pre-hook wl-mail-send-pre-hook))
1243           (wl-news-send-pre-hook (and force-pre-hook wl-news-send-pre-hook))
1244           mail-send-hook
1245           mail-send-actions)
1246       (wl-draft-send kill-when-done mes-string))))
1247
1248 (defun wl-draft-clone-local-variables ()
1249   (let ((locals (buffer-local-variables))
1250         result)
1251     (while locals
1252       (when (and (consp (car locals))
1253                  (car (car locals))
1254                  (string-match wl-draft-clone-local-variable-regexp
1255                                (symbol-name (car (car locals)))))
1256         (wl-append result (list (car (car locals)))))
1257       (setq locals (cdr locals)))
1258     result))
1259
1260 (defun wl-draft-send (&optional kill-when-done mes-string)
1261   "Send current draft message.
1262 If KILL-WHEN-DONE is non-nil, current draft buffer is killed"
1263   (interactive)
1264   ;; Don't call this explicitly.
1265   ;; Added to 'wl-draft-send-hook (by teranisi)
1266   ;; (wl-draft-config-exec)
1267   (run-hooks 'wl-draft-send-hook)
1268   (when (or (not wl-interactive-send)
1269             (y-or-n-p "Do you really want to send current draft? "))
1270     (let ((send-mail-function 'wl-draft-raw-send)
1271           (editing-buffer (current-buffer))
1272           (sending-buffer (wl-draft-generate-clone-buffer
1273                            " *wl-draft-sending-buffer*"
1274                            (append wl-draft-config-variables
1275                                    (wl-draft-clone-local-variables))))
1276           (wl-draft-verbose-msg nil)
1277           err)
1278       (unwind-protect
1279           (save-excursion (set-buffer sending-buffer)
1280             (if (and (not (wl-message-mail-p))
1281                      (not (wl-message-news-p)))
1282                 (error "No recipient is specified"))
1283             (expand-abbrev) ; for mail-abbrevs
1284             (let ((mime-header-encode-method-alist
1285                    (append
1286                     '((wl-draft-eword-encode-address-list
1287                        .  (To Cc Bcc Resent-To Resent-Cc Bcc Resent-Bcc)))
1288                     (if (boundp 'mime-header-encode-method-alist)
1289                         (symbol-value 'mime-header-encode-method-alist)))))
1290               (run-hooks 'mail-send-hook) ; translate buffer
1291               )
1292             ;;
1293             (if wl-draft-verbose-send
1294                 (message (or mes-string "Sending...")))
1295             (funcall wl-draft-send-function editing-buffer kill-when-done)
1296             ;; Now perform actions on successful sending.
1297             (while mail-send-actions
1298               (condition-case ()
1299                   (apply (car (car mail-send-actions))
1300                          (cdr (car mail-send-actions)))
1301                 (error))
1302               (setq mail-send-actions (cdr mail-send-actions)))
1303             (if wl-draft-verbose-send
1304                 (message (concat (or wl-draft-verbose-msg
1305                                      mes-string "Sending...")
1306                                  "done"))))
1307         ;; kill sending buffer, anyway.
1308         (and (buffer-live-p sending-buffer)
1309              (kill-buffer sending-buffer))))))
1310
1311 (defun wl-draft-mime-bcc-field ()
1312   "Return the MIME-Bcc field body. The field is deleted."
1313   (prog1 (std11-field-body wl-draft-mime-bcc-field-name)
1314     (wl-draft-delete-field wl-draft-mime-bcc-field-name)))
1315
1316 (defun wl-draft-do-mime-bcc (field-body)
1317   "Send MIME-Bcc (Encapsulated blind carbon copy)."
1318   (let ((orig-from (mime-decode-field-body (std11-field-body "from")
1319                                            'From))
1320         (orig-subj (mime-decode-field-body (or (std11-field-body "subject")
1321                                                "")
1322                                            'Subject))
1323         (recipients (wl-parse-addresses field-body))
1324         (draft-buffer (current-buffer))
1325         wl-draft-use-frame)
1326     (save-window-excursion
1327       (when (and (not wl-draft-doing-mime-bcc) ; To avoid infinite loop.
1328                  (not (zerop (length field-body))))
1329         (let ((wl-draft-doing-mime-bcc t))
1330           (dolist (recipient recipients)
1331             (wl-draft-create-buffer)
1332             (wl-draft-create-contents
1333              (append `((From . ,orig-from)
1334                        (To . ,recipient)
1335                        (Subject . ,(concat "A blind carbon copy ("
1336                                            orig-subj
1337                                            ")")))
1338                      (wl-draft-default-headers)))
1339             (wl-draft-insert-mail-header-separator)
1340             (wl-draft-prepare-edit)
1341             (goto-char (point-max))
1342             (insert (or wl-draft-mime-bcc-body
1343                         "This is a blind carbon copy.")
1344                     "\n")
1345             (mime-edit-insert-tag "message" "rfc822")
1346             (insert-buffer draft-buffer)
1347             (let (wl-interactive-send)
1348               (wl-draft-send 'kill-when-done))))))))
1349
1350 ;; Derived from `message-save-drafts' in T-gnus.
1351 (defun wl-draft-save ()
1352   "Save current draft."
1353   (interactive)
1354   (if (buffer-modified-p)
1355       (progn
1356         (message "Saving %s..." wl-draft-buffer-file-name)
1357         (let ((msg (buffer-substring-no-properties (point-min) (point-max))))
1358           (with-temp-file wl-draft-buffer-file-name
1359             (insert msg)
1360             ;; If no header separator, insert it.
1361             (save-excursion
1362               (goto-char (point-min))
1363               (unless (re-search-forward
1364                        (concat "^" (regexp-quote mail-header-separator) "$")
1365                        nil t)
1366                 (goto-char (point-min))
1367                 (if (re-search-forward "\n\n" nil t)
1368                     (replace-match (concat "\n" mail-header-separator "\n"))
1369                   (goto-char (point-max))
1370                   (insert (if (eq (char-before) ?\n) "" "\n")
1371                           mail-header-separator "\n"))))
1372             (let ((mime-header-encode-method-alist
1373                    '((eword-encode-unstructured-field-body))))
1374               (mime-edit-translate-buffer))
1375             (wl-draft-get-header-delimiter t)))
1376         (set-buffer-modified-p nil)
1377         (wl-draft-config-info-operation
1378          (and (string-match "[0-9]+$" wl-draft-buffer-file-name)
1379               (string-to-int
1380                (match-string 0 wl-draft-buffer-file-name)))
1381          'save)
1382         (message "Saving %s...done" wl-draft-buffer-file-name))
1383     (message "(No changes need to be saved)")))
1384
1385 (defun wl-draft-mimic-kill-buffer ()
1386   "Kill the current (draft) buffer with query."
1387   (interactive)
1388   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
1389                                       (buffer-name))))
1390         wl-draft-use-frame)
1391     (if (or (not bufname)
1392             (string-equal bufname "")
1393             (string-equal bufname (buffer-name)))
1394         (let ((bufname (current-buffer)))
1395           (when (or (not (buffer-modified-p))
1396                     (yes-or-no-p
1397                      (format "Buffer %s modified; kill anyway? " bufname)))
1398             (set-buffer-modified-p nil)
1399             (wl-draft-hide bufname)
1400             (kill-buffer bufname)))
1401       (kill-buffer bufname))))
1402
1403 (defun wl-draft-save-and-exit ()
1404   "Save current draft and exit current draft mode."
1405   (interactive)
1406   (wl-draft-save)
1407   (let ((editing-buffer (current-buffer)))
1408     (wl-draft-hide editing-buffer)
1409     (kill-buffer editing-buffer)))
1410
1411 (defun wl-draft-send-and-exit ()
1412   "Send current draft message and kill it."
1413   (interactive)
1414   (wl-draft-send t))
1415
1416 (defun wl-draft-send-from-toolbar ()
1417   (interactive)
1418   (let ((wl-interactive-send t))
1419     (wl-draft-send-and-exit)))
1420
1421 (defun wl-draft-delete-field (field &optional delimline replace)
1422   (wl-draft-delete-fields (regexp-quote field) delimline replace))
1423
1424 (defun wl-draft-delete-fields (field &optional delimline replace)
1425   (save-restriction
1426     (unless delimline
1427       (goto-char (point-min))
1428       (if (search-forward "\n\n" nil t)
1429           (setq delimline (point))
1430         (setq delimline (point-max))))
1431     (narrow-to-region (point-min) delimline)
1432     (goto-char (point-min))
1433     (let ((regexp (concat "^" field ":"))
1434           (case-fold-search t))
1435       (while (not (eobp))
1436         (if (looking-at regexp)
1437             (progn
1438               (delete-region
1439                (point)
1440                (progn
1441                  (forward-line 1)
1442                  (if (re-search-forward "^[^ \t]" nil t)
1443                      (goto-char (match-beginning 0))
1444                    (point-max))))
1445               (if replace
1446                   (insert (concat field ": " replace "\n"))))
1447           (forward-line 1)
1448           (if (re-search-forward "^[^ \t]" nil t)
1449               (goto-char (match-beginning 0))
1450             (point-max)))))))
1451
1452 (defun wl-draft-get-fcc-list (header-end)
1453   (if (and wl-draft-doing-mime-bcc
1454            wl-draft-disable-fcc-for-mime-bcc)
1455       (progn
1456         (wl-draft-delete-field "fcc")
1457         nil)
1458     (let (fcc-list
1459           (case-fold-search t))
1460       (or (markerp header-end) (error "HEADER-END must be a marker"))
1461       (save-excursion
1462         (goto-char (point-min))
1463         (while (re-search-forward "^Fcc:[ \t]*" header-end t)
1464           (save-match-data
1465             (setq fcc-list
1466                   (append fcc-list
1467                           (split-string
1468                            (buffer-substring-no-properties
1469                             (point)
1470                             (progn
1471                               (end-of-line)
1472                               (skip-chars-backward " \t")
1473                               (point)))
1474                            ",[ \t]*")))
1475             (dolist (folder fcc-list)
1476               (wl-folder-confirm-existence
1477                (wl-folder-get-elmo-folder (eword-decode-string folder)))))
1478           (delete-region (match-beginning 0)
1479                          (progn (forward-line 1) (point)))))
1480       fcc-list)))
1481
1482 (defun wl-draft-do-fcc (header-end &optional fcc-list)
1483   (let ((send-mail-buffer (current-buffer))
1484         (tembuf (generate-new-buffer " fcc output"))
1485         (case-fold-search t)
1486         beg end)
1487     (or (markerp header-end) (error "HEADER-END must be a marker"))
1488     (save-excursion
1489       (unless fcc-list
1490         (setq fcc-list (wl-draft-get-fcc-list header-end)))
1491       (set-buffer tembuf)
1492       (erase-buffer)
1493       ;; insert just the headers to avoid moving the gap more than
1494       ;; necessary (the message body could be arbitrarily huge.)
1495       (insert-buffer-substring send-mail-buffer 1 header-end)
1496       (wl-draft-insert-required-fields t)
1497       (goto-char (point-max))
1498       (insert-buffer-substring send-mail-buffer header-end)
1499       (let ((id (std11-field-body "Message-ID"))
1500             (elmo-enable-disconnected-operation t)
1501             cache-saved)
1502         (while fcc-list
1503           (unless (or cache-saved
1504                       (elmo-folder-plugged-p
1505                        (wl-folder-get-elmo-folder (car fcc-list))))
1506             (elmo-file-cache-save id nil) ;; for disconnected operation
1507             (setq cache-saved t))
1508           (if (elmo-folder-append-buffer
1509                (wl-folder-get-elmo-folder
1510                 (eword-decode-string (car fcc-list)))
1511                (not wl-fcc-force-as-read))
1512               (wl-draft-write-sendlog 'ok 'fcc nil (car fcc-list) id)
1513             (wl-draft-write-sendlog 'failed 'fcc nil (car fcc-list) id))
1514           (setq fcc-list (cdr fcc-list)))))
1515     (kill-buffer tembuf)))
1516
1517 (defun wl-draft-on-field-p ()
1518   (if (< (point)
1519          (save-excursion
1520            (goto-char (point-min))
1521            (search-forward (concat "\n" mail-header-separator "\n") nil 0)
1522            (point)))
1523       (if (bolp)
1524           (if (bobp)
1525               t
1526             (save-excursion
1527               (forward-line -1)
1528               (if (or (looking-at ".*,[ \t]?$")
1529                       (looking-at "^[^ \t]+:[ \t]+.*:$")); group list name
1530                   nil t)))
1531         (let ((pos (point)))
1532           (save-excursion
1533             (beginning-of-line)
1534             (if (looking-at "^[ \t]")
1535                 nil
1536               (if (re-search-forward ":" pos t) nil t)))))))
1537
1538 ;;;;;;;;;;;;;;;;
1539 ;;;###autoload
1540 (defun wl-draft (&optional header-alist
1541                            content-type content-transfer-encoding
1542                            body edit-again
1543                            parent-folder)
1544   "Write and send mail/news message with Wanderlust."
1545   (interactive)
1546   (require 'wl)
1547   (unless wl-init
1548     (wl-load-profile)
1549     (wl-folder-init)
1550     (elmo-init)
1551     (wl-plugged-init t))
1552   (let (wl-demo)
1553     (wl-init)) ; returns immediately if already initialized.
1554
1555
1556   (let (buf-name header-alist-internal)
1557     (setq buf-name
1558           (wl-draft-create-buffer parent-folder))
1559
1560     (unless (cdr (assq 'From header-alist))
1561       (setq header-alist
1562             (append (list (cons 'From wl-from)) header-alist)))
1563     (unless (cdr (assq 'To header-alist))
1564       (let ((to))
1565         (when (setq to (and
1566                         (interactive-p)
1567                         ""))
1568           (if (assq 'To header-alist)
1569               (setcdr (assq 'To header-alist) to)
1570             (setq header-alist
1571                   (append header-alist
1572                           (list (cons 'To to))))))))
1573     (unless (cdr (assq 'Subject header-alist))
1574       (if (assq 'Subject header-alist)
1575           (setcdr (assq 'Subject header-alist) "")
1576         (setq header-alist
1577               (append header-alist (list (cons 'Subject ""))))))
1578     (setq header-alist (append header-alist
1579                                (wl-draft-default-headers)
1580                                wl-draft-additional-header-alist
1581                                (if body (list "" (cons 'Body body)))))
1582     (wl-draft-create-contents header-alist)
1583     (if edit-again
1584         (wl-draft-decode-body
1585          content-type content-transfer-encoding))
1586     (wl-draft-insert-mail-header-separator)
1587     (wl-draft-prepare-edit)
1588     (if (interactive-p)
1589         (run-hooks 'wl-mail-setup-hook))
1590     (goto-char (point-min))
1591     (wl-user-agent-compose-internal) ;; user-agent
1592     (cond ((and
1593             (interactive-p)
1594             (string= (cdr (assq 'To header-alist)) ""))
1595            (mail-position-on-field "To"))
1596           (t
1597            (goto-char (point-max))))
1598     buf-name))
1599
1600 (defun wl-draft-create-buffer (&optional parent-folder)
1601   (let* ((draft-folder (wl-folder-get-elmo-folder wl-draft-folder))
1602          (parent-folder (or parent-folder (wl-summary-buffer-folder-name)))
1603          (summary-buf (wl-summary-get-buffer parent-folder))
1604          (reply-or-forward
1605           (or (eq this-command 'wl-summary-reply)
1606               (eq this-command 'wl-summary-forward)
1607               (eq this-command 'wl-summary-target-mark-forward)
1608               (eq this-command 'wl-summary-target-mark-reply-with-citation)))
1609          buf-name file-name num change-major-mode-hook)
1610     (if (not (elmo-folder-message-file-p draft-folder))
1611         (error "%s folder cannot be used for draft folder" wl-draft-folder))
1612     (setq num (elmo-max-of-list
1613                (or (elmo-folder-list-messages draft-folder) '(0))))
1614     (setq num (+ 1 num))
1615     ;; To get unused buffer name.
1616     (while (get-buffer (concat wl-draft-folder "/" (int-to-string num)))
1617       (setq num (+ 1 num)))
1618     (setq buf-name (find-file-noselect
1619                     (setq file-name
1620                           (elmo-message-file-name
1621                            (wl-folder-get-elmo-folder wl-draft-folder)
1622                            num))))
1623     ;; switch-buffer according to draft buffer style.
1624     (if wl-draft-use-frame
1625         (switch-to-buffer-other-frame buf-name)
1626       (if reply-or-forward
1627           (case wl-draft-reply-buffer-style
1628             (split
1629              (split-window-vertically)
1630              (other-window 1)
1631              (switch-to-buffer buf-name))
1632             (keep
1633              (switch-to-buffer buf-name))
1634             (full
1635              (delete-other-windows)
1636              (switch-to-buffer buf-name))
1637             (t
1638              (if (functionp wl-draft-reply-buffer-style)
1639                  (funcall wl-draft-reply-buffer-style buf-name)
1640                (error "Invalid value for wl-draft-reply-buffer-style"))))
1641         (case wl-draft-buffer-style
1642           (split
1643            (when (eq major-mode 'wl-summary-mode)
1644              (wl-summary-toggle-disp-msg 'off))
1645            (split-window-vertically)
1646            (other-window 1)
1647            (switch-to-buffer buf-name))
1648           (keep
1649            (switch-to-buffer buf-name))
1650           (full
1651            (delete-other-windows)
1652            (switch-to-buffer buf-name))
1653           (t (if (functionp wl-draft-buffer-style)
1654                  (funcall wl-draft-buffer-style buf-name)
1655                (error "Invalid value for wl-draft-buffer-style"))))))
1656     (set-buffer buf-name)
1657     (if (not (string-match (regexp-quote wl-draft-folder)
1658                            (buffer-name)))
1659         (rename-buffer (concat wl-draft-folder "/" (int-to-string num))))
1660     (auto-save-mode -1)
1661     (wl-draft-mode)
1662     (make-local-variable 'truncate-partial-width-windows)
1663     (setq truncate-partial-width-windows nil)
1664     (setq truncate-lines wl-draft-truncate-lines)
1665     (setq wl-sent-message-via nil)
1666     (setq wl-sent-message-queued nil)
1667     (setq wl-draft-buffer-file-name file-name)
1668     (setq wl-draft-config-exec-flag t)
1669     (setq wl-draft-parent-folder (or parent-folder ""))
1670     (or (eq this-command 'wl-folder-write-current-folder)
1671         (setq wl-draft-buffer-cur-summary-buffer summary-buf))
1672     buf-name))
1673
1674 (defun wl-draft-create-contents (header-alist)
1675   "header-alist' sample
1676 '(function  ;; funcall
1677   string    ;; insert string
1678   (symbol . string)    ;;  insert symbol-value: string
1679   (symbol . function)  ;;  (funcall) and if it returns string,
1680                        ;;  insert symbol-value: string
1681   (symbol . nil)       ;;  do nothing
1682   nil                  ;;  do nothing
1683   )
1684 "
1685   (unless (eq major-mode 'wl-draft-mode)
1686     (error "wl-draft-create-header must be use in wl-draft-mode."))
1687   (let ((halist header-alist)
1688         field value)
1689     (while halist
1690       (cond
1691        ;; function
1692        ((functionp (car halist)) (funcall (car halist)))
1693        ;; string
1694        ((stringp (car halist)) (insert (car halist) "\n"))
1695        ;; cons
1696        ((consp (car halist))
1697         (setq field (car (car halist)))
1698         (setq value (cdr (car halist)))
1699         (cond
1700          ((symbolp field)
1701           (cond
1702            ((eq field 'Body) ; body
1703             (insert value))
1704            ((stringp value) (insert (symbol-name field) ": " value "\n"))
1705            ((functionp value)
1706             (let ((value-return (funcall value)))
1707               (when (stringp value-return)
1708                 (insert (symbol-name field) ": " value-return "\n"))))
1709            ((not value))
1710            (t
1711             (debug))))
1712          ;;
1713          ((not field))
1714          (t
1715           (debug))
1716          )))
1717       (setq halist (cdr halist)))))
1718
1719 (defun wl-draft-prepare-edit ()
1720   (unless (eq major-mode 'wl-draft-mode)
1721     (error "wl-draft-create-header must be use in wl-draft-mode."))
1722   (let (change-major-mode-hook)
1723     (wl-draft-editor-mode)
1724     (when wl-draft-write-file-function
1725       (add-hook 'local-write-file-hooks wl-draft-write-file-function))
1726     (wl-draft-overload-functions)
1727     (wl-highlight-headers 'for-draft)
1728     (wl-draft-save)
1729     (clear-visited-file-modtime)))
1730
1731 (defun wl-draft-decode-header ()
1732   (save-excursion
1733     (std11-narrow-to-header)
1734     (wl-draft-decode-message-in-buffer)
1735     (widen)))
1736
1737 (defun wl-draft-decode-body (&optional content-type content-transfer-encoding)
1738   (let ((content-type
1739          (or content-type
1740                 (std11-field-body "content-type")))
1741         (content-transfer-encoding
1742          (or content-transfer-encoding
1743              (std11-field-body "content-transfer-encoding")))
1744         delimline)
1745     (save-excursion
1746       (std11-narrow-to-header)
1747       (wl-draft-delete-field "content-type")
1748       (wl-draft-delete-field "content-transfer-encoding")
1749       (goto-char (point-max))
1750       (setq delimline (point-marker))
1751       (widen)
1752       (narrow-to-region delimline (point-max))
1753       (goto-char (point-min))
1754       (when content-type
1755         (insert "Content-type: " content-type "\n"))
1756       (when content-transfer-encoding
1757         (insert "Content-Transfer-Encoding: " content-transfer-encoding "\n"))
1758       (wl-draft-decode-message-in-buffer)
1759       (goto-char (point-min))
1760       (unless (re-search-forward "^$" (point-at-eol) t)
1761         (insert "\n"))
1762       (widen)
1763       delimline)))
1764
1765 ;;; subroutine for wl-draft-create-contents
1766 ;;; must be used in wl-draft-mode
1767 (defun wl-draft-check-new-line ()
1768   (if (not (= (preceding-char) ?\n))
1769       (insert ?\n)))
1770
1771 (defsubst wl-draft-trim-ccs (cc)
1772   (let ((field
1773          (if (functionp cc)
1774              (funcall cc)
1775            cc)))
1776     (if (and field
1777              (null (and wl-draft-delete-myself-from-bcc-fcc
1778                         (elmo-list-member
1779                          (mapcar 'wl-address-header-extract-address
1780                                  (append
1781                                   (wl-parse-addresses (std11-field-body "To"))
1782                                   (wl-parse-addresses (std11-field-body "Cc"))))
1783                          (mapcar 'downcase wl-subscribed-mailing-list)))))
1784         field
1785       nil)))
1786
1787 (defsubst wl-draft-default-headers ()
1788   (list
1789    (cons 'Mail-Reply-To (and wl-insert-mail-reply-to
1790                              (wl-address-header-extract-address
1791                               wl-from)))
1792    (cons 'User-Agent wl-generate-mailer-string-function)
1793    (cons 'Reply-To mail-default-reply-to)
1794    (cons 'Bcc (function
1795                (lambda ()
1796                  (wl-draft-trim-ccs
1797                   (or wl-bcc (and mail-self-blind (user-login-name)))))))
1798    (cons 'Fcc (function
1799                (lambda ()
1800                  (wl-draft-trim-ccs wl-fcc))))
1801    (cons 'Organization wl-organization)
1802    (and wl-auto-insert-x-face
1803         (file-exists-p wl-x-face-file)
1804         'wl-draft-insert-x-face-field-here) ;; allow nil
1805    mail-default-headers
1806    ;; check \n at th end of line for `mail-default-headers'
1807    'wl-draft-check-new-line
1808    ))
1809
1810 (defun wl-draft-insert-mail-header-separator (&optional delimline)
1811   (save-excursion
1812     (if delimline
1813         (goto-char delimline)
1814       (goto-char (point-min))
1815       (if (search-forward "\n\n" nil t)
1816           (delete-backward-char 1)
1817         (goto-char (point-max))))
1818     (wl-draft-check-new-line)
1819     (put-text-property (point)
1820                        (progn
1821                          (insert mail-header-separator "\n")
1822                          (1- (point)))
1823                        'category 'mail-header-separator)
1824     (point)))
1825
1826 ;;;;;;;;;;;;;;;;
1827
1828 (defun wl-draft-elmo-nntp-send ()
1829   (let ((elmo-nntp-post-pre-hook wl-news-send-pre-hook)
1830         (elmo-nntp-default-user
1831          (or wl-nntp-posting-user elmo-nntp-default-user))
1832         (elmo-nntp-default-server
1833          (or wl-nntp-posting-server elmo-nntp-default-server))
1834         (elmo-nntp-default-port
1835          (or wl-nntp-posting-port elmo-nntp-default-port))
1836         (elmo-nntp-default-stream-type
1837          (or wl-nntp-posting-stream-type elmo-nntp-default-stream-type))
1838         (elmo-nntp-default-function wl-nntp-posting-function)
1839         condition)
1840     (if (setq condition (cdr (elmo-string-matched-assoc
1841                               (std11-field-body "Newsgroups")
1842                               wl-nntp-posting-config-alist)))
1843         (if (stringp condition)
1844             (setq elmo-nntp-default-server condition)
1845           (while (car condition)
1846             (set (intern (format "elmo-nntp-default-%s"
1847                                  (symbol-name (caar condition))))
1848                  (cdar condition))
1849             (setq condition (cdr condition)))))
1850     (unless elmo-nntp-default-function
1851       (error "wl-draft-nntp-send: posting-function is nil."))
1852     (if (not (elmo-plugged-p elmo-nntp-default-server elmo-nntp-default-port))
1853         (wl-draft-set-sent-message 'news 'unplugged
1854                                    (cons elmo-nntp-default-server
1855                                          elmo-nntp-default-port))
1856       (funcall elmo-nntp-default-function
1857                elmo-nntp-default-server (current-buffer))
1858       (wl-draft-set-sent-message 'news 'sent)
1859       (wl-draft-write-sendlog 'ok 'nntp elmo-nntp-default-server
1860                               (std11-field-body "Newsgroups")
1861                               (std11-field-body "Message-ID")))))
1862
1863 (defun wl-draft-generate-clone-buffer (name &optional local-variables)
1864   "Generate clone of current buffer named NAME."
1865   (let ((editing-buffer (current-buffer)))
1866     (save-excursion
1867       (set-buffer (generate-new-buffer name))
1868       (erase-buffer)
1869       (wl-draft-mode)
1870       (wl-draft-editor-mode)
1871       (insert-buffer editing-buffer)
1872       (message "")
1873       (while local-variables
1874         (make-local-variable (car local-variables))
1875         (set (car local-variables)
1876              (save-excursion
1877                (set-buffer editing-buffer)
1878                (symbol-value (car local-variables))))
1879         (setq local-variables (cdr local-variables)))
1880       (current-buffer))))
1881
1882 (defun wl-draft-remove-text-plain-tag ()
1883   "Remove text/plain tag of mime-edit."
1884   (if (looking-at "^--\\[\\[text/plain\\]\\]$")
1885       (delete-region (point-at-bol)(1+ (point-at-eol)))))
1886
1887 (defun wl-draft-reedit (number)
1888   (let ((draft-folder (wl-folder-get-elmo-folder wl-draft-folder))
1889         (wl-draft-reedit t)
1890         buffer file-name change-major-mode-hook body-top)
1891     (setq file-name (elmo-message-file-name draft-folder number))
1892     (unless (file-exists-p file-name)
1893       (error "File %s does not exist" file-name))
1894     (if (setq buffer (get-buffer
1895                       (concat wl-draft-folder "/"
1896                               (number-to-string number))))
1897         (progn
1898           (if wl-draft-use-frame
1899               (switch-to-buffer-other-frame buffer)
1900             (switch-to-buffer buffer))
1901           (set-buffer buffer))
1902       (setq buffer (get-buffer-create (number-to-string number)))
1903       ;; switch-buffer according to draft buffer style.
1904       (if wl-draft-use-frame
1905           (switch-to-buffer-other-frame buffer)
1906         (case wl-draft-buffer-style
1907           (split
1908            (split-window-vertically)
1909            (other-window 1)
1910            (switch-to-buffer buffer))
1911           (keep
1912            (switch-to-buffer buffer))
1913           (full
1914            (delete-other-windows)
1915            (switch-to-buffer buffer))
1916           (t (if (functionp wl-draft-buffer-style)
1917                  (funcall wl-draft-buffer-style buffer)
1918                (error "Invalid value for wl-draft-buffer-style")))))
1919       (set-buffer buffer)
1920       (insert-file-contents-as-binary file-name)
1921       (let((mime-edit-again-ignored-field-regexp
1922             "^\\(Content-.*\\|Mime-Version\\):"))
1923         (wl-draft-decode-message-in-buffer))
1924       (setq body-top (wl-draft-insert-mail-header-separator))
1925       (if (not (string-match (regexp-quote wl-draft-folder)
1926                              (buffer-name)))
1927           (rename-buffer (concat wl-draft-folder "/" (buffer-name))))
1928       (auto-save-mode -1)
1929       (wl-draft-mode)
1930       (setq buffer-file-name file-name)
1931       (make-local-variable 'truncate-partial-width-windows)
1932       (setq truncate-partial-width-windows nil)
1933       (setq truncate-lines wl-draft-truncate-lines)
1934       (setq wl-sent-message-via nil)
1935       (setq wl-sent-message-queued nil)
1936       (setq wl-draft-buffer-file-name file-name)
1937       (wl-draft-config-info-operation number 'load)
1938       (goto-char (point-min))
1939       (wl-draft-overload-functions)
1940       (wl-draft-editor-mode)
1941       (when wl-draft-write-file-function
1942         (add-hook 'local-write-file-hooks wl-draft-write-file-function))
1943       (wl-highlight-headers 'for-draft)
1944       (goto-char body-top)
1945       (run-hooks 'wl-draft-reedit-hook)
1946       (goto-char (point-max))
1947       buffer)))
1948
1949 (defmacro wl-draft-body-goto-top ()
1950   (` (progn
1951        (goto-char (point-min))
1952        (if (re-search-forward mail-header-separator nil t)
1953            (forward-char 1)
1954          (goto-char (point-max))))))
1955
1956 (defmacro wl-draft-body-goto-bottom ()
1957   (` (goto-char (point-max))))
1958
1959 (defmacro wl-draft-config-body-goto-header ()
1960   (` (progn
1961        (goto-char (point-min))
1962        (if (re-search-forward mail-header-separator nil t)
1963            (beginning-of-line)
1964          (goto-char (point-max))))))
1965
1966 (defsubst wl-draft-config-sub-eval-insert (content &optional newline)
1967   (let (content-value)
1968     (when (and content
1969                (stringp (setq content-value (eval content))))
1970       (insert content-value)
1971       (if newline (insert "\n")))))
1972
1973 (defun wl-draft-config-sub-body (content)
1974   (wl-draft-body-goto-top)
1975   (delete-region (point) (point-max))
1976   (wl-draft-config-sub-eval-insert content))
1977
1978 (defun wl-draft-config-sub-top (content)
1979   (wl-draft-body-goto-top)
1980   (wl-draft-config-sub-eval-insert content))
1981
1982 (defun wl-draft-config-sub-bottom (content)
1983   (wl-draft-body-goto-bottom)
1984   (wl-draft-config-sub-eval-insert content))
1985
1986 (defun wl-draft-config-sub-header (content)
1987   (wl-draft-config-body-goto-header)
1988   (wl-draft-config-sub-eval-insert content 'newline))
1989
1990 (defun wl-draft-config-sub-header-top (content)
1991   (goto-char (point-min))
1992   (wl-draft-config-sub-eval-insert content 'newline))
1993
1994 (defun wl-draft-config-sub-part-top (content)
1995   (goto-char (mime-edit-content-beginning))
1996   (wl-draft-config-sub-eval-insert content 'newline))
1997
1998 (defun wl-draft-config-sub-part-bottom (content)
1999   (goto-char (mime-edit-content-end))
2000   (wl-draft-config-sub-eval-insert content 'newline))
2001
2002 (defsubst wl-draft-config-sub-file (content)
2003   (let ((coding-system-for-read wl-cs-autoconv)
2004         (file (expand-file-name (eval content))))
2005     (if (file-exists-p file)
2006         (insert-file-contents file)
2007       (error "%s: no exists file" file))))
2008
2009 (defun wl-draft-config-sub-body-file (content)
2010   (wl-draft-body-goto-top)
2011   (delete-region (point) (point-max))
2012   (wl-draft-config-sub-file content))
2013
2014 (defun wl-draft-config-sub-top-file (content)
2015   (wl-draft-body-goto-top)
2016   (wl-draft-config-sub-file content))
2017
2018 (defun wl-draft-config-sub-bottom-file (content)
2019   (wl-draft-body-goto-bottom)
2020   (wl-draft-config-sub-file content))
2021
2022 (defun wl-draft-config-sub-header-file (content)
2023   (wl-draft-config-body-goto-header)
2024   (wl-draft-config-sub-file content))
2025
2026 (defun wl-draft-config-sub-template (content)
2027   (setq wl-draft-config-variables
2028         (wl-template-insert (eval content))))
2029
2030 (defun wl-draft-config-sub-x-face (content)
2031   (if (and (string-match "\\.xbm\\(\\.gz\\)?$" content)
2032            (fboundp 'x-face-insert)) ; x-face.el is installed.
2033       (x-face-insert content)
2034     (wl-draft-replace-field "X-Face" (elmo-get-file-string content t) t)))
2035
2036 (defsubst wl-draft-config-sub-func (field content)
2037   (let (func)
2038     (if (setq func (assq field wl-draft-config-sub-func-alist))
2039         (let (wl-draft-config-variables)
2040           (funcall (cdr func) content)
2041           ;; for wl-draft-config-sub-template
2042           (cons t wl-draft-config-variables)))))
2043
2044 (defsubst wl-draft-config-exec-sub (clist)
2045   (let (config local-variables)
2046     (while clist
2047       (setq config (car clist))
2048       (cond
2049        ((functionp config)
2050         (funcall config))
2051        ((consp config)
2052         (let ((field (car config))
2053               (content (cdr config))
2054               ret-val)
2055           (cond
2056            ((stringp field)
2057             (wl-draft-replace-field field (eval content) t))
2058            ((setq ret-val (wl-draft-config-sub-func field content))
2059             (if (cdr ret-val) ;; for wl-draft-config-sub-template
2060                 (wl-append local-variables (cdr ret-val))))
2061            ((boundp field) ;; variable
2062             (make-local-variable field)
2063             (set field (eval content))
2064             (wl-append local-variables (list field)))
2065            (t
2066             (error "%s: not variable" field)))))
2067        (t
2068         (error "%s: not supported type" config)))
2069       (setq clist (cdr clist)))
2070     local-variables))
2071
2072 (defun wl-draft-prepared-config-exec (&optional config-alist reply-buf)
2073   "Change headers in draft preparation time."
2074   (interactive)
2075   (unless wl-draft-reedit
2076     (let ((config-alist
2077            (or config-alist
2078                (and (boundp 'wl-draft-prepared-config-alist)
2079                     wl-draft-prepared-config-alist)     ;; For compatible.
2080                wl-draft-config-alist)))
2081       (if config-alist
2082           (wl-draft-config-exec config-alist reply-buf)))))
2083
2084 (defun wl-draft-config-exec (&optional config-alist reply-buf)
2085   "Change headers according to the value of `wl-draft-config-alist'.
2086 Automatically applied in draft sending time."
2087   (interactive)
2088   (let ((case-fold-search t)
2089         (alist (or config-alist wl-draft-config-alist))
2090         (reply-buf (or reply-buf (and (buffer-live-p wl-draft-reply-buffer)
2091                                       wl-draft-reply-buffer)))
2092         (local-variables wl-draft-config-variables)
2093         key clist found)
2094     (when (and (or (interactive-p)
2095                    wl-draft-config-exec-flag)
2096                alist)
2097       (save-excursion
2098         (catch 'done
2099           (while alist
2100             (setq key (caar alist)
2101                   clist (cdar alist))
2102             (cond
2103              ((eq key 'reply)
2104               (when (and
2105                      reply-buf
2106                      (save-excursion
2107                        (set-buffer reply-buf)
2108                        (save-restriction
2109                          (std11-narrow-to-header)
2110                          (goto-char (point-min))
2111                          (re-search-forward (car clist) nil t))))
2112                 (wl-draft-config-exec-sub (cdr clist))
2113                 (setq found t)))
2114              ((stringp key)
2115               (when (save-restriction
2116                       (std11-narrow-to-header mail-header-separator)
2117                       (goto-char (point-min))
2118                       (re-search-forward key nil t))
2119                 (wl-append local-variables
2120                            (wl-draft-config-exec-sub clist))
2121                 (setq found t)))
2122              ((eval key)
2123               (wl-append local-variables
2124                          (wl-draft-config-exec-sub clist))
2125               (setq found t)))
2126             (if (and found wl-draft-config-matchone)
2127                 (throw 'done t))
2128             (setq alist (cdr alist))))
2129         (if found
2130             (setq wl-draft-config-exec-flag nil))
2131         (run-hooks 'wl-draft-config-exec-hook)
2132         (put-text-property (point-min)(point-max) 'face nil)
2133         (wl-highlight-message (point-min)(point-max) t)
2134         (setq wl-draft-config-variables
2135               (elmo-uniq-list local-variables))))))
2136
2137 (defun wl-draft-replace-field (field content &optional add)
2138   (save-excursion
2139     (save-restriction
2140       (let ((case-fold-search t)
2141             (inhibit-read-only t) ;; added by teranisi.
2142             beg)
2143         (std11-narrow-to-header mail-header-separator)
2144         (goto-char (point-min))
2145         (if (re-search-forward (concat "^" (regexp-quote field) ":") nil t)
2146             (if content
2147                 ;; replace field
2148                 (progn
2149                   (setq beg (point))
2150                   (re-search-forward "^[^ \t]" nil 'move)
2151                   (beginning-of-line)
2152                   (skip-chars-backward "\n")
2153                   (delete-region beg (point))
2154                   (insert " " content))
2155               ;; delete field
2156               (save-excursion
2157                 (beginning-of-line)
2158                 (setq beg (point)))
2159               (re-search-forward "^[^ \t]" nil 'move)
2160               (beginning-of-line)
2161               (delete-region beg (point)))
2162           (when (and add content)
2163             ;; add field
2164             (goto-char (point-max))
2165             (insert (concat field ": " content "\n"))))))))
2166
2167 (defun wl-draft-config-info-operation (msg operation)
2168   (let* ((msgdb-dir (elmo-folder-msgdb-path (wl-folder-get-elmo-folder
2169                                              wl-draft-folder)))
2170          (filename
2171           (expand-file-name
2172            (format "%s-%d" wl-draft-config-save-filename msg)
2173            msgdb-dir))
2174          element alist variable)
2175     (cond
2176      ((eq operation 'save)
2177       (let ((variables (elmo-uniq-list wl-draft-config-variables)))
2178         (while (setq variable (pop variables))
2179           (when (boundp variable)
2180             (wl-append alist
2181                        (list (cons variable (eval variable))))))
2182         (elmo-object-save filename alist)))
2183      ((eq operation 'load)
2184       (setq alist (elmo-object-load filename))
2185       (while (setq element (pop alist))
2186         (set (make-local-variable (car element)) (cdr element))
2187         (wl-append wl-draft-config-variables (list (car element)))))
2188      ((eq operation 'delete)
2189       (if (file-exists-p filename)
2190           (delete-file filename))))))
2191
2192 (defun wl-draft-queue-info-operation (msg operation
2193                                           &optional add-sent-message-via)
2194   (let* ((msgdb-dir (elmo-folder-msgdb-path
2195                      (wl-folder-get-elmo-folder wl-queue-folder)))
2196          (filename
2197           (expand-file-name
2198            (format "%s-%d" wl-draft-queue-save-filename msg)
2199            msgdb-dir))
2200          element alist variable)
2201     (cond
2202      ((eq operation 'save)
2203       (let ((variables (elmo-uniq-list
2204                         (append wl-draft-queue-save-variables
2205                                 wl-draft-config-variables
2206                                 (list 'wl-draft-fcc-list)))))
2207         (if add-sent-message-via
2208             (progn
2209               (push 'wl-sent-message-queued variables)
2210               (push 'wl-sent-message-via variables)))
2211         (while (setq variable (pop variables))
2212           (when (boundp variable)
2213             (wl-append alist
2214                        (list (cons variable (eval variable))))))
2215         (elmo-object-save filename alist)))
2216      ((eq operation 'load)
2217       (setq alist (elmo-object-load filename))
2218       (while (setq element (pop alist))
2219         (set (make-local-variable (car element)) (cdr element))))
2220      ((eq operation 'get-sent-via)
2221       (setq alist (elmo-object-load filename))
2222       (cdr (assq 'wl-sent-message-via alist)))
2223      ((eq operation 'delete)
2224       (if (file-exists-p filename)
2225           (delete-file filename))))))
2226
2227 (defun wl-draft-queue-append (wl-sent-message-via)
2228   (if wl-draft-verbose-send
2229       (message "Queuing..."))
2230   (let ((send-buffer (current-buffer))
2231         (folder (wl-folder-get-elmo-folder wl-queue-folder))
2232         (message-id (std11-field-body "Message-ID")))
2233     (if (elmo-folder-append-buffer folder t)
2234         (progn
2235           (wl-draft-queue-info-operation
2236            (car (elmo-folder-status folder))
2237            'save wl-sent-message-via)
2238           (wl-draft-write-sendlog 'ok 'queue nil wl-queue-folder message-id)
2239           (when wl-draft-verbose-send
2240             (setq wl-draft-verbose-msg "Queuing...")
2241             (message "Queuing...done")))
2242       (wl-draft-write-sendlog 'failed 'queue nil wl-queue-folder message-id)
2243       (error "Queuing failed"))))
2244
2245 (defun wl-draft-queue-flush ()
2246   "Flush draft queue."
2247   (interactive)
2248   (let* ((queue-folder (wl-folder-get-elmo-folder wl-queue-folder))
2249          (msgs2 (progn
2250                   (elmo-folder-open-internal queue-folder)
2251                   (elmo-folder-list-messages queue-folder)))
2252          (i 0)
2253          (performed 0)
2254          (wl-draft-queue-flushing t)
2255          msgs failure len buffer msgid sent-via)
2256     ;; get plugged send message
2257     (while msgs2
2258       (setq sent-via (wl-draft-queue-info-operation (car msgs2) 'get-sent-via))
2259       (catch 'found
2260         (while sent-via
2261           (when (and (eq (nth 1 (car sent-via)) 'unplugged)
2262                      (or (not (nth 2 (car sent-via)))
2263                          (elmo-plugged-p
2264                           (car (nth 2 (car sent-via)))
2265                           (cdr (nth 2 (car sent-via))))))
2266             (wl-append msgs (list (car msgs2)))
2267             (throw 'found t))
2268           (setq sent-via (cdr sent-via))))
2269       (setq msgs2 (cdr msgs2)))
2270     (when (> (setq len (length msgs)) 0)
2271       (if (elmo-y-or-n-p (format
2272                           "%d message(s) are in the sending queue.  Send now? "
2273                           len)
2274                          (not elmo-dop-flush-confirm) t)
2275           (progn
2276             (save-excursion
2277               (setq buffer (get-buffer-create " *wl-draft-queue-flush*"))
2278               (set-buffer buffer)
2279               (while msgs
2280                 ;; reset buffer local variables
2281                 (kill-all-local-variables)
2282                 (erase-buffer)
2283                 (setq i (+ 1 i)
2284                       failure nil)
2285                 (setq wl-sent-message-via nil)
2286                 (wl-draft-queue-info-operation (car msgs) 'load)
2287                 (elmo-message-fetch queue-folder
2288                                     (car msgs)
2289                                     (elmo-make-fetch-strategy 'entire)
2290                                     nil (current-buffer))
2291                 (condition-case err
2292                     (setq failure (funcall
2293                                    wl-draft-queue-flush-send-function
2294                                    (format "Sending (%d/%d)..." i len)))
2295 ;;;               (wl-draft-raw-send nil nil
2296 ;;;                                  (format "Sending (%d/%d)..." i len))
2297                   (error
2298                    (elmo-display-error err t)
2299                    (setq failure t))
2300                   (quit
2301                    (setq failure t)))
2302                 (if (eq wl-sent-message-modified 'requeue)
2303                     (progn
2304                       (elmo-folder-delete-messages
2305                        queue-folder (cons (car msgs) nil))
2306                       (wl-draft-queue-info-operation (car msgs) 'delete))
2307                   (unless failure
2308                     (elmo-folder-delete-messages
2309                      queue-folder (cons (car msgs) nil))
2310                     (wl-draft-queue-info-operation (car msgs) 'delete)
2311                     (setq performed (+ 1 performed))))
2312                 (setq msgs (cdr msgs)))
2313               (kill-buffer buffer)
2314               (message "%d message(s) are sent." performed)))
2315         (message "%d message(s) are remained to be sent." len))
2316       (elmo-folder-close queue-folder)
2317       len)))
2318
2319 (defun wl-jump-to-draft-buffer (&optional arg)
2320   "Jump to the draft if exists."
2321   (interactive "P")
2322   (if arg
2323       (wl-jump-to-draft-folder)
2324     (let ((draft-bufs (wl-collect-draft))
2325           buf)
2326       (cond
2327        ((null draft-bufs)
2328         (message "No draft buffer exist."))
2329        (t
2330         (setq draft-bufs
2331               (sort (mapcar 'buffer-name draft-bufs)
2332                     (function (lambda (a b)
2333                                 (not (string< a b))))))
2334         (if (setq buf (cdr (member (buffer-name)
2335                                    draft-bufs)))
2336             (setq buf (car buf))
2337           (setq buf (car draft-bufs)))
2338         (switch-to-buffer buf))))))
2339
2340 (defun wl-jump-to-draft-folder ()
2341   (let ((msgs (reverse (elmo-folder-list-messages (wl-folder-get-elmo-folder
2342                                                    wl-draft-folder))))
2343         (mybuf (buffer-name))
2344         msg buf)
2345     (if (not msgs)
2346         (message "No draft message exist.")
2347       (if (string-match (concat "^" wl-draft-folder "/") mybuf)
2348           (setq msg (cadr (memq
2349                            (string-to-int (substring mybuf (match-end 0)))
2350                            msgs))))
2351       (or msg (setq msg (car msgs)))
2352       (if (setq buf (get-buffer (format "%s/%d" wl-draft-folder msg)))
2353           (switch-to-buffer buf)
2354         (wl-draft-reedit msg)))))
2355
2356 (defun wl-draft-highlight-and-recenter (&optional n)
2357   (interactive "P")
2358   (when wl-highlight-body-too
2359     (let ((modified (buffer-modified-p)))
2360       (unwind-protect
2361           (progn
2362             (put-text-property (point-min) (point-max) 'face nil)
2363             (wl-highlight-message (point-min) (point-max) t))
2364         (set-buffer-modified-p modified))))
2365   (recenter n))
2366
2367 ;;;; user-agent support by Sen Nagata
2368
2369 ;; this appears to be necessarily global...
2370 (defvar wl-user-agent-compose-p nil)
2371 (defvar wl-user-agent-headers-and-body-alist nil)
2372
2373 ;; this should be a generic function for mail-mode -- i wish there was
2374 ;; something like it in sendmail.el
2375 (defun wl-user-agent-insert-header (header-name header-value)
2376   "Insert HEADER-NAME w/ value HEADER-VALUE into a message."
2377   ;; it seems like overriding existing headers is acceptable -- should
2378   ;; we provide an option?
2379
2380   ;; plan was: unfold header (might be folded), remove existing value, insert
2381   ;;           new value
2382   ;; wl doesn't seem to fold header lines yet anyway :-)
2383
2384   (let ((kill-whole-line t)
2385         end-of-line)
2386     (mail-position-on-field (capitalize header-name))
2387     (setq end-of-line (point))
2388     (beginning-of-line)
2389     (re-search-forward ":" end-of-line)
2390     (insert (concat " " header-value "\n"))
2391     (kill-line)))
2392
2393 ;; this should be a generic function for mail-mode -- i wish there was
2394 ;; something like it in sendmail.el
2395 ;;
2396 ;; ** haven't dealt w/ case where the body is already set **
2397 (defun wl-user-agent-insert-body (body-text)
2398   "Insert a body of text, BODY-TEXT, into a message."
2399   ;; code defensively... :-P
2400   (goto-char (point-min))
2401   (search-forward mail-header-separator)
2402   (forward-line 1)
2403   (insert body-text))
2404
2405 ;;;###autoload
2406 (defun wl-user-agent-compose (&optional to subject other-headers continue
2407                                         switch-function yank-action
2408                                         send-actions)
2409   "Support the `compose-mail' interface for wl.
2410 Only support for TO, SUBJECT, and OTHER-HEADERS has been implemented.
2411 Support for CONTINUE, YANK-ACTION, and SEND-ACTIONS has not
2412 been implemented yet.  Partial support for SWITCH-FUNCTION now supported."
2413
2414   (unless (featurep 'wl)
2415     (require 'wl))
2416   (or switch-function
2417       (setq switch-function 'keep))
2418   ;; protect these -- to and subject get bound at some point, so it looks
2419   ;; to be necessary to protect the values used w/in
2420   (let ((wl-user-agent-headers-and-body-alist other-headers)
2421         (wl-draft-use-frame (eq switch-function 'switch-to-buffer-other-frame))
2422         (wl-draft-buffer-style switch-function))
2423     (if to
2424         (if (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
2425                                    'ignore-case)
2426             (setcdr
2427              (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
2428                                     'ignore-case)
2429              to)
2430           (setq wl-user-agent-headers-and-body-alist
2431                 (cons (cons "to" to)
2432                       wl-user-agent-headers-and-body-alist))))
2433     (if subject
2434         (if (wl-string-match-assoc "subject"
2435                                    wl-user-agent-headers-and-body-alist
2436                                    'ignore-case)
2437             (setcdr
2438              (wl-string-match-assoc "subject"
2439                                     wl-user-agent-headers-and-body-alist
2440                                     'ignore-case)
2441              subject)
2442           (setq wl-user-agent-headers-and-body-alist
2443                 (cons (cons "subject" subject)
2444                       wl-user-agent-headers-and-body-alist))))
2445     ;; i think this is what we want to use...
2446     (unwind-protect
2447         (progn
2448           ;; tell the hook-function to do its stuff
2449           (setq wl-user-agent-compose-p t)
2450           ;; because to get the hooks working, wl-draft has to think it has
2451           ;; been called interactively
2452           (call-interactively 'wl-draft))
2453       (setq wl-user-agent-compose-p nil))))
2454
2455 (defun wl-user-agent-compose-internal ()
2456   "Manipulate headers and/or a body of a draft message."
2457   ;; being called from wl-user-agent-compose?
2458   (if wl-user-agent-compose-p
2459       (progn
2460         ;; insert headers
2461         (let ((headers wl-user-agent-headers-and-body-alist)
2462               (case-fold-search t))
2463           (while headers
2464             ;; skip body
2465             (if (not (string-match "^body$" (car (car headers))))
2466                 (wl-user-agent-insert-header
2467                  (car (car headers)) (cdr (car headers)))
2468               t)
2469             (setq headers (cdr headers))))
2470         ;; highlight headers (from wl-draft in wl-draft.el)
2471         (wl-highlight-headers 'for-draft)
2472         ;; insert body
2473         (if (wl-string-match-assoc "body" wl-user-agent-headers-and-body-alist
2474                                    'ignore-case)
2475             (wl-user-agent-insert-body
2476              (cdr (wl-string-match-assoc
2477                    "body"
2478                    wl-user-agent-headers-and-body-alist 'ignore-case)))))
2479     t))
2480
2481 (require 'product)
2482 (product-provide (provide 'wl-draft) (require 'wl-version))
2483
2484 ;;; wl-draft.el ends here