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