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