* wl-draft.el (wl-draft-send-mail-with-smtp): run-hook
[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 mechnism server)
105   (format "SMTP:%s/%s@%s"
106           user mechnism 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   (interactive)
1220   (save-buffer)
1221   (wl-draft-config-info-operation
1222    (and (string-match "[0-9]+$" wl-draft-buffer-file-name)
1223         (string-to-int
1224          (match-string 0 wl-draft-buffer-file-name)))
1225    'save))
1226
1227 (defun wl-draft-mimic-kill-buffer ()
1228   "Kill the current (draft) buffer with query."
1229   (interactive)
1230   (let ((bufname (read-buffer (format "Kill buffer: (default %s) "
1231                                       (buffer-name))))
1232         wl-draft-use-frame)
1233     (if (or (not bufname)
1234             (string-equal bufname "")
1235             (string-equal bufname (buffer-name)))
1236         (wl-draft-save-and-exit)
1237       (kill-buffer bufname))))
1238
1239 (defun wl-draft-save-and-exit ()
1240   "Save current draft and exit current draft mode."
1241   (interactive)
1242   (wl-draft-save)
1243   (let ((editing-buffer (current-buffer)))
1244     (wl-draft-hide editing-buffer)
1245     (kill-buffer editing-buffer)))
1246
1247 (defun wl-draft-send-and-exit ()
1248   "Send current draft message and kill it."
1249   (interactive)
1250   (wl-draft-send t))
1251
1252 (defun wl-draft-send-from-toolbar ()
1253   (interactive)
1254   (let ((wl-interactive-send t))
1255     (wl-draft-send-and-exit)))
1256
1257 (defun wl-draft-delete-field (field &optional delimline)
1258   (wl-draft-delete-fields (regexp-quote field) delimline))
1259
1260 (defun wl-draft-delete-fields (regexp &optional delimline)
1261   (save-restriction
1262     (unless delimline
1263       (if (search-forward "\n\n" nil t)
1264           (setq delimline (point))
1265         (setq delimline (point-max))))
1266     (narrow-to-region (point-min) delimline)
1267     (goto-char (point-min))
1268     (let ((regexp (concat "^" regexp ":"))
1269           (case-fold-search t)
1270           last)
1271       (while (not (eobp))
1272         (if (looking-at regexp)
1273             (progn
1274               (delete-region
1275                (point)
1276                (progn
1277                  (forward-line 1)
1278                  (if (re-search-forward "^[^ \t]" nil t)
1279                      (goto-char (match-beginning 0))
1280                    (point-max)))))
1281           (forward-line 1)
1282           (if (re-search-forward "^[^ \t]" nil t)
1283               (goto-char (match-beginning 0))
1284             (point-max)))))))
1285
1286 (defun wl-draft-get-fcc-list (header-end)
1287   (let (fcc-list
1288         (case-fold-search t))
1289     (or (markerp header-end) (error "HEADER-END must be a marker"))
1290     (save-excursion
1291       (goto-char (point-min))
1292       (while (re-search-forward "^Fcc:[ \t]*" header-end t)
1293         (setq fcc-list
1294               (cons (buffer-substring-no-properties
1295                      (point)
1296                      (progn
1297                        (end-of-line)
1298                        (skip-chars-backward " \t")
1299                        (point)))
1300                     fcc-list))
1301         (save-match-data
1302           (wl-folder-confirm-existence
1303            (wl-folder-get-elmo-folder (eword-decode-string (car fcc-list)))))
1304         (delete-region (match-beginning 0)
1305                        (progn (forward-line 1) (point)))))
1306     fcc-list))
1307
1308 (defun wl-draft-do-fcc (header-end &optional fcc-list)
1309   (let ((send-mail-buffer (current-buffer))
1310         (tembuf (generate-new-buffer " fcc output"))
1311         (case-fold-search t)
1312         beg end)
1313     (or (markerp header-end) (error "HEADER-END must be a marker"))
1314     (save-excursion
1315       (unless fcc-list
1316         (setq fcc-list (wl-draft-get-fcc-list header-end)))
1317       (set-buffer tembuf)
1318       (erase-buffer)
1319       ;; insert just the headers to avoid moving the gap more than
1320       ;; necessary (the message body could be arbitrarily huge.)
1321       (insert-buffer-substring send-mail-buffer 1 header-end)
1322       (wl-draft-insert-required-fields t)
1323       (goto-char (point-max))
1324       (insert-buffer-substring send-mail-buffer header-end)
1325       (let ((id (std11-field-body "Message-ID"))
1326             (elmo-enable-disconnected-operation t)
1327             cache-saved)
1328         (while fcc-list
1329           (unless (or cache-saved
1330                       (elmo-folder-plugged-p
1331                        (wl-folder-get-elmo-folder (car fcc-list))))
1332             (elmo-file-cache-save id nil) ;; for disconnected operation
1333             (setq cache-saved t))
1334           (if (elmo-folder-append-buffer
1335                (wl-folder-get-elmo-folder
1336                 (eword-decode-string (car fcc-list)))
1337                (not wl-fcc-force-as-read))
1338               (wl-draft-write-sendlog 'ok 'fcc nil (car fcc-list) id)
1339             (wl-draft-write-sendlog 'failed 'fcc nil (car fcc-list) id))
1340           (setq fcc-list (cdr fcc-list)))))
1341     (kill-buffer tembuf)))
1342
1343 (defun wl-draft-on-field-p ()
1344   (if (< (point)
1345          (save-excursion
1346            (goto-char (point-min))
1347            (search-forward (concat "\n" mail-header-separator "\n") nil 0)
1348            (point)))
1349       (if (bolp)
1350           (if (bobp)
1351               t
1352             (save-excursion
1353               (forward-line -1)
1354               (if (or (looking-at ".*,[ \t]?$")
1355                       (looking-at "^[^ \t]+:[ \t]+.*:$")); group list name
1356                   nil t)))
1357         (let ((pos (point)))
1358           (save-excursion
1359             (beginning-of-line)
1360             (if (looking-at "^[ \t]")
1361                 nil
1362               (if (re-search-forward ":" pos t) nil t)))))))
1363
1364 (defun wl-draft-random-alphabet ()
1365   (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)))
1366     (nth (abs (% (random) 26)) alphabet)))
1367
1368 ;;;###autoload
1369 (defun wl-draft (&optional to subject in-reply-to cc references newsgroups
1370                            mail-followup-to
1371                            content-type content-transfer-encoding
1372                            body edit-again summary-buf from parent-folder)
1373   "Write and send mail/news message with Wanderlust."
1374   (interactive)
1375   (require 'wl)
1376   (unless wl-init
1377     (wl-load-profile)
1378     (wl-folder-init)
1379     (elmo-init)
1380     (wl-plugged-init t))
1381   (wl-init) ; returns immediately if already initialized.
1382   (if (interactive-p)
1383       (setq summary-buf (wl-summary-get-buffer (wl-summary-buffer-folder-name))))
1384   (let ((draft-folder (wl-folder-get-elmo-folder wl-draft-folder))
1385         buf-name file-name num wl-demo change-major-mode-hook)
1386     (if (not (elmo-folder-message-file-p draft-folder))
1387         (error "%s folder cannot be used for draft folder" wl-draft-folder))
1388     (setq num (elmo-max-of-list
1389                (or (elmo-folder-list-messages draft-folder) '(0))))
1390     (setq num (+ 1 num))
1391     ;; To get unused buffer name.
1392     (while (get-buffer (concat wl-draft-folder "/" (int-to-string num)))
1393       (setq num (+ 1 num)))
1394     (setq buf-name (find-file-noselect
1395                     (setq file-name
1396                           (elmo-message-file-name
1397                            (wl-folder-get-elmo-folder wl-draft-folder)
1398                            num))))
1399     (if wl-draft-use-frame
1400         (switch-to-buffer-other-frame buf-name)
1401       (switch-to-buffer buf-name))
1402     (set-buffer buf-name)
1403     (if (not (string-match (regexp-quote wl-draft-folder)
1404                            (buffer-name)))
1405         (rename-buffer (concat wl-draft-folder "/" (int-to-string num))))
1406     (if (or (eq wl-draft-reply-buffer-style 'full)
1407             (eq this-command 'wl-draft)
1408             (eq this-command 'wl-summary-write)
1409             (eq this-command 'wl-summary-write-current-folder))
1410         (delete-other-windows))
1411     (auto-save-mode -1)
1412     (wl-draft-mode)
1413     (make-local-variable 'truncate-partial-width-windows)
1414     (setq truncate-partial-width-windows nil)
1415     (setq truncate-lines wl-draft-truncate-lines)
1416     (setq wl-sent-message-via nil)
1417     (setq wl-sent-message-queued nil)
1418     (setq wl-draft-parent-folder parent-folder)
1419     (if (stringp (or from wl-from))
1420         (insert "From: " (or from wl-from) "\n"))
1421     (and (or (interactive-p)
1422              (eq this-command 'wl-summary-write)
1423              to)
1424          (insert "To: " (or to "") "\n"))
1425     (and cc (insert "Cc: " (or cc "") "\n"))
1426     (insert "Subject: " (or subject "") "\n")
1427     (and newsgroups (insert "Newsgroups: " newsgroups "\n"))
1428     (and mail-followup-to (insert "Mail-Followup-To: " mail-followup-to "\n"))
1429     (and wl-insert-mail-reply-to
1430          (insert "Mail-Reply-To: "
1431                  (wl-address-header-extract-address
1432                   wl-from) "\n"))
1433     (and in-reply-to (insert "In-Reply-To: " in-reply-to "\n"))
1434     (and references (insert "References: " references "\n"))
1435     (insert (funcall wl-generate-mailer-string-function) "\n")
1436     (setq wl-draft-buffer-file-name file-name)
1437     (if mail-default-reply-to
1438         (insert "Reply-To: " mail-default-reply-to "\n"))
1439     (wl-draft-insert-ccs "Bcc: " (or wl-bcc
1440                                (and mail-self-blind (user-login-name))))
1441     (wl-draft-insert-ccs "Fcc: " wl-fcc)
1442     (if wl-organization
1443         (insert "Organization: " wl-organization "\n"))
1444     (and wl-auto-insert-x-face
1445          (file-exists-p wl-x-face-file)
1446          (wl-draft-insert-x-face-field-here))
1447     (if mail-default-headers
1448         (insert mail-default-headers))
1449     (if (not (= (preceding-char) ?\n))
1450         (insert ?\n))
1451     (if edit-again
1452         (let (start)
1453           (setq start (point))
1454           (when content-type
1455             (insert "Content-type: " content-type "\n"))
1456           (when content-transfer-encoding
1457             (insert "Content-Transfer-Encoding: " content-transfer-encoding "\n"))
1458           (if (or content-type content-transfer-encoding)
1459               (insert "\n"))
1460           (and body (insert body))
1461           (save-restriction
1462             (narrow-to-region start (point))
1463             (and edit-again
1464                  (wl-draft-decode-message-in-buffer))
1465             (widen)
1466             (goto-char start)
1467             (put-text-property (point)
1468                                (progn
1469                                  (insert mail-header-separator "\n")
1470                                  (1- (point)))
1471                                'category 'mail-header-separator)))
1472       (put-text-property (point)
1473                          (progn
1474                            (insert mail-header-separator "\n")
1475                            (1- (point)))
1476                          'category 'mail-header-separator)
1477       (and body (insert body)))
1478     (as-binary-output-file
1479      (write-region (point-min)(point-max) wl-draft-buffer-file-name
1480                    nil t))
1481     (wl-draft-editor-mode)
1482     (wl-draft-overload-functions)
1483     (wl-highlight-headers 'for-draft)
1484     (goto-char (point-min))
1485     (setq wl-draft-config-exec-flag t)
1486     (if (interactive-p)
1487         (run-hooks 'wl-mail-setup-hook))
1488     (wl-user-agent-compose-internal) ;; user-agent
1489     (cond ((eq this-command 'wl-summary-write-current-newsgroup)
1490            (mail-position-on-field "Subject"))
1491           ((and (interactive-p) (null to))
1492            (mail-position-on-field "To"))
1493           (t
1494            (goto-char (point-max))))
1495     (setq wl-draft-buffer-cur-summary-buffer (or summary-buf
1496                                                  (get-buffer
1497                                                   wl-summary-buffer-name)))
1498     buf-name))
1499
1500 (defsubst wl-draft-insert-ccs (str cc)
1501   (let ((field
1502          (if (functionp cc)
1503              (funcall cc)
1504            cc)))
1505     (if (and field
1506              (null (and wl-draft-delete-myself-from-bcc-fcc
1507                         (elmo-list-member
1508                          (mapcar 'wl-address-header-extract-address
1509                                  (append
1510                                   (wl-parse-addresses (std11-field-body "To"))
1511                                   (wl-parse-addresses (std11-field-body "Cc"))))
1512                          (mapcar 'downcase wl-subscribed-mailing-list)))))
1513         (insert str field "\n"))))
1514
1515 (defun wl-draft-elmo-nntp-send ()
1516   (let ((elmo-nntp-post-pre-hook wl-news-send-pre-hook)
1517         (elmo-nntp-default-user
1518          (or wl-nntp-posting-user elmo-nntp-default-user))
1519         (elmo-nntp-default-server
1520          (or wl-nntp-posting-server elmo-nntp-default-server))
1521         (elmo-nntp-default-port
1522          (or wl-nntp-posting-port elmo-nntp-default-port))
1523         (elmo-nntp-default-stream-type
1524          (or wl-nntp-posting-stream-type elmo-nntp-default-stream-type)))
1525     (if (not (elmo-plugged-p elmo-nntp-default-server elmo-nntp-default-port))
1526         (wl-draft-set-sent-message 'news 'unplugged
1527                                    (cons elmo-nntp-default-server
1528                                          elmo-nntp-default-port))
1529       (elmo-nntp-post elmo-nntp-default-server (current-buffer))
1530       (wl-draft-set-sent-message 'news 'sent)
1531       (wl-draft-write-sendlog 'ok 'nntp elmo-nntp-default-server
1532                               (std11-field-body "Newsgroups")
1533                               (std11-field-body "Message-ID")))))
1534
1535 (defun wl-draft-generate-clone-buffer (name &optional local-variables)
1536   "Generate clone of current buffer named NAME."
1537   (let ((editing-buffer (current-buffer)))
1538     (save-excursion
1539       (set-buffer (generate-new-buffer name))
1540       (erase-buffer)
1541       (wl-draft-mode)
1542       (wl-draft-editor-mode)
1543       (insert-buffer editing-buffer)
1544       (message "")
1545       (while local-variables
1546         (make-local-variable (car local-variables))
1547         (set (car local-variables)
1548              (save-excursion
1549                (set-buffer editing-buffer)
1550                (symbol-value (car local-variables))))
1551         (setq local-variables (cdr local-variables)))
1552       (current-buffer))))
1553
1554 (defun wl-draft-reedit (number)
1555   (let ((draft-folder (wl-folder-get-elmo-folder wl-draft-folder))
1556         (wl-draft-reedit t)
1557         buf-name file-name change-major-mode-hook)
1558     (setq file-name (elmo-message-file-name draft-folder number))
1559     (unless (file-exists-p file-name)
1560       (error "File %s does not exist" file-name))
1561     (setq buf-name (find-file-noselect file-name))
1562     (if wl-draft-use-frame
1563         (switch-to-buffer-other-frame buf-name)
1564       (switch-to-buffer buf-name))
1565     (set-buffer buf-name)
1566     (if (not (string-match (regexp-quote wl-draft-folder)
1567                            (buffer-name)))
1568         (rename-buffer (concat wl-draft-folder "/" (buffer-name))))
1569     (auto-save-mode -1)
1570     (wl-draft-mode)
1571     (setq wl-sent-message-via nil)
1572     (setq wl-sent-message-queued nil)
1573     (setq wl-draft-buffer-file-name file-name)
1574     (wl-draft-config-info-operation number 'load)
1575     (goto-char (point-min))
1576     (or (re-search-forward "\n\n" nil t)
1577         (search-forward (concat mail-header-separator "\n") nil t))
1578     (write-region (point-min)(point-max) wl-draft-buffer-file-name
1579                   nil t)
1580     (wl-draft-overload-functions)
1581     (wl-draft-editor-mode)
1582     (wl-highlight-headers 'for-draft)
1583     (run-hooks 'wl-draft-reedit-hook)
1584     (goto-char (point-max))
1585     buf-name
1586     ))
1587
1588 (defmacro wl-draft-body-goto-top ()
1589   (` (progn
1590        (goto-char (point-min))
1591        (if (re-search-forward mail-header-separator nil t)
1592            (forward-char 1)
1593          (goto-char (point-max))))))
1594
1595 (defmacro wl-draft-body-goto-bottom ()
1596   (` (goto-char (point-max))))
1597
1598 (defmacro wl-draft-config-body-goto-header ()
1599   (` (progn
1600        (goto-char (point-min))
1601        (if (re-search-forward mail-header-separator nil t)
1602            (beginning-of-line)
1603          (goto-char (point-max))))))
1604
1605 (defun wl-draft-config-sub-body (content)
1606   (wl-draft-body-goto-top)
1607   (delete-region (point) (point-max))
1608   (if content (insert (eval content))))
1609
1610 (defun wl-draft-config-sub-top (content)
1611   (wl-draft-body-goto-top)
1612   (if content (insert (eval content))))
1613
1614 (defun wl-draft-config-sub-bottom (content)
1615   (wl-draft-body-goto-bottom)
1616   (if content (insert (eval content))))
1617
1618 (defun wl-draft-config-sub-header (content)
1619   (wl-draft-config-body-goto-header)
1620   (if content (insert (concat (eval content) "\n"))))
1621
1622 (defun wl-draft-config-sub-header-top (content)
1623   (goto-char (point-min))
1624   (if content (insert (concat (eval content) "\n"))))
1625
1626 (defun wl-draft-config-sub-part-top (content)
1627   (goto-char (mime-edit-content-beginning))
1628   (if content (insert (concat (eval content) "\n"))))
1629
1630 (defun wl-draft-config-sub-part-bottom (content)
1631   (goto-char (mime-edit-content-end))
1632   (if content (insert (concat (eval content) "\n"))))
1633
1634 (defsubst wl-draft-config-sub-file (content)
1635   (let ((coding-system-for-read wl-cs-autoconv)
1636         (file (expand-file-name (eval content))))
1637     (if (file-exists-p file)
1638         (insert-file-contents file)
1639       (error "%s: no exists file" file))))
1640
1641 (defun wl-draft-config-sub-body-file (content)
1642   (wl-draft-body-goto-top)
1643   (delete-region (point) (point-max))
1644   (wl-draft-config-sub-file content))
1645
1646 (defun wl-draft-config-sub-top-file (content)
1647   (wl-draft-body-goto-top)
1648   (wl-draft-config-sub-file content))
1649
1650 (defun wl-draft-config-sub-bottom-file (content)
1651   (wl-draft-body-goto-bottom)
1652   (wl-draft-config-sub-file content))
1653
1654 (defun wl-draft-config-sub-header-file (content)
1655   (wl-draft-config-body-goto-header)
1656   (wl-draft-config-sub-file content))
1657
1658 (defun wl-draft-config-sub-template (content)
1659   (setq wl-draft-config-variables
1660         (wl-template-insert (eval content))))
1661
1662 (defun wl-draft-config-sub-x-face (content)
1663   (if (and (string-match "\\.xbm\\(\\.gz\\)?$" content)
1664            (fboundp 'x-face-insert)) ; x-face.el is installed.
1665       (x-face-insert content)
1666     (wl-draft-replace-field "X-Face" (elmo-get-file-string content t) t)))
1667
1668 (defsubst wl-draft-config-sub-func (field content)
1669   (let (func)
1670     (if (setq func (assq field wl-draft-config-sub-func-alist))
1671         (let (wl-draft-config-variables)
1672           (funcall (cdr func) content)
1673           ;; for wl-draft-config-sub-template
1674           (cons t wl-draft-config-variables)))))
1675
1676 (defsubst wl-draft-config-exec-sub (clist)
1677   (let (config local-variables)
1678     (while clist
1679       (setq config (car clist))
1680       (cond
1681        ((functionp config)
1682         (funcall config))
1683        ((consp config)
1684         (let ((field (car config))
1685               (content (cdr config))
1686               ret-val)
1687           (cond
1688            ((stringp field)
1689             (wl-draft-replace-field field (eval content) t))
1690            ((setq ret-val (wl-draft-config-sub-func field content))
1691             (if (cdr ret-val) ;; for wl-draft-config-sub-template
1692                 (wl-append local-variables (cdr ret-val))))
1693            ((boundp field) ;; variable
1694             (make-local-variable field)
1695             (set field (eval content))
1696             (wl-append local-variables (list field)))
1697            (t
1698             (error "%s: not variable" field)))))
1699        (t
1700         (error "%s: not supported type" config)))
1701       (setq clist (cdr clist)))
1702     local-variables))
1703
1704 (defun wl-draft-prepared-config-exec (&optional config-alist reply-buf)
1705   "Change headers in draft preparation time."
1706   (interactive)
1707   (unless wl-draft-reedit
1708     (let ((config-alist
1709            (or config-alist
1710                (and (boundp 'wl-draft-prepared-config-alist)
1711                     wl-draft-prepared-config-alist)     ;; For compatible.
1712                wl-draft-config-alist)))
1713       (if config-alist
1714           (wl-draft-config-exec config-alist reply-buf)))))
1715
1716 (defun wl-draft-config-exec (&optional config-alist reply-buf)
1717   "Change headers in draft sending time."
1718   (interactive)
1719   (let ((case-fold-search t)
1720         (alist (or config-alist wl-draft-config-alist))
1721         (reply-buf (or reply-buf (and (buffer-live-p wl-draft-reply-buffer)
1722                                       wl-draft-reply-buffer)))
1723         (local-variables wl-draft-config-variables)
1724         key clist found)
1725     (when (and (or (interactive-p)
1726                    wl-draft-config-exec-flag)
1727                alist)
1728       (save-excursion
1729         (catch 'done
1730           (while alist
1731             (setq key (caar alist)
1732                   clist (cdar alist))
1733             (cond
1734              ((eq key 'reply)
1735               (when (and
1736                      reply-buf
1737                      (save-excursion
1738                        (set-buffer reply-buf)
1739                        (save-restriction
1740                          (std11-narrow-to-header)
1741                          (goto-char (point-min))
1742                          (re-search-forward (car clist) nil t))))
1743                 (wl-draft-config-exec-sub (cdr clist))
1744                 (setq found t)))
1745              ((stringp key)
1746               (when (save-restriction
1747                       (std11-narrow-to-header mail-header-separator)
1748                       (goto-char (point-min))
1749                       (re-search-forward key nil t))
1750                 (wl-append local-variables
1751                            (wl-draft-config-exec-sub clist))
1752                 (setq found t)))
1753              ((eval key)
1754               (wl-append local-variables
1755                          (wl-draft-config-exec-sub clist))
1756               (setq found t)))
1757             (if (and found wl-draft-config-matchone)
1758                 (throw 'done t))
1759             (setq alist (cdr alist))))
1760         (if found
1761             (setq wl-draft-config-exec-flag nil))
1762         (run-hooks 'wl-draft-config-exec-hook)
1763         (put-text-property (point-min)(point-max) 'face nil)
1764         (wl-highlight-message (point-min)(point-max) t)
1765         (setq wl-draft-config-variables
1766               (elmo-uniq-list local-variables))))))
1767
1768 (defun wl-draft-replace-field (field content &optional add)
1769   (save-excursion
1770     (save-restriction
1771       (let ((case-fold-search t)
1772             (inhibit-read-only t) ;; added by teranisi.
1773             beg)
1774         (std11-narrow-to-header mail-header-separator)
1775         (goto-char (point-min))
1776         (if (re-search-forward (concat "^" (regexp-quote field) ":") nil t)
1777             (if content
1778                 ;; replace field
1779                 (progn
1780                   (setq beg (point))
1781                   (re-search-forward "^[^ \t]" nil 'move)
1782                   (beginning-of-line)
1783                   (skip-chars-backward "\n")
1784                   (delete-region beg (point))
1785                   (insert " " content))
1786               ;; delete field
1787               (save-excursion
1788                 (beginning-of-line)
1789                 (setq beg (point)))
1790               (re-search-forward "^[^ \t]" nil 'move)
1791               (beginning-of-line)
1792               (delete-region beg (point)))
1793           (when (and add content)
1794             ;; add field
1795             (goto-char (point-max))
1796             (insert (concat field ": " content "\n"))))))))
1797
1798 (defun wl-draft-config-info-operation (msg operation)
1799   (let* ((msgdb-dir (elmo-folder-msgdb-path (wl-folder-get-elmo-folder
1800                                              wl-draft-folder)))
1801          (filename
1802           (expand-file-name
1803            (format "%s-%d" wl-draft-config-save-filename msg)
1804            msgdb-dir))
1805          element alist variable)
1806     (cond
1807      ((eq operation 'save)
1808       (let ((variables (elmo-uniq-list wl-draft-config-variables)))
1809         (while (setq variable (pop variables))
1810           (when (boundp variable)
1811             (wl-append alist
1812                        (list (cons variable (eval variable))))))
1813         (elmo-object-save filename alist)))
1814      ((eq operation 'load)
1815       (setq alist (elmo-object-load filename))
1816       (while (setq element (pop alist))
1817         (set (make-local-variable (car element)) (cdr element))
1818         (wl-append wl-draft-config-variables (list (car element)))))
1819      ((eq operation 'delete)
1820       (if (file-exists-p filename)
1821           (delete-file filename))))))
1822
1823 (defun wl-draft-queue-info-operation (msg operation
1824                                           &optional add-sent-message-via)
1825   (let* ((msgdb-dir (elmo-folder-msgdb-path
1826                      (wl-folder-get-elmo-folder wl-queue-folder)))
1827          (filename
1828           (expand-file-name
1829            (format "%s-%d" wl-draft-queue-save-filename msg)
1830            msgdb-dir))
1831          element alist variable)
1832     (cond
1833      ((eq operation 'save)
1834       (let ((variables (elmo-uniq-list
1835                         (append wl-draft-queue-save-variables
1836                                 wl-draft-config-variables
1837                                 (list 'wl-draft-fcc-list)))))
1838         (if add-sent-message-via
1839             (progn
1840               (push 'wl-sent-message-queued variables)
1841               (push 'wl-sent-message-via variables)))
1842         (while (setq variable (pop variables))
1843           (when (boundp variable)
1844             (wl-append alist
1845                        (list (cons variable (eval variable))))))
1846         (elmo-object-save filename alist)))
1847      ((eq operation 'load)
1848       (setq alist (elmo-object-load filename))
1849       (while (setq element (pop alist))
1850         (set (make-local-variable (car element)) (cdr element))))
1851      ((eq operation 'get-sent-via)
1852       (setq alist (elmo-object-load filename))
1853       (cdr (assq 'wl-sent-message-via alist)))
1854      ((eq operation 'delete)
1855       (if (file-exists-p filename)
1856           (delete-file filename))))))
1857
1858 (defun wl-draft-queue-append (wl-sent-message-via)
1859   (if wl-draft-verbose-send
1860       (message "Queuing..."))
1861   (let ((send-buffer (current-buffer))
1862         (folder (wl-folder-get-elmo-folder wl-queue-folder))
1863         (message-id (std11-field-body "Message-ID")))
1864     (if (elmo-folder-append-buffer folder t)
1865         (progn
1866           (wl-draft-queue-info-operation
1867            (car (elmo-folder-status folder))
1868            'save wl-sent-message-via)
1869           (wl-draft-write-sendlog 'ok 'queue nil wl-queue-folder message-id)
1870           (when wl-draft-verbose-send
1871             (setq wl-draft-verbose-msg "Queuing...")
1872             (message "Queuing...done")))
1873       (wl-draft-write-sendlog 'failed 'queue nil wl-queue-folder message-id)
1874       (error "Queuing failed"))))
1875
1876 (defun wl-draft-queue-flush ()
1877   "Flush draft queue."
1878   (interactive)
1879   (let* ((queue-folder (wl-folder-get-elmo-folder wl-queue-folder))
1880          (msgs2 (progn
1881                   (elmo-folder-open-internal queue-folder)
1882                   (elmo-folder-list-messages queue-folder)))
1883          (i 0)
1884          (performed 0)
1885          (wl-draft-queue-flushing t)
1886          msgs failure len buffer msgid sent-via)
1887     ;; get plugged send message
1888     (while msgs2
1889       (setq sent-via (wl-draft-queue-info-operation (car msgs2) 'get-sent-via))
1890       (catch 'found
1891         (while sent-via
1892           (when (and (eq (nth 1 (car sent-via)) 'unplugged)
1893                      (or (not (nth 2 (car sent-via)))
1894                          (elmo-plugged-p
1895                           (car (nth 2 (car sent-via)))
1896                           (cdr (nth 2 (car sent-via))))))
1897             (wl-append msgs (list (car msgs2)))
1898             (throw 'found t))
1899           (setq sent-via (cdr sent-via))))
1900       (setq msgs2 (cdr msgs2)))
1901     (when (> (setq len (length msgs)) 0)
1902       (if (elmo-y-or-n-p (format
1903                           "%d message(s) are in the sending queue.  Send now? "
1904                           len)
1905                          (not elmo-dop-flush-confirm) t)
1906           (progn
1907             (save-excursion
1908               (setq buffer (get-buffer-create " *wl-draft-queue-flush*"))
1909               (set-buffer buffer)
1910               (while msgs
1911                 ;; reset buffer local variables
1912                 (kill-all-local-variables)
1913                 (erase-buffer)
1914                 (setq i (+ 1 i)
1915                       failure nil)
1916                 (setq wl-sent-message-via nil)
1917                 (wl-draft-queue-info-operation (car msgs) 'load)
1918                 (elmo-message-fetch queue-folder
1919                                     (car msgs)
1920                                     (elmo-make-fetch-strategy 'entire)
1921                                     nil (current-buffer))
1922                 (condition-case err
1923                     (setq failure (funcall
1924                                    wl-draft-queue-flush-send-function
1925                                    (format "Sending (%d/%d)..." i len)))
1926 ;;;               (wl-draft-raw-send nil nil
1927 ;;;                                  (format "Sending (%d/%d)..." i len))
1928                   (error
1929                    (elmo-display-error err t)
1930                    (setq failure t))
1931                   (quit
1932                    (setq failure t)))
1933                 (if (eq wl-sent-message-modified 'requeue)
1934                     (progn
1935                       (elmo-folder-delete-messages
1936                        queue-folder (cons (car msgs) nil))
1937                       (wl-draft-queue-info-operation (car msgs) 'delete))
1938                   (unless failure
1939                     (elmo-folder-delete-messages
1940                      queue-folder (cons (car msgs) nil))
1941                     (wl-draft-queue-info-operation (car msgs) 'delete)
1942                     (setq performed (+ 1 performed))))
1943                 (setq msgs (cdr msgs)))
1944               (kill-buffer buffer)
1945               (message "%d message(s) are sent." performed)))
1946         (message "%d message(s) are remained to be sent." len))
1947       (elmo-folder-close queue-folder)
1948       len)))
1949
1950 (defun wl-jump-to-draft-buffer (&optional arg)
1951   "Jump to the draft if exists."
1952   (interactive "P")
1953   (if arg
1954       (wl-jump-to-draft-folder)
1955     (let ((bufs (buffer-list))
1956           (draft-regexp (concat
1957                          "^" (regexp-quote
1958                               (elmo-localdir-folder-directory-internal
1959                                (wl-folder-get-elmo-folder wl-draft-folder)))))
1960           buf draft-bufs)
1961       (while bufs
1962         (if (and
1963              (setq buf (buffer-file-name (car bufs)))
1964              (string-match draft-regexp buf))
1965             (setq draft-bufs (cons (buffer-name (car bufs)) draft-bufs)))
1966         (setq bufs (cdr bufs)))
1967       (cond
1968        ((null draft-bufs)
1969         (message "No draft buffer exist."))
1970        (t
1971         (setq draft-bufs
1972               (sort draft-bufs (function (lambda (a b) (not (string< a b))))))
1973         (if (setq buf (cdr (member (buffer-name) draft-bufs)))
1974             (setq buf (car buf))
1975           (setq buf (car draft-bufs)))
1976         (switch-to-buffer buf))))))
1977
1978 (defun wl-jump-to-draft-folder ()
1979   (let ((msgs (reverse (elmo-folder-list-messages (wl-folder-get-elmo-folder
1980                                                    wl-draft-folder))))
1981         (mybuf (buffer-name))
1982         msg buf)
1983     (if (not msgs)
1984         (message "No draft message exist.")
1985       (if (string-match (concat "^" wl-draft-folder "/") mybuf)
1986           (setq msg (cadr (memq
1987                            (string-to-int (substring mybuf (match-end 0)))
1988                            msgs))))
1989       (or msg (setq msg (car msgs)))
1990       (if (setq buf (get-buffer (format "%s/%d" wl-draft-folder msg)))
1991           (switch-to-buffer buf)
1992         (wl-draft-reedit msg)))))
1993
1994 (defun wl-draft-highlight-and-recenter (&optional n)
1995   (interactive "P")
1996   (if wl-highlight-body-too
1997       (let ((beg (point-min))
1998             (end (point-max)))
1999         (put-text-property beg end 'face nil)
2000         (wl-highlight-message beg end t)))
2001   (recenter n))
2002
2003 ;;;; user-agent support by Sen Nagata
2004
2005 ;; this appears to be necessarily global...
2006 (defvar wl-user-agent-compose-p nil)
2007 (defvar wl-user-agent-headers-and-body-alist nil)
2008
2009 ;; this should be a generic function for mail-mode -- i wish there was
2010 ;; something like it in sendmail.el
2011 (defun wl-user-agent-insert-header (header-name header-value)
2012   "Insert HEADER-NAME w/ value HEADER-VALUE into a message."
2013   ;; it seems like overriding existing headers is acceptable -- should
2014   ;; we provide an option?
2015
2016   ;; plan was: unfold header (might be folded), remove existing value, insert
2017   ;;           new value
2018   ;; wl doesn't seem to fold header lines yet anyway :-)
2019
2020   (let ((kill-whole-line t)
2021         end-of-line)
2022     (mail-position-on-field (capitalize header-name))
2023     (setq end-of-line (point))
2024     (beginning-of-line)
2025     (re-search-forward ":" end-of-line)
2026     (insert (concat " " header-value "\n"))
2027     (kill-line)))
2028
2029 ;; this should be a generic function for mail-mode -- i wish there was
2030 ;; something like it in sendmail.el
2031 ;;
2032 ;; ** haven't dealt w/ case where the body is already set **
2033 (defun wl-user-agent-insert-body (body-text)
2034   "Insert a body of text, BODY-TEXT, into a message."
2035   ;; code defensively... :-P
2036   (goto-char (point-min))
2037   (search-forward mail-header-separator)
2038   (forward-line 1)
2039   (insert body-text))
2040
2041 ;;;###autoload
2042 (defun wl-user-agent-compose (&optional to subject other-headers continue
2043                                         switch-function yank-action
2044                                         send-actions)
2045   "Support the `compose-mail' interface for wl.
2046 Only support for TO, SUBJECT, and OTHER-HEADERS has been implemented.
2047 Support for CONTINUE, YANK-ACTION, and SEND-ACTIONS has not
2048 been implemented yet.  Partial support for SWITCH-FUNCTION now supported."
2049
2050   (unless (featurep 'wl)
2051     (require 'wl))
2052   ;; protect these -- to and subject get bound at some point, so it looks
2053   ;; to be necessary to protect the values used w/in
2054   (let ((wl-user-agent-headers-and-body-alist other-headers)
2055         (wl-draft-use-frame (eq switch-function 'switch-to-buffer-other-frame))
2056         (wl-draft-reply-buffer-style 'split))
2057     (when (eq switch-function 'switch-to-buffer-other-window)
2058       (when (one-window-p t)
2059         (if (window-minibuffer-p) (other-window 1))
2060         (split-window))
2061       (other-window 1))
2062     (if to
2063         (if (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
2064                                    'ignore-case)
2065             (setcdr
2066              (wl-string-match-assoc "to" wl-user-agent-headers-and-body-alist
2067                                     'ignore-case)
2068              to)
2069           (setq wl-user-agent-headers-and-body-alist
2070                 (cons (cons "to" to)
2071                       wl-user-agent-headers-and-body-alist))))
2072     (if subject
2073         (if (wl-string-match-assoc "subject"
2074                                    wl-user-agent-headers-and-body-alist
2075                                    'ignore-case)
2076             (setcdr
2077              (wl-string-match-assoc "subject"
2078                                     wl-user-agent-headers-and-body-alist
2079                                     'ignore-case)
2080              subject)
2081           (setq wl-user-agent-headers-and-body-alist
2082                 (cons (cons "subject" subject)
2083                       wl-user-agent-headers-and-body-alist))))
2084     ;; i think this is what we want to use...
2085     (unwind-protect
2086         (progn
2087           ;; tell the hook-function to do its stuff
2088           (setq wl-user-agent-compose-p t)
2089           ;; because to get the hooks working, wl-draft has to think it has
2090           ;; been called interactively
2091           (call-interactively 'wl-draft))
2092       (setq wl-user-agent-compose-p nil))))
2093
2094 (defun wl-user-agent-compose-internal ()
2095   "Manipulate headers and/or a body of a draft message."
2096   ;; being called from wl-user-agent-compose?
2097   (if wl-user-agent-compose-p
2098       (progn
2099         ;; insert headers
2100         (let ((headers wl-user-agent-headers-and-body-alist)
2101               (case-fold-search t))
2102           (while headers
2103             ;; skip body
2104             (if (not (string-match "^body$" (car (car headers))))
2105                 (wl-user-agent-insert-header
2106                  (car (car headers)) (cdr (car headers)))
2107               t)
2108             (setq headers (cdr headers))))
2109         ;; highlight headers (from wl-draft in wl-draft.el)
2110         (wl-highlight-headers 'for-draft)
2111         ;; insert body
2112         (if (wl-string-match-assoc "body" wl-user-agent-headers-and-body-alist
2113                                    'ignore-case)
2114             (wl-user-agent-insert-body
2115              (cdr (wl-string-match-assoc
2116                    "body"
2117                    wl-user-agent-headers-and-body-alist 'ignore-case)))))
2118     t))
2119
2120 (require 'product)
2121 (product-provide (provide 'wl-draft) (require 'wl-version))
2122
2123 ;;; wl-draft.el ends here