tm 7.44.
[elisp/tm.git] / tm-edit.el
1 ;;;
2 ;;; tm-edit.el --- Simple MIME Composer for GNU Emacs
3 ;;;
4 ;;; Copyright (C) 1993 UMEDA Masanobu
5 ;;; Copyright (C) 1994 .. 1996 MORIOKA Tomohiko
6 ;;;
7 ;;; Author: UMEDA Masanobu <umerin@mse.kyutech.ac.jp>
8 ;;;         MORIOKA Tomohiko <morioka@jaist.ac.jp>
9 ;;; Maintainer: MORIOKA Tomohiko <morioka@jaist.ac.jp>
10 ;;; Created: 1994/08/21 renamed from mime.el
11 ;;; Version: $Revision: 7.44 $
12 ;;; Keywords: mail, news, MIME, multimedia, multilingual
13 ;;;
14 ;;; This file is part of tm (Tools for MIME).
15 ;;;
16 ;;; This program is free software; you can redistribute it and/or
17 ;;; modify it under the terms of the GNU General Public License as
18 ;;; published by the Free Software Foundation; either version 2, or
19 ;;; (at your option) any later version.
20 ;;;
21 ;;; This program is distributed in the hope that it will be useful,
22 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
24 ;;; General Public License for more details.
25 ;;;
26 ;;; You should have received a copy of the GNU General Public License
27 ;;; along with This program.  If not, write to the Free Software
28 ;;; Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
29
30 ;;; Commentary:
31
32 ;; This is an Emacs minor mode for editing Internet multimedia
33 ;; messages formatted in MIME (RFC 1521 and RFC 1522). All messages in
34 ;; this mode are composed in the tagged MIME format, that are
35 ;; described in the following examples. The messages composed in the
36 ;; tagged MIME format are automatically translated into a MIME
37 ;; compliant message when exiting the mode.
38
39 ;; Mule (a multilingual extension to Emacs 18 and 19) has a capability
40 ;; of handling multilingual text in limited ISO-2022 manner that is
41 ;; based on early experiences in Japanese Internet community and
42 ;; resulted in RFC 1468 (ISO-2022-JP charset for MIME). In order to
43 ;; enable multilingual capability in single text message in MIME,
44 ;; charset of multilingual text written in Mule is declared as either
45 ;; `ISO-2022-JP-2' [RFC 1554] or `ISO-2022-INT-1'. Mule is required
46 ;; for reading the such messages.
47
48 ;; This MIME composer can work with Mail mode, mh-e letter Mode, and
49 ;; News mode.  First of all, you need the following autoload
50 ;; definition to load mime/editor-mode automatically:
51 ;;
52 ;; (autoload 'mime/editor-mode "tm-edit"
53 ;;           "Minor mode for editing MIME message." t)
54 ;;
55 ;; In case of Mail mode (includes VM mode), you need the following
56 ;; hook definition:
57 ;;
58 ;; (add-hook 'mail-mode-hook 'mime/editor-mode)
59 ;; (add-hook 'mail-send-hook 'mime-editor/maybe-translate)
60 ;;
61 ;; In case of MH-E, you need the following hook definition:
62 ;;
63 ;; (add-hook 'mh-letter-mode-hook
64 ;;           (function
65 ;;            (lambda ()
66 ;;              (mime/editor-mode)
67 ;;              (make-local-variable 'mail-header-separator)
68 ;;              (setq mail-header-separator "--------")
69 ;;              ))))
70 ;; (add-hook 'mh-before-send-letter-hook 'mime-editor/maybe-translate)
71 ;;
72 ;; In case of News mode, you need the following hook definition:
73 ;;
74 ;; (add-hook 'news-reply-mode-hook 'mime/editor-mode)
75 ;; (add-hook 'news-inews-hook 'mime-editor/maybe-translate)
76 ;;
77 ;; In case of Emacs 19, it is possible to emphasize the message tags
78 ;; using font-lock mode as follows:
79 ;;
80 ;; (add-hook 'mime/editor-mode-hook
81 ;;           (function
82 ;;            (lambda ()
83 ;;              (font-lock-mode 1)
84 ;;              (setq font-lock-keywords (list mime-editor/tag-regexp))
85 ;;              ))))
86
87 ;; The message tag looks like:
88 ;;
89 ;;      --[[TYPE/SUBTYPE;PARAMETERS][ENCODING]]
90 ;;
91 ;; The tagged MIME message examples:
92 ;;
93 ;; This is a conventional plain text.  It should be translated into
94 ;; text/plain.
95 ;; 
96 ;;--[[text/plain]]
97 ;; This is also a plain text.  But, it is explicitly specified as is.
98 ;;
99 ;;--[[text/plain; charset=ISO-2022-JP]]
100 ;; \e$B$3$l$O\e(B charset \e$B$r\e(B ISO-2022-JP \e$B$K;XDj$7$?F|K\8l$N\e(B plain \e$B%F%-%9%H$G$9\e(B.
101 ;;
102 ;;--[[text/richtext]]
103 ;; <center>This is a richtext.</center>
104 ;;
105 ;;--[[image/gif][base64]]^M...image encoded in base64 comes here...
106 ;;
107 ;;--[[audio/basic][base64]]^M...audio encoded in base64 comes here...
108
109 ;;; Code:
110
111 (require 'sendmail)
112 (require 'mail-utils)
113 (require 'mel)
114 (require 'tl-822)
115 (require 'tl-list)
116 (require 'tm-view)
117 (require 'tm-ew-e)
118 (require 'signature)
119
120
121 ;;; @ version
122 ;;;
123
124 (defconst mime-editor/RCS-ID
125   "$Id: tm-edit.el,v 7.44 1996/02/23 16:16:30 morioka Exp $")
126
127 (defconst mime-editor/version (get-version-string mime-editor/RCS-ID))
128
129
130 ;;; @ variables
131 ;;;
132
133 (defvar mime-prefix "\C-c\C-x"
134   "*Keymap prefix for MIME commands.")
135
136 (defvar mime-signature-file "~/.signature.rtf"
137   "*Signature file to be included as a part of a multipart message.")
138
139 (defvar mime-ignore-preceding-spaces nil
140   "*Ignore preceding white spaces if non-nil.")
141
142 (defvar mime-ignore-trailing-spaces nil
143   "*Ignore trailing white spaces if non-nil.")
144
145 (defvar mime-ignore-same-text-tag t
146   "*Ignore preceding text content-type tag that is same with new one.
147 If non-nil, the text tag is not inserted unless something different.")
148
149 (defvar mime-auto-hide-body t
150   "*Hide non-textual body encoded in base64 after insertion if non-nil.")
151
152 (defvar mime-string-encoder
153   (cond ((boundp 'NEMACS)
154          (function mime-string-encoder-for-nemacs))
155         ((featurep 'mule)
156          (function mime-string-encoder-for-mule))
157         ((string-match "^19\\." emacs-version)
158          (function mime-string-encoder-for-emacs19))
159         (t                              ;ASCII only emacs
160          (function mime-string-encoder-for-emacs18)))
161   "*Function to encode a string for given encoding method.
162 The method is a form of (CHARSET . ENCODING).")
163
164 (defvar mime-voice-recorder
165   (function mime-voice-recorder-for-sun)
166   "*Function to record a voice message and return a buffer that contains it.")
167
168 (defvar mime/editor-mode-hook nil
169   "*Hook called when enter MIME mode.")
170
171 (defvar mime-editor/translate-hook nil
172   "*Hook called before translating into a MIME compliant message.
173 To insert a signature file specified by mime-signature-file
174 (`.signature.rtf' by default) automatically, call the function
175 `mime-editor/insert-signature' from this hook.")
176
177 (defvar mime-editor/exit-hook nil
178   "*Hook called when exit MIME mode.")
179
180 (defvar mime-content-types
181   '(("text"
182      ;; Charset parameter need not to be specified, since it is
183      ;; defined automatically while translation.
184      ("plain"
185       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
186       )
187      ("richtext"
188       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
189       )
190      ("enriched"
191       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
192       )
193      ("x-latex"
194       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
195       )
196      ("html"
197       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
198       )
199      ("x-rot13-47")
200      )
201     ("message"
202      ("external-body"
203       ("access-type"
204        ("anon-ftp"
205         ("site" "ftp.jaist.ac.jp" "wnoc-fuk.wide.ad.jp" "nic.karrn.ad.jp")
206         ("directory" "/pub/GNU/elisp/mime")
207         ("name")
208         ("mode" "image" "ascii" "local8"))
209        ("ftp"
210         ("site")
211         ("directory")
212         ("name")
213         ("mode" "image" "ascii" "local8"))
214        ("tftp"        ("site") ("name"))
215        ("afs"         ("site") ("name"))
216        ("local-file"  ("site") ("name"))
217        ("mail-server" ("server" "ftpmail@nic.karrn.ad.jp"))
218        ))
219      ("rfc822")
220      )
221     ("application"
222      ("octet-stream" ("type" "" "tar" "shar"))
223      ("postscript")
224      ("x-kiss" ("x-cnf")))
225     ("image"
226      ("gif")
227      ("jpeg")
228      ("tiff")
229      ("x-pic")
230      ("x-mag")
231      ("x-xwd")
232      ("x-xbm")
233      )
234     ("audio" ("basic"))
235     ("video" ("mpeg"))
236     )
237   "*Alist of content-type, subtype, parameters and its values.")
238
239 (defvar mime-file-types
240   '(("\\.rtf$"
241      "text"     "richtext"      nil
242      nil
243      nil                nil)
244     ("\\.html$"
245      "text"     "html"          nil
246      nil
247      nil                nil)
248     ("\\.ps$"
249      "application" "postscript" nil
250      "quoted-printable"
251      "attachment"       (("filename" . file))
252      )
253     ("\\.jpg$"
254      "image"    "jpeg"          nil
255      "base64"
256      "inline"           (("filename" . file))
257      )
258     ("\\.gif$"
259      "image"    "gif"           nil
260      "base64"
261      "inline"           (("filename" . file))
262      )
263     ("\\.tiff$"
264      "image"    "tiff"          nil
265      "base64"
266      "inline"           (("filename" . file))
267      )
268     ("\\.pic$"
269      "image"    "x-pic"         nil
270      "base64"
271      "inline"           (("filename" . file))
272      )
273     ("\\.mag$"
274      "image"    "x-mag"         nil
275      "base64"
276      "inline"           (("filename" . file))
277      )
278     ("\\.xbm$"
279      "image"    "x-xbm"         nil
280      "base64"
281      "inline"           (("filename" . file))
282      )
283     ("\\.xwd$"
284      "image"    "x-xwd"         nil
285      "base64"
286      "inline"           (("filename" . file))
287      )
288     ("\\.au$"
289      "audio"    "basic"         nil
290      "base64"
291      "attachment"               (("filename" . file))
292      )
293     ("\\.mpg$"
294      "video"    "mpeg"          nil
295      "base64"
296      "attachment"       (("filename" . file))
297      )
298     ("\\.el$"
299      "application" "octet-stream" (("type" . "emacs-lisp"))
300      "7bit"
301      "attachment"       (("filename" . file))
302      )
303     ("\\.lsp$"
304      "application" "octet-stream" (("type" . "common-lisp"))
305      "7bit"
306      "attachment"       (("filename" . file))
307      )
308     ("\\.tar\\.gz$"
309      "application" "octet-stream" (("type" . "tar+gzip"))
310      nil
311      "attachment"       (("filename" . file))
312      )
313     ("\\.tgz$"
314      "application" "octet-stream" (("type" . "tar+gzip"))
315      nil
316      "attachment"       (("filename" . file))
317      )
318     ("\\.tar\\.Z$"
319      "application" "octet-stream" (("type" . "tar+compress"))
320      nil
321      "attachment"       (("filename" . file))
322      )
323     ("\\.taz$"
324      "application" "octet-stream" (("type" . "tar+compress"))
325      nil
326      "attachment"       (("filename" . file))
327      )
328     ("\\.gz$"
329      "application" "octet-stream" (("type" . "gzip"))
330      nil
331      "attachment"       (("filename" . file))
332      )
333     ("\\.Z$"
334      "application" "octet-stream" (("type" . "compress"))
335      nil
336      "attachment"       (("filename" . file))
337      )
338     ("\\.lzh$"
339      "application" "octet-stream" (("type" . "lha"))
340      nil
341      "attachment"       (("filename" . file))
342      )
343     ("\\.zip$"
344      "application" "zip" nil
345      nil
346      "attachment"       (("filename" . file))
347      )
348     ("\\.diff$"
349      "application" "octet-stream" (("type" . "patch"))
350      nil
351      "attachment"       (("filename" . file))
352      )
353     ("\\.signature"
354      "text"     "plain"         nil     nil)
355     (".*"
356      "application" "octet-stream" nil
357      nil
358      "attachment"       (("filename" . file))
359      )
360     )
361   "*Alist of file name, types, parameters, and default encoding.
362 If encoding is nil, it is determined from its contents.")
363
364 ;;; @@ about message inserting
365 ;;;
366
367 (defvar mime-editor/yank-ignored-field-list
368   '("Received" "Sender" "Approved" "Path" "Status" "X-VM-.*" "X-UIDL")
369   "Delete these fields from original message when it is inserted
370 as message/rfc822 part.
371 Each elements are regexp of field-name. [tm-edit.el]")
372
373 (defvar mime-editor/yank-ignored-field-regexp
374   (concat "^"
375           (apply (function regexp-or) mime-editor/yank-ignored-field-list)
376           ":"))
377
378 (defvar mime-editor/message-inserter-alist nil)
379 (defvar mime-editor/mail-inserter-alist nil)
380
381 ;;; @@ about message splitting
382 ;;;
383
384 (defvar mime-editor/split-message t
385   "*Split large message if it is non-nil. [tm-edit.el]")
386
387 (defvar mime-editor/message-default-max-length 1000
388   "*Default maximum size of a message. [tm-edit.el]")
389
390 (defvar mime-editor/message-max-length-alist
391   '((news-reply-mode . 500)))
392
393 (defconst mime-editor/split-ignored-field-regexp
394   "\\(^Content-\\|^Subject:\\|^Mime-Version:\\)")
395
396 (defvar mime-editor/split-blind-field-regexp
397   "\\(^[BDFbdf]cc:\\|^cc:[ \t]*$\\)")
398
399 (defvar mime-editor/message-default-sender-alist
400   '((mail-mode . mail-send-and-exit)
401     (mh-letter-mode . mh-send-letter)
402     (news-reply-mode . gnus-inews-news)
403     ))
404
405 (defvar mime-editor/split-message-sender-alist
406   '((mail-mode
407      . (lambda ()
408          (interactive)
409          (sendmail-send-it)
410          ))
411     (mh-letter-mode
412      . (lambda (&optional arg)
413          (interactive "P")
414          (write-region (point-min) (point-max)
415                        mime-editor/draft-file-name nil 'no-message)
416          (cond (arg
417                 (pop-to-buffer "MH mail delivery")
418                 (erase-buffer)
419                 (mh-exec-cmd-output mh-send-prog t "-watch" "-nopush"
420                                     "-nodraftfolder"
421                                     mh-send-args mime-editor/draft-file-name)
422                 (goto-char (point-max)) ; show the interesting part
423                 (recenter -1)
424                 (sit-for 1))
425                (t
426                 (apply 'mh-exec-cmd-quiet t mh-send-prog 
427                        (mh-list-to-string
428                         (list "-nopush" "-nodraftfolder"
429                               "-noverbose" "-nowatch"
430                               mh-send-args mime-editor/draft-file-name)))))
431          ))
432     ))
433
434 (defvar mime-editor/window-config-alist
435   '((mail-mode       . nil)
436     (mh-letter-mode  . mh-previous-window-config)
437     (news-reply-mode . (cond ((boundp 'gnus-winconf-post-news)
438                               (prog1
439                                   gnus-winconf-post-news
440                                 (setq gnus-winconf-post-news nil)
441                                 ))
442                              ((boundp 'gnus-prev-winconf)
443                               (prog1
444                                   gnus-prev-winconf
445                                 (setq gnus-prev-winconf nil)
446                                 ))
447                              ))
448     ))
449
450 (defvar mime-editor/news-reply-mode-server-running nil)
451
452
453 ;;; @@ about PGP
454 ;;;
455
456 (defvar mime-editor/signing-type nil
457   "*PGP signing type (pgp-elkins, pgp-kazu or nil). [tm-edit.el]")
458
459 (defvar mime-editor/encrypting-type nil
460   "*PGP encrypting type (pgp-elkins, pgp-kazu or nil). [tm-edit.el]")
461
462 (if (or mime-editor/signing-type mime-editor/encrypting-type)
463     (require 'mailcrypt)
464   )
465
466
467 ;;; @@ about tag
468 ;;;
469
470 (defconst mime-editor/single-part-tag-regexp
471   "^--[[][[]\\([^]]*\\)]\\([[]\\([^]]*\\)]\\|\\)]"
472   "*Regexp of MIME tag in the form of [[CONTENT-TYPE][ENCODING]].")
473
474 (defconst mime-editor/multipart-beginning-regexp "^--<<\\([^<>]+\\)>>-{\n")
475
476 (defconst mime-editor/multipart-end-regexp "^--}-<<\\([^<>]+\\)>>\n")
477
478 (defconst mime-editor/beginning-tag-regexp
479   (regexp-or mime-editor/single-part-tag-regexp
480              mime-editor/multipart-beginning-regexp))
481
482 (defconst mime-editor/end-tag-regexp
483   (regexp-or mime-editor/single-part-tag-regexp
484              mime-editor/multipart-end-regexp))
485
486 (defconst mime-editor/tag-regexp
487   (regexp-or mime-editor/single-part-tag-regexp
488              mime-editor/multipart-beginning-regexp
489              mime-editor/multipart-end-regexp))
490
491 (defvar mime-tag-format "--[[%s]]"
492   "*Control-string making a MIME tag.")
493
494 (defvar mime-tag-format-with-encoding "--[[%s][%s]]"
495   "*Control-string making a MIME tag with encoding.")
496
497 ;;; @@ multipart boundary
498 ;;;
499
500 (defvar mime-multipart-boundary "Multipart"
501   "*Boundary of a multipart message.")
502
503
504 ;;; @@ buffer local variables
505 ;;;
506
507 (defvar mime/editor-mode-old-local-map nil)
508 (defvar mime/editor-mode-old-selective-display nil)
509 (defvar mime/editing-buffer nil)
510
511 \f
512 ;;; @ constants
513 ;;;
514
515 (defconst mime-tspecials-regexp "[][()<>@,;:\\\"/?.= \t]"
516   "*Specify MIME tspecials.
517 Tspecials means any character that matches with it in header must be quoted.")
518
519 (defconst mime-editor/mime-version-value
520   (format "1.0 (generated by tm-edit %s)" mime-editor/version)
521   "MIME version number.")
522
523 (defconst mime-editor/mime-map (make-sparse-keymap)
524   "Keymap for MIME commands.")
525
526 ;;; @ keymap and menu
527 ;;;
528
529 (defvar mime/editor-mode-flag nil)
530 (make-variable-buffer-local 'mime/editor-mode-flag)
531
532 (set-alist 'minor-mode-alist 'mime/editor-mode-flag '(" MIME-Edit"))
533
534 (defun mime-editor/define-keymap (keymap)
535   "Add mime-editor commands to KEYMAP."
536   (if (not (keymapp keymap))
537       nil
538     (define-key keymap "\C-t" 'mime-editor/insert-text)
539     (define-key keymap "\C-i" 'mime-editor/insert-file)
540     (define-key keymap "\C-e" 'mime-editor/insert-external)
541     (define-key keymap "\C-v" 'mime-editor/insert-voice)
542     (define-key keymap "\C-y" 'mime-editor/insert-message)
543     (define-key keymap "\C-m" 'mime-editor/insert-mail)
544     (define-key keymap "\C-w" 'mime-editor/insert-signature)
545     (define-key keymap "\C-s" 'mime-editor/insert-signature)
546     (define-key keymap "\C-k" 'mime-editor/insert-key)
547     (define-key keymap "t"    'mime-editor/insert-tag)
548     (define-key keymap "a"    'mime-editor/enclose-alternative-region)
549     (define-key keymap "p"    'mime-editor/enclose-parallel-region)
550     (define-key keymap "m"    'mime-editor/enclose-mixed-region)
551     (define-key keymap "d"    'mime-editor/enclose-digest-region)
552     (define-key keymap "s"    'mime-editor/enclose-signed-region)
553     (define-key keymap "e"    'mime-editor/enclose-encrypted-region)
554     (define-key keymap "\C-p" 'mime-editor/preview-message)
555     (define-key keymap "\C-z" 'mime-editor/exit)
556     (define-key keymap "?"    'mime-editor/help)
557     ))
558
559 (mime-editor/define-keymap mime-editor/mime-map)
560
561 (defconst mime-editor/menu-title "MIME-Edit")
562
563 (defconst mime-editor/menu-list
564   '((mime-help  "Describe MIME editor mode" mime-editor/help)
565     (file       "Insert File"           mime-editor/insert-file)
566     (external   "Insert External"       mime-editor/insert-external)
567     (voice      "Insert Voice"          mime-editor/insert-voice)
568     (message    "Insert Message"        mime-editor/insert-message)
569     (mail       "Insert Mail"           mime-editor/insert-mail)
570     (signature  "Insert Signature"      mime-editor/insert-signature)
571     (text       "Insert Text"           mime-editor/insert-text)
572     (tag        "Insert Tag"            mime-editor/insert-tag)
573     (alternative "Enclose as alternative"
574                  mime-editor/enclose-alternative-region)
575     (parallel   "Enclose as parallel"   mime-editor/enclose-parallel-region)
576     (mixed      "Enclose as serial"     mime-editor/enclose-mixed-region)
577     (digest     "Enclose as digest"     mime-editor/enclose-digest-region)
578     (signed     "Enclose as signed"     mime-editor/enclose-signed-region)
579     (encrypted  "Enclose as encrypted"  mime-editor/enclose-encrypted-region)
580     (key        "Insert Public Key"     mime-editor/insert-key)
581     (split      "About split"           mime-editor/set-split)
582     (sign       "About sign"            mime-editor/set-sign)
583     (encrypt    "About encryption"      mime-editor/set-encrypt)
584     (preview    "Preview Message"       mime-editor/preview-message)
585     )
586   "MIME-edit menubar entry.")
587
588 (defun mime-editor/define-menu-for-emacs19 ()
589   "Define menu for Emacs 19."
590   (define-key (current-local-map) [menu-bar mime-edit]
591     (cons mime-editor/menu-title
592           (make-sparse-keymap mime-editor/menu-title)))
593   (mapcar (function
594            (lambda (item)
595              (define-key (current-local-map)
596                (vector 'menu-bar 'mime-edit (car item))
597                (cons (nth 1 item)(nth 2 item))
598                )
599              ))
600           (reverse mime-editor/menu-list)
601           ))
602
603 ;;; modified by Pekka Marjola <pema@niksula.hut.fi>
604 ;;;     1995/9/5 (c.f. [tm-en:69])
605 (defun mime-editor/define-menu-for-xemacs ()
606   "Define menu for Emacs 19."
607   (cond ((featurep 'menubar)
608          (make-local-variable 'current-menubar)
609          (set-buffer-menubar current-menubar)
610          (add-submenu nil
611                       (cons mime-editor/menu-title
612                             (mapcar (function
613                                      (lambda (item)
614                                        (vector (nth 1 item)(nth 2 item)
615                                                mime/editor-mode-flag)
616                                        ))
617                                     mime-editor/menu-list)))
618          )))
619
620 ;;; modified by Steven L. Baur <steve@miranova.com>
621 ;;;     1995/12/6 (c.f. [tm-en:209])
622 (if (and (string-match "XEmacs\\|Lucid" emacs-version)
623          (not (boundp 'mime-editor/popup-menu-for-xemacs)))
624     (setq mime-editor/popup-menu-for-xemacs
625           (append '("MIME Commands" "---")
626                   (mapcar (function (lambda (item)
627                                       (vector (nth 1 item)
628                                               (nth 2 item)
629                                               t)))
630                           mime-editor/menu-list)))
631   )
632 ;;; end
633
634
635 ;;; @ functions
636 ;;;
637
638 ;;;###autoload
639 (defun mime/editor-mode ()
640   "MIME minor mode for editing the tagged MIME message.
641
642 In this mode, basically, the message is composed in the tagged MIME
643 format.  The message tag looks like:
644
645         `--[[text/plain; charset=ISO-2022-JP][7bit]]'.
646
647 The tag specifies the MIME content type, subtype, optional parameters
648 and transfer encoding of the message following the tag.  Messages
649 without any tag are treated as `text/plain' by default.  Charset and
650 transfer encoding are automatically defined unless explicitly
651 specified.  Binary messages such as audio and image are usually hidden
652 using selective-display facility.  The messages in the tagged MIME
653 format are automatically translated into a MIME compliant message when
654 exiting this mode.
655
656 Available charsets depend on Emacs version being used.  The following
657 lists the available charsets of each emacs.
658
659 Emacs18:        US-ASCII is only available.
660 NEmacs:         US-ASCII and ISO-2022-JP are available.
661 Emacs19:        US-ASCII and ISO-8859-1 are available.
662 Mule:           US-ASCII, ISO-8859-* (except for ISO-8859-6),
663                 ISO-2022-JP, ISO-2022-JP-2 and ISO-2022-INT-1 are available.
664
665 ISO-2022-JP-2 and ISO-2022-INT-1 charsets used in Mule is expected to
666 be used to represent multilingual text in intermixed manner.  Any
667 languages that has no registered charset are represented as either
668 ISO-2022-JP-2 or ISO-2022-INT-1 in Mule.
669
670 Following commands are available in addition to major mode commands:
671 \\[mime-editor/insert-text]     insert a text message.
672 \\[mime-editor/insert-file]     insert a (binary) file.
673 \\[mime-editor/insert-external] insert a reference to external body.
674 \\[mime-editor/insert-voice]    insert a voice message.
675 \\[mime-editor/insert-message]  insert a mail or news message.
676 \\[mime-editor/insert-mail]     insert a mail message.
677 \\[mime-editor/insert-signature]        insert a signature file at end.
678 \\[mime-editor/insert-tag]      insert a new MIME tag.
679 \\[mime-editor/enclose-alternative-region]      enclose as multipart/alternative.
680 \\[mime-editor/enclose-parallel-region] enclose as multipart/parallel.
681 \\[mime-editor/enclose-mixed-region]    enclose as multipart/mixed.
682 \\[mime-editor/enclose-digest-region]   enclose as multipart/digest.
683 \\[mime-editor/enclose-signed-region]   enclose as PGP signed.
684 \\[mime-editor/enclose-encrypted-region]        enclose as PGP encrypted.
685 \\[mime-editor/insert-key]      insert PGP public key.
686 \\[mime-editor/preview-message] preview editing MIME message.
687 \\[mime-editor/exit]    exit and translate into a MIME compliant message.
688 \\[mime-editor/maybe-translate] exit and translate if in MIME mode, then split.
689 \\[mime-editor/help]    show this help.
690
691 Additional commands are available in some major modes:
692 C-c C-c         exit, translate and run the original command.
693 C-c C-s         exit, translate and run the original command.
694
695 The following is a message example written in the tagged MIME format.
696 TABs at the beginning of the line are not a part of the message:
697
698         This is a conventional plain text.  It should be translated
699         into text/plain.
700         --[[text/plain]]
701         This is also a plain text.  But, it is explicitly specified as
702         is.
703         --[[text/plain; charset=ISO-2022-JP]]
704         \e$B$3$l$O\e(B charset \e$B$r\e(B ISO-2022-JP \e$B$K;XDj$7$?F|K\8l$N\e(B plain \e$B%F%-%9\e(B
705         \e$B%H$G$9\e(B.
706         --[[text/richtext]]
707         <center>This is a richtext.</center>
708         --[[image/gif][base64]]^M...image encoded in base64 here...
709         --[[audio/basic][base64]]^M...audio encoded in base64 here...
710
711 User customizable variables (not documented all of them):
712  mime-prefix
713     Specifies a key prefix for MIME minor mode commands.
714
715  mime-signature-file
716     Specifies a signature file to be included as part of a multipart
717     message.
718
719  mime-ignore-preceding-spaces
720     Preceding white spaces in a message body are ignored if non-nil.
721
722  mime-ignore-trailing-spaces
723     Trailing white spaces in a message body are ignored if non-nil.
724
725  mime-auto-fill-header
726     Fill header fields that contain encoded-words if non-nil.
727
728  mime-auto-hide-body
729     Hide a non-textual body message encoded in base64 after insertion
730     if non-nil.
731
732  mime-string-encoder
733     Specifies a function to encode a string for given encoding method.
734     The method is a form of (CHARSET . ENCODING).
735
736  mime-voice-recorder
737     Specifies a function to record a voice message and return a buffer
738     that contains it.  The function mime-voice-recorder-for-sun is for
739     Sun SparcStations.
740
741  mime/editor-mode-hook
742     Turning on MIME mode calls the value of mime/editor-mode-hook, if
743     it is non-nil.
744
745  mime-editor/translate-hook
746     The value of mime-editor/translate-hook is called just before translating
747     the tagged MIME format into a MIME compliant message if it is
748     non-nil.  If the hook call the function mime-editor/insert-signature,
749     the signature file will be inserted automatically.
750
751  mime-editor/exit-hook
752     Turning off MIME mode calls the value of mime-editor/exit-hook, if it is
753     non-nil."
754   (interactive)
755   (if mime/editor-mode-flag
756       (error "You are already editing a MIME message.")
757     (setq mime/editor-mode-flag t)
758     ;; Remember old key bindings.
759     (if (string-match "XEmacs\\|Lucid" emacs-version)
760         nil
761     (make-local-variable 'mime/editor-mode-old-local-map)
762     (setq mime/editor-mode-old-local-map (current-local-map))
763     ;; Add MIME commands to current local map.
764       (use-local-map (copy-keymap (current-local-map))))
765     (if (not (lookup-key (current-local-map) mime-prefix))
766         (define-key (current-local-map) mime-prefix mime-editor/mime-map))
767     
768     ;; Define menu.  Menus for other emacs implementations are
769     ;; welcome.
770     ;;  modified by Pekka Marjola <pema@niksula.hut.fi>
771     ;;          1995/9/5 (c.f. [tm-eng:69])
772     (cond ((string-match "XEmacs\\|Lucid" emacs-version)
773            (mime-editor/define-menu-for-xemacs))
774           ((string-match "^19\\." emacs-version)
775            (mime-editor/define-menu-for-emacs19)
776            ))
777     ;; end
778     
779     ;; Remember old selective-display.
780     (make-local-variable 'mime/editor-mode-old-selective-display)
781     (setq mime/editor-mode-old-selective-display selective-display)
782     (setq selective-display t)
783     ;; I don't care about saving these.
784     (setq paragraph-start
785           (regexp-or mime-editor/single-part-tag-regexp
786                      paragraph-start))
787     (setq paragraph-separate
788           (regexp-or mime-editor/single-part-tag-regexp
789                      paragraph-separate))
790     (run-hooks 'mime/editor-mode-hook)
791     (message
792      (substitute-command-keys
793       "Type \\[mime-editor/exit] to exit MIME mode, and type \\[mime-editor/help] to get help."))
794     ))
795
796 ;;;###autoload
797 (defalias 'edit-mime 'mime/editor-mode)         ; for convenience
798 (defalias 'mime-mode 'mime/editor-mode)         ; for convenience
799
800 (defun mime-editor/exit (&optional nomime no-error)
801   "Translate the tagged MIME message into a MIME compliant message.
802 With no argument encode a message in the buffer into MIME, otherwise
803 just return to previous mode."
804   (interactive "P")
805   (if (not mime/editor-mode-flag)
806       (if (null no-error)
807           (error "You aren't editing a MIME message.")
808         )
809     (if (not nomime)
810         (progn
811           (run-hooks 'mime-editor/translate-hook)
812           (mime-editor/translate-buffer)))
813     ;; Restore previous state.
814     (setq mime/editor-mode-flag nil)
815     (cond ((string-match "XEmacs\\|Lucid" emacs-version)
816            ;; mime-prefix only defined if binding was nil
817            (if (eq (lookup-key (current-local-map) mime-prefix)
818                    mime-editor/mime-map)
819                (define-key (current-local-map) mime-prefix nil))
820            (delete-menu-item (list mime-editor/menu-title)))
821           (t
822            (use-local-map mime/editor-mode-old-local-map)))
823     
824     (setq selective-display mime/editor-mode-old-selective-display)
825     (set-buffer-modified-p (buffer-modified-p))
826     (run-hooks 'mime-editor/exit-hook)
827     (message "Exit MIME editor mode.")
828     ))
829
830 (defun mime-editor/maybe-translate ()
831   (interactive)
832   (mime-editor/exit nil t)
833   (call-interactively 'mime-editor/maybe-split-and-send)
834   )
835
836 (defun mime-editor/help ()
837   "Show help message about MIME mode."
838   (interactive)
839   (with-output-to-temp-buffer "*Help*"
840     (princ "MIME editor mode:\n")
841     (princ (documentation 'mime/editor-mode))
842     (print-help-return-message)))
843
844 (defun mime-editor/insert-text ()
845   "Insert a text message.
846 Charset is automatically obtained from the `mime/lc-charset-alist'."
847   (interactive)
848   (if (and (mime-editor/insert-tag "text" nil nil)
849            (looking-at mime-editor/single-part-tag-regexp))
850       (progn
851         ;; Make a space between the following message.
852         (insert "\n")
853         (forward-char -1)
854         )))
855
856 (defun mime-editor/insert-file (file)
857   "Insert a message from a file."
858   (interactive "fInsert file as MIME message: ")
859   (let*  ((guess (mime-find-file-type file))
860           (pritype (nth 0 guess))
861           (subtype (nth 1 guess))
862           (parameters (nth 2 guess))
863           (default (nth 3 guess))       ;Guess encoding from its file name.
864           (disposition-type (nth 4 guess))
865           (disposition-params (nth 5 guess))
866           (encoding
867            (if (not (interactive-p))
868                default
869              (completing-read
870               (concat "What transfer encoding"
871                       (if default
872                           (concat " (default "
873                                   (if (string-equal default "")
874                                       "\"\""
875                                     default)
876                                   ")"
877                                   ))
878                       ": ")
879               mime-encoding-method-alist nil t nil))))
880     (if (string-equal encoding "")
881         (setq encoding default))
882     (if (or (consp parameters) (stringp disposition-type))
883         (let ((rest parameters) cell attribute value)
884           (setq parameters "")
885           (while rest
886             (setq cell (car rest))
887             (setq attribute (car cell))
888             (setq value (cdr cell))
889             (if (eq value 'file)
890                 (setq value (rfc822/wrap-as-quoted-string
891                              (file-name-nondirectory file)))
892               )
893             (setq parameters (concat parameters "; " attribute "=" value))
894             (setq rest (cdr rest))
895             )
896           (if disposition-type
897               (progn
898                 (setq parameters
899                       (concat parameters "\n"
900                               "Content-Disposition: " disposition-type))
901                 (setq rest disposition-params)
902                 (while rest
903                   (setq cell (car rest))
904                   (setq attribute (car cell))
905                   (setq value (cdr cell))
906                   (if (eq value 'file)
907                       (setq value (rfc822/wrap-as-quoted-string
908                                    (file-name-nondirectory file)))
909                     )
910                   (setq parameters
911                         (concat parameters "; " attribute "=" value))
912                   (setq rest (cdr rest))
913                   )
914                 ))
915           ))
916     (mime-editor/insert-tag pritype subtype parameters)
917     (mime-editor/insert-binary-file file encoding)
918     ))
919
920 (defun mime-editor/insert-external ()
921   "Insert a reference to external body."
922   (interactive)
923   (mime-editor/insert-tag "message" "external-body" nil ";\n\t")
924   ;;(forward-char -1)
925   ;;(insert "Content-Description: " (read-string "Content-Description: ") "\n")
926   ;;(forward-line 1)
927   (let* ((pritype (mime-prompt-for-type))
928          (subtype (mime-prompt-for-subtype pritype))
929          (parameters (mime-prompt-for-parameters pritype subtype ";\n\t")))
930     (and pritype
931          subtype
932          (insert "Content-Type: "
933                  pritype "/" subtype (or parameters "") "\n")))
934   (if (and (not (eobp))
935            (not (looking-at mime-editor/single-part-tag-regexp)))
936       (insert (mime-make-text-tag) "\n")))
937
938 (defun mime-editor/insert-voice ()
939   "Insert a voice message."
940   (interactive)
941   (mime-editor/insert-tag "audio" "basic" nil)
942   (let ((buffer (funcall mime-voice-recorder)))
943     (unwind-protect
944         (mime-editor/insert-binary-buffer buffer "base64")
945       (kill-buffer buffer)
946       )))
947
948 (defun mime-editor/insert-signature (&optional arg)
949   "Insert a signature file specified by mime-signature-file."
950   (interactive "P")
951   (let ((signature
952          (expand-file-name
953           (if arg
954               (read-file-name "Insert your signature: "
955                               (concat signature-file-name "-")
956                               signature-file-name
957                               nil)
958             (signature/get-signature-file-name))))
959         )
960     (if signature-insert-at-eof
961         (goto-char (point-max))
962       )
963     (apply (function mime-editor/insert-tag)
964            (mime-find-file-type signature))
965     (if (file-readable-p signature)
966         (progn
967           (goto-char (point-max))
968           (if (not (bolp))
969               (insert "\n"))
970           (delete-blank-lines)
971           (insert-file-contents signature)
972           (set-buffer-modified-p (buffer-modified-p))
973                                         ; force mode line update
974           ))))
975
976 \f
977 ;; Insert a new tag around a point.
978
979 (defun mime-editor/insert-tag (&optional pritype subtype parameters delimiter)
980   "Insert new MIME tag and return a list of PRITYPE, SUBTYPE, and PARAMETERS.
981 If nothing is inserted, return nil."
982   (interactive)
983   (let ((oldtag nil)
984         (newtag nil)
985         (current (point))
986         exist-prev-tag exist-next-tag)
987     (setq pritype
988           (or pritype
989               (mime-prompt-for-type)))
990     (setq subtype
991           (or subtype
992               (mime-prompt-for-subtype pritype)))
993     (setq parameters
994           (or parameters
995               (mime-prompt-for-parameters pritype subtype delimiter)))
996     ;; Make a new MIME tag.
997     (setq newtag (mime-make-tag pritype subtype parameters))
998     ;; Find an current MIME tag.
999     (setq oldtag
1000           (save-excursion
1001             (if (mime-editor/goto-tag)
1002                 (progn
1003                   (if (eq current (match-beginning 0))
1004                       (setq exist-next-tag t)
1005                     (setq exist-prev-tag t)
1006                     )
1007                   (buffer-substring (match-beginning 0) (match-end 0))
1008                   )
1009               ;; Assume content type is 'text/plan'.
1010               (mime-make-tag "text" "plain")
1011               )))
1012     ;; We are only interested in TEXT.
1013     (if (and oldtag
1014              (not (mime-test-content-type
1015                    (mime-editor/get-contype oldtag) "text")))
1016         (setq oldtag nil))
1017     (cond (exist-prev-tag (insert "\n"))
1018           (exist-next-tag (save-excursion
1019                             (insert "\n")
1020                             )))
1021     (if (not (bolp))
1022         (if exist-prev-tag
1023             (forward-line 1)
1024           (insert "\n")
1025           ))
1026     ;; Make a new tag.
1027     (if (or (not oldtag)                ;Not text
1028             (or mime-ignore-same-text-tag
1029                 (not (string-equal oldtag newtag))))
1030         (progn
1031           ;; Mark the beginning of the tag for convenience.
1032           (push-mark (point) 'nomsg)
1033           (insert newtag "\n")
1034           (list pritype subtype parameters) ;New tag is created.
1035           )
1036       ;; Restore previous point.
1037       (goto-char current)
1038       nil                               ;Nothing is created.
1039       )
1040     ))
1041
1042 ;; Insert the binary content after MIME tag.
1043 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
1044 ;;      for x-uue
1045 (defun mime-editor/insert-binary-file (file &optional encoding)
1046   "Insert binary FILE at point.
1047 Optional argument ENCODING specifies an encoding method such as base64."
1048   (let ((tmpbuf (get-buffer-create " *MIME insert*")))
1049     (save-excursion
1050       (set-buffer tmpbuf)
1051       (erase-buffer)
1052       (let ((mc-flag nil)               ;Mule
1053             (file-coding-system-for-read
1054              (if (featurep 'mule) *noconv*))
1055             (kanji-flag nil)            ;NEmacs
1056             (emx-binary-mode t)         ;Stop CRLF to LF conversion in OS/2
1057             )
1058         (let (jka-compr-compression-info-list
1059               jam-zcat-filename-list)
1060           (insert-file-contents file))))
1061     (prog1
1062         (if (and (stringp encoding)
1063                  (string-equal (downcase encoding) "x-uue"))
1064             (progn
1065               (require 'mel-u)
1066               (let ((uuencode-external-encoder
1067                      (cons (car uuencode-external-encoder)
1068                            (list (file-name-nondirectory file))
1069                            )))
1070                 (mime-editor/insert-binary-buffer tmpbuf encoding)
1071                 ))
1072           (mime-editor/insert-binary-buffer tmpbuf encoding))
1073       (kill-buffer tmpbuf))))
1074
1075 ;; Insert the binary content after MIME tag.
1076 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
1077 ;;      for x-uue
1078 (defun mime-editor/insert-binary-buffer (buffer &optional encoding)
1079   "Insert binary BUFFER at point.
1080 Optional argument ENCODING specifies an encoding method such as base64."
1081   (let* ((tagend (1- (point)))          ;End of the tag
1082          (hide-p (and mime-auto-hide-body
1083                       (stringp encoding)
1084                       (let ((en (downcase encoding)))
1085                         (or (string-equal en "base64")
1086                             (string-equal en "x-uue")
1087                             ))))
1088          )
1089     (save-restriction
1090       (narrow-to-region (1- (point)) (point))
1091       (let ((start (point))
1092             (emx-binary-mode t))        ;Stop LF to CRLF conversion in OS/2
1093         (insert-buffer-substring buffer)
1094         ;; Encode binary message if necessary.
1095         (if encoding
1096             (mime-encode-region encoding start (point-max))))
1097       (if hide-p
1098           (progn
1099             (mime-flag-region (point-min) (1- (point-max)) ?\^M)
1100             (goto-char (point-max)))
1101         ))
1102     ;; Define encoding even if it is 7bit.
1103     (if (stringp encoding)
1104         (save-excursion
1105           (goto-char tagend)            ;Make sure which line the tag is on.
1106           (mime-editor/define-encoding encoding)))
1107     ))
1108
1109 \f
1110 ;; Commands work on a current message flagment.
1111
1112 (defun mime-editor/goto-tag ()
1113   "Search for the beginning of the tagged MIME message."
1114   (let ((current (point)) multipart)
1115     (if (looking-at mime-editor/tag-regexp)
1116         t
1117       ;; At first, go to the end.
1118       (cond ((re-search-forward mime-editor/beginning-tag-regexp nil t)
1119              (goto-char (match-beginning 0)) ;For multiline tag
1120              (forward-line -1)
1121              (end-of-line)
1122              )
1123             (t
1124              (goto-char (point-max))
1125              ))
1126       ;; Then search for the beginning. 
1127       (re-search-backward mime-editor/end-tag-regexp nil t)
1128       (beginning-of-line)
1129       (or (looking-at mime-editor/beginning-tag-regexp)
1130           ;; Restore previous point.
1131           (progn
1132             (goto-char current)
1133             nil
1134             ))
1135       )))
1136
1137 (defun mime-editor/content-beginning ()
1138   "Return the point of the beginning of content."
1139   (save-excursion
1140     (let ((beg (save-excursion
1141                  (beginning-of-line) (point))))
1142       (if (mime-editor/goto-tag)
1143           (let ((top (point)))
1144             (goto-char (match-end 0))
1145             (if (and (= beg top)
1146                      (= (following-char) ?\^M))
1147                 (point)
1148               (forward-line 1)
1149               (point)))
1150         ;; Default text/plain tag.
1151         (goto-char (point-min))
1152         (re-search-forward
1153          (concat "\n" (regexp-quote mail-header-separator)
1154                  (if mime-ignore-preceding-spaces
1155                      "[ \t\n]*\n" "\n")) nil 'move)
1156         (point))
1157       )))
1158
1159 (defun mime-editor/content-end ()
1160   "Return the point of the end of content."
1161   (save-excursion
1162     (let ((beg (save-excursion
1163                  (beginning-of-line) (point))))
1164       (if (mime-editor/goto-tag)
1165           (let ((top (point)))
1166             (goto-char (match-end 0))
1167             (if (and (= beg top)        ;Must be on the same line.
1168                      (= (following-char) ?\^M))
1169                 (progn
1170                   (end-of-line)
1171                   (point))
1172               ;; Move to the end of this text.
1173               (if (re-search-forward mime-editor/tag-regexp nil 'move)
1174                   ;; Don't forget a multiline tag.
1175                   (goto-char (match-beginning 0)))
1176               (point)
1177               ))
1178         ;; Assume the message begins with text/plain.
1179         (goto-char (mime-editor/content-beginning))
1180         (if (re-search-forward mime-editor/tag-regexp nil 'move)
1181             ;; Don't forget a multiline tag.
1182             (goto-char (match-beginning 0)))
1183         (point))
1184       )))
1185
1186 (defun mime-editor/define-charset (charset)
1187   "Set charset of current tag to CHARSET."
1188   (save-excursion
1189     (if (mime-editor/goto-tag)
1190         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1191           (delete-region (match-beginning 0) (match-end 0))
1192           (insert
1193            (mime-create-tag (mime-set-parameter
1194                              (mime-editor/get-contype tag) "charset" charset)
1195                             (mime-editor/get-encoding tag))))
1196       )))
1197
1198 (defun mime-editor/define-encoding (encoding)
1199   "Set encoding of current tag to ENCODING."
1200   (save-excursion
1201     (if (mime-editor/goto-tag)
1202         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1203           (delete-region (match-beginning 0) (match-end 0))
1204           (insert (mime-create-tag (mime-editor/get-contype tag) encoding)))
1205       )))
1206
1207 (defun mime-editor/choose-charset ()
1208   "Choose charset of a text following current point."
1209   (mime/find-charset-region (point) (mime-editor/content-end))
1210   )
1211
1212 (defun mime-make-text-tag (&optional subtype)
1213   "Make a tag for a text after current point.
1214 Subtype of text type can be specified by an optional argument SUBTYPE.
1215 Otherwise, it is obtained from mime-content-types."
1216   (let* ((pritype "text")
1217          (subtype (or subtype
1218                       (car (car (cdr (assoc pritype mime-content-types)))))))
1219     ;; Charset should be defined later.
1220     (mime-make-tag pritype subtype)))
1221
1222 \f
1223 ;; Tag handling functions
1224
1225 (defun mime-make-tag (pritype subtype &optional parameters encoding)
1226   "Make a tag of MIME message of PRITYPE, SUBTYPE and optional PARAMETERS."
1227   (mime-create-tag (concat (or pritype "") "/" (or subtype "")
1228                            (or parameters ""))
1229                    encoding))
1230
1231 (defun mime-create-tag (contype &optional encoding)
1232   "Make a tag with CONTENT-TYPE and optional ENCODING."
1233   (format (if encoding mime-tag-format-with-encoding mime-tag-format)
1234           contype encoding))
1235
1236 (defun mime-editor/get-contype (tag)
1237   "Return Content-Type (including parameters) of TAG."
1238   (and (stringp tag)
1239        (or (string-match mime-editor/single-part-tag-regexp tag)
1240            (string-match mime-editor/multipart-beginning-regexp tag)
1241            (string-match mime-editor/multipart-end-regexp tag)
1242            )
1243        (substring tag (match-beginning 1) (match-end 1))
1244        ))
1245
1246 (defun mime-editor/get-encoding (tag)
1247   "Return encoding of TAG."
1248   (and (stringp tag)
1249        (string-match mime-editor/single-part-tag-regexp tag)
1250        (match-beginning 3)
1251        (not (= (match-beginning 3) (match-end 3)))
1252        (substring tag (match-beginning 3) (match-end 3))))
1253
1254 (defun mime-get-parameter (contype parameter)
1255   "For given CONTYPE return value for PARAMETER.
1256 Nil if no such parameter."
1257   (if (string-match
1258        (concat
1259         ";[ \t\n]*"
1260         (regexp-quote parameter)
1261         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\([ \t\n]*;\\|$\\)")
1262        contype)
1263       (substring contype (match-beginning 1) (match-end 1))
1264     nil                                 ;No such parameter
1265     ))
1266
1267 (defun mime-set-parameter (contype parameter value)
1268   "For given CONTYPE set PARAMETER to VALUE."
1269   (if (string-match
1270        (concat
1271         ";[ \t\n]*\\("
1272         (regexp-quote parameter)
1273         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\)[ \t\n]*\\(;\\|$\\)")
1274        contype)
1275       ;; Change value
1276       (concat (substring contype 0 (match-beginning 1))
1277               parameter "=" value
1278               (substring contype (match-end 1)))
1279     (concat contype "; " parameter "=" value)))
1280
1281 (defun mime-strip-parameters (contype)
1282   "Return primary content-type and subtype without parameters for CONTYPE."
1283   (if (string-match "^[ \t]*\\([^; \t\n]*\\)" contype)
1284       (substring contype (match-beginning 1) (match-end 1)) nil))
1285
1286 (defun mime-test-content-type (contype type &optional subtype)
1287   "Test if CONTYPE is a TYPE and an optional SUBTYPE."
1288   (and (stringp contype)
1289        (stringp type)
1290        (string-match
1291         (concat "^[ \t]*" (downcase type) "/" (downcase (or subtype "")))
1292         (downcase contype))))
1293
1294 \f
1295 ;; Basic functions
1296
1297 (defun mime-find-file-type (file)
1298   "Guess Content-Type, subtype, and parameters from FILE."
1299   (let ((guess nil)
1300         (guesses mime-file-types))
1301     (while (and (not guess) guesses)
1302       (if (string-match (car (car guesses)) file)
1303           (setq guess (cdr (car guesses))))
1304       (setq guesses (cdr guesses)))
1305     guess
1306     ))
1307
1308 (defun mime-prompt-for-type ()
1309   "Ask for Content-type."
1310   (let ((type ""))
1311     ;; Repeat until primary content type is specified.
1312     (while (string-equal type "")
1313       (setq type
1314             (completing-read "What content type: "
1315                              mime-content-types
1316                              nil
1317                              'require-match ;Type must be specified.
1318                              nil
1319                              ))
1320       (if (string-equal type "")
1321           (progn
1322             (message "Content type is required.")
1323             (beep)
1324             (sit-for 1)
1325             ))
1326       )
1327     type
1328     ))
1329
1330 (defun mime-prompt-for-subtype (pritype)
1331   "Ask for Content-type subtype of Content-Type PRITYPE."
1332   (let* ((default (car (car (cdr (assoc pritype mime-content-types)))))
1333          (answer
1334           (completing-read
1335            (if default
1336                (concat
1337                 "What content subtype: (default " default ") ")
1338              "What content subtype: ")
1339            (cdr (assoc pritype mime-content-types))
1340            nil
1341            'require-match               ;Subtype must be specified.
1342            nil
1343            )))
1344     (if (string-equal answer "") default answer)))
1345
1346 (defun mime-prompt-for-parameters (pritype subtype &optional delimiter)
1347   "Ask for Content-type parameters of Content-Type PRITYPE and SUBTYPE.
1348 Optional DELIMITER specifies parameter delimiter (';' by default)."
1349   (let* ((delimiter (or delimiter "; "))
1350          (parameters
1351           (mapconcat
1352            (function identity)
1353            (delq nil
1354                  (mime-prompt-for-parameters-1
1355                   (cdr (assoc subtype
1356                               (cdr (assoc pritype mime-content-types))))))
1357            delimiter
1358            )))
1359     (if (and (stringp parameters)
1360              (not (string-equal parameters "")))
1361         (concat delimiter parameters)
1362       ""                                ;"" if no parameters
1363       )))
1364
1365 (defun mime-prompt-for-parameters-1 (optlist)
1366   (apply (function append)
1367          (mapcar (function mime-prompt-for-parameter) optlist)))
1368
1369 (defun mime-prompt-for-parameter (parameter)
1370   "Ask for PARAMETER.
1371 Parameter must be '(PROMPT CHOICE1 (CHOISE2 ...))."
1372   (let* ((prompt (car parameter))
1373          (choices (mapcar (function
1374                            (lambda (e)
1375                              (if (consp e) e (list e))))
1376                           (cdr parameter)))
1377          (default (car (car choices)))
1378          (answer nil))
1379     (if choices
1380         (progn
1381           (setq answer
1382                 (completing-read
1383                  (concat "What " prompt
1384                          ": (default "
1385                          (if (string-equal default "") "\"\"" default)
1386                          ") ")
1387                  choices nil nil ""))
1388           ;; If nothing is selected, use default.
1389           (if (string-equal answer "")
1390               (setq answer default)))
1391       (setq answer
1392             (read-string (concat "What " prompt ": "))))
1393     (cons (if (and answer
1394                    (not (string-equal answer "")))
1395               (concat prompt "="
1396                       ;; Note: control characters ignored!
1397                       (if (string-match mime-tspecials-regexp answer)
1398                           (concat "\"" answer "\"") answer)))
1399           (mime-prompt-for-parameters-1 (cdr (assoc answer (cdr parameter)))))
1400     ))
1401
1402 (defun mime-encode-string (encoding string)
1403   "Using ENCODING encode a STRING.
1404 If the STRING is too long, the encoded string may be broken into
1405 several lines."
1406   (save-excursion
1407     (set-buffer (get-buffer-create " *MIME encoding*"))
1408     (erase-buffer)
1409     (insert string)
1410     (mime-encode-region encoding (point-min) (point-max))
1411     (prog1
1412         (buffer-substring (point-min) (point-max))
1413       (kill-buffer (current-buffer)))))
1414
1415 (defun mime-decode-string (encoding string)
1416   "Using ENCODING decode a STRING."
1417   (save-excursion
1418     (set-buffer (get-buffer-create " *MIME decoding*"))
1419     (erase-buffer)
1420     (insert string)
1421     (mime-decode-region encoding (point-min) (point-max))
1422     (prog1
1423         (buffer-substring (point-min) (point-max))
1424       (kill-buffer (current-buffer)))))
1425
1426 (defun mime-flag-region (from to flag)
1427   "Hides or shows lines from FROM to TO, according to FLAG.
1428 If FLAG is `\\n' (newline character) then text is shown,
1429 while if FLAG is `\\^M' (control-M) the text is hidden."
1430   (let ((buffer-read-only nil)          ;Okay even if write protected.
1431         (modp (buffer-modified-p)))
1432     (unwind-protect
1433         (subst-char-in-region from to
1434                               (if (= flag ?\n) ?\^M ?\n)
1435                               flag t)
1436       (set-buffer-modified-p modp))))
1437
1438 \f
1439 ;;; @ Translate the tagged MIME messages into a MIME compliant message.
1440 ;;;
1441
1442 (defun mime-editor/translate-buffer ()
1443   "Encode the tagged MIME message in current buffer in MIME compliant message."
1444   (interactive)
1445   (if (catch 'mime-editor/error
1446         (save-excursion
1447           (mime-editor/pgp-enclose-buffer)
1448           (mime/encode-message-header)
1449           (mime-editor/translate-body)
1450           ))
1451       (progn
1452         (undo)
1453         (error "Translation error!")
1454         )))
1455
1456 (defun mime-editor/find-inmost ()
1457   (goto-char (point-min))
1458   (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1459       (let ((bb (match-beginning 0))
1460             (be (match-end 0))
1461             (type (buffer-substring (match-beginning 1)(match-end 1)))
1462             end-exp eb ee)
1463         (setq end-exp (format "^--}-<<%s>>\n" type))
1464         (widen)
1465         (if (re-search-forward end-exp nil t)
1466             (progn
1467               (setq eb (match-beginning 0))
1468               (setq ee (match-end 0))
1469               )
1470           (setq eb (point-max))
1471           (setq ee (point-max))
1472           )
1473         (narrow-to-region be eb)
1474         (goto-char be)
1475         (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1476             (let (ret)
1477               (narrow-to-region (match-beginning 0)(point-max))
1478               (mime-editor/find-inmost)
1479               )
1480           (widen)
1481           ;;(delete-region eb ee)
1482           (list type bb be eb)
1483           ))))
1484
1485 (defun mime-editor/process-multipart-1 (boundary)
1486   (let ((ret (mime-editor/find-inmost)))
1487     (if ret
1488         (let ((type (car ret))
1489               (bb (nth 1 ret))(be (nth 2 ret))
1490               (eb (nth 3 ret))
1491               )
1492           (narrow-to-region bb eb)
1493           (delete-region bb be)
1494           (setq bb (point-min))
1495           (setq eb (point-max))
1496           (widen)
1497           (goto-char eb)
1498           (if (looking-at mime-editor/multipart-end-regexp)
1499               (let ((beg (match-beginning 0))
1500                     (end (match-end 0))
1501                     )
1502                 (delete-region beg end)
1503                 (if (and (not (looking-at mime-editor/single-part-tag-regexp))
1504                          (not (eobp)))
1505                     (insert (concat (mime-make-text-tag) "\n"))
1506                   )))
1507           (cond ((string= type "signed")
1508                  (cond ((eq mime-editor/signing-type 'pgp-elkins)
1509                         (mime-editor/sign-pgp-elkins bb eb boundary)
1510                         )
1511                        ((eq mime-editor/signing-type 'pgp-kazu)
1512                         (mime-editor/process-pgp-kazu 'mc-sign
1513                                                       bb eb boundary)
1514                         )
1515                        ))
1516                 ((string= type "encrypted")
1517                  (cond ((eq mime-editor/signing-type 'pgp-elkins)
1518                         (mime-editor/encrypt-pgp-elkins bb eb boundary)
1519                         )
1520                        ((eq mime-editor/signing-type 'pgp-kazu)
1521                         (mime-editor/process-pgp-kazu 'mc-encrypt
1522                                                       bb eb boundary)
1523                         )))
1524                 (t
1525                  (setq boundary
1526                        (nth 2 (mime-editor/translate-region bb eb
1527                                                             boundary t)))
1528                  (goto-char bb)
1529                  (insert
1530                   (format "--[[multipart/%s;
1531  boundary=\"%s\"][7bit]]\n"
1532                           type boundary))
1533                  ))
1534           boundary))))
1535
1536 (defun tm:mc-pgp-generic-parser (result)
1537   (let ((ret (mc-pgp-generic-parser result)))
1538     (if (consp ret)
1539         (vector (car ret)(cdr ret))
1540       )))
1541
1542 (autoload 'mc-pgp-lookup-key "mc-pgp")
1543
1544 (defun tm:mc-process-region
1545   (beg end passwd program args parser &optional buffer boundary)
1546   (let ((obuf (current-buffer))
1547         (process-connection-type nil)
1548         mybuf result rgn proc)
1549     (unwind-protect
1550         (progn
1551           (setq mybuf (or buffer (generate-new-buffer " *mailcrypt temp")))
1552           (set-buffer mybuf)
1553           (erase-buffer)
1554           (set-buffer obuf)
1555           (buffer-disable-undo mybuf)
1556           (setq proc
1557                 (apply 'start-process "*PGP*" mybuf program args))
1558           (if passwd
1559               (progn
1560                 (process-send-string proc (concat passwd "\n"))
1561                 (or mc-passwd-timeout (mc-deactivate-passwd t))))
1562           (process-send-region proc beg end)
1563           (process-send-eof proc)
1564           (while (eq 'run (process-status proc))
1565             (accept-process-output proc 5))
1566           (setq result (process-exit-status proc))
1567           ;; Hack to force a status_notify() in Emacs 19.29
1568           (delete-process proc)
1569           (set-buffer mybuf)
1570           (goto-char (point-max))
1571           (if (re-search-backward "\nProcess \\*PGP.*\n\\'" nil t)
1572               (delete-region (match-beginning 0) (match-end 0)))
1573           (goto-char (point-min))
1574           ;; CRNL -> NL
1575           (while (search-forward "\r\n" nil t)
1576             (replace-match "\n"))
1577           ;; Hurm.  FIXME; must get better result codes.
1578           (if (stringp result)
1579               (error "%s exited abnormally: '%s'" program result)
1580             (setq rgn (funcall parser result))
1581             ;; If the parser found something, migrate it
1582             (if (consp rgn)
1583                 (progn
1584                   (set-buffer obuf)
1585                   (if boundary
1586                       (save-restriction
1587                         (narrow-to-region beg end)
1588                         (goto-char beg)
1589                         (insert (format "--%s\n" boundary))
1590                         (goto-char (point-max))
1591                         (insert (format "\n--%s
1592 Content-Type: application/pgp-signature
1593 Content-Transfer-Encoding: 7bit
1594
1595 " boundary))
1596                         (insert-buffer-substring mybuf (car rgn) (cdr rgn))
1597                         (goto-char (point-max))
1598                         (insert (format "\n--%s--\n" boundary))
1599                         )
1600                     (delete-region beg end)
1601                     (goto-char beg)
1602                     (insert-buffer-substring mybuf (car rgn) (cdr rgn))
1603                     )
1604                   (set-buffer mybuf)
1605                   (delete-region (car rgn) (cdr rgn)))))
1606           ;; Return nil on failure and exit code on success
1607           (if rgn result))
1608       ;; Cleanup even on nonlocal exit
1609       (if (and proc (eq 'run (process-status proc)))
1610           (interrupt-process proc))
1611       (set-buffer obuf)
1612       (or buffer (null mybuf) (kill-buffer mybuf)))))
1613
1614 (defun tm:mc-pgp-sign-region (start end &optional id unclear boundary)
1615   (if (not (boundp 'mc-pgp-user-id))
1616       (load "mc-pgp")
1617     )
1618   (let ((process-environment process-environment)
1619         (buffer (get-buffer-create mc-buffer-name))
1620         passwd args key
1621         (parser (function mc-pgp-generic-parser))
1622         (pgp-path mc-pgp-path)
1623         )
1624     (setq key (mc-pgp-lookup-key (or id mc-pgp-user-id)))
1625     (setq passwd
1626           (mc-activate-passwd
1627            (cdr key)
1628            (format "PGP passphrase for %s (%s): " (car key) (cdr key))))
1629     (setenv "PGPPASSFD" "0")
1630     (setq args
1631           (cons
1632            (if boundary
1633                "-fbast"
1634              "-fast")
1635            (list "+verbose=1" "+language=en"
1636                  (format "+clearsig=%s" (if unclear "off" "on"))
1637                  "+batchmode" "-u" (cdr key))))
1638     (if mc-pgp-comment
1639         (setq args (cons (format "+comment=%s" mc-pgp-comment) args))
1640       )
1641     (message "Signing as %s ..." (car key))
1642     (if (tm:mc-process-region
1643          start end passwd pgp-path args parser buffer boundary)
1644         (progn
1645           (if boundary
1646               (progn
1647                 (goto-char (point-min))
1648                 (insert
1649                  (format "\
1650 --[[multipart/signed; protocol=\"application/pgp-signature\";
1651  boundary=\"%s\"; micalg=pgp-md5][7bit]]\n" boundary))
1652                 ))
1653           (message "Signing as %s ... Done." (car key))
1654           t)
1655       nil)))
1656
1657 (defun mime-editor/sign-pgp-elkins (beg end boundary)
1658   (save-excursion
1659     (save-restriction
1660       (narrow-to-region beg end)
1661       (let* ((ret
1662               (mime-editor/translate-region beg end boundary))
1663              (ctype    (car ret))
1664              (encoding (nth 1 ret))
1665              (parts    (nth 3 ret))
1666              (pgp-boundary (concat "pgp-sign-" boundary))
1667              )
1668         (goto-char beg)
1669         (insert (format "Content-Type: %s\n" ctype))
1670         (if encoding
1671             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1672           )
1673         (insert "\n")
1674         (or (tm:mc-pgp-sign-region (point-min)(point-max)
1675                                    nil nil pgp-boundary)
1676             (throw 'mime-editor/error 'pgp-error)
1677             )
1678         ))))
1679
1680 (autoload 'mc-pgp-encrypt-region "mc-pgp")
1681
1682 (defun mime-editor/encrypt-pgp-elkins (beg end boundary)
1683   (save-excursion
1684     (save-restriction
1685       (let ((from (rfc822/get-field-body "From"))
1686             (to (rfc822/get-field-body "To"))
1687             (cc (rfc822/get-field-body "cc"))
1688             recipients)
1689         (narrow-to-region beg end)
1690         (let* ((ret
1691                 (mime-editor/translate-region beg end boundary))
1692                (ctype    (car ret))
1693                (encoding (nth 1 ret))
1694                (parts    (nth 3 ret))
1695                (pgp-boundary (concat "pgp-" boundary))
1696                )
1697           (goto-char beg)
1698           (if (and (stringp from)
1699                    (not (string-equal from "")))
1700               (insert (format "From: %s\n" from))
1701             )
1702           (if (and (stringp to)
1703                    (not (string-equal to "")))
1704               (progn
1705                 (insert (format "To: %s\n" to))
1706                 (setq recipients to)
1707                 ))
1708           (if (and (stringp cc)
1709                    (not (string-equal cc "")))
1710               (progn
1711                 (insert (format "cc: %s\n" cc))
1712                 (if recipients
1713                     (setq recipients (concat recipients "," cc))
1714                   (setq recipients cc)
1715                   )))
1716           (insert (format "Content-Type: %s\n" ctype))
1717           (if encoding
1718               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1719             )
1720           (insert "\n")
1721           (if (null
1722                (let ((mc-pgp-always-sign 'never))
1723                  (mc-pgp-encrypt-region
1724                   (mc-split "\\([ \t\n]*,[ \t\n]*\\)+" recipients)
1725                   (point-min) (point-max) from nil)
1726                  ))
1727               (throw 'mime-editor/error 'pgp-error)
1728             )
1729           (goto-char beg)
1730           (insert (format "--[[multipart/encrypted;
1731  boundary=\"%s\";
1732  protocol=\"application/pgp-encrypted\"][7bit]]
1733 --%s
1734 Content-Type: application/pgp-encrypted
1735
1736 --%s
1737 Content-Type: application/octet-stream
1738 Content-Transfer-Encoding: 7bit
1739
1740 " pgp-boundary pgp-boundary pgp-boundary))
1741           (goto-char (point-max))
1742           (insert (format "\n--%s--\n" pgp-boundary))
1743           )))))
1744
1745 (defun mime-editor/process-pgp-kazu (type beg end boundary)
1746   (save-excursion
1747     (save-restriction
1748       (narrow-to-region beg end)
1749       (let* ((ret
1750               (mime-editor/translate-region beg end boundary))
1751              (ctype    (car ret))
1752              (encoding (nth 1 ret))
1753              (parts    (nth 3 ret))
1754              )
1755         (goto-char beg)
1756         (insert (format "Content-Type: %s\n" ctype))
1757         (if encoding
1758             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1759           )
1760         (insert "\n")
1761         (if (null
1762              (progn
1763                (goto-char beg)
1764                (insert "=\n")
1765                (prog1
1766                    (let ((mail-header-separator "="))
1767                      (call-interactively type)
1768                      )
1769                  (goto-char beg)
1770                  (and (search-forward "=\n")
1771                       (replace-match ""))
1772                  )))
1773             (throw 'mime-editor/error 'pgp-error)
1774           )
1775         (goto-char beg)
1776         (insert
1777          "--[[application/pgp; format=mime][7bit]]\n")
1778         ))
1779     ))
1780
1781 (defun mime-editor/translate-body ()
1782   "Encode the tagged MIME body in current buffer in MIME compliant message."
1783   (interactive)
1784   (save-excursion
1785     (let ((boundary
1786            (concat mime-multipart-boundary "_"
1787                    (replace-space-with-underline (current-time-string))
1788                    ))
1789           (i 1)
1790           ret)
1791       (while (mime-editor/process-multipart-1
1792               (format "%s-%d" boundary i))
1793         (setq i (1+ i))
1794         )
1795       (save-restriction
1796         ;; We are interested in message body.
1797         (let* ((beg
1798                 (progn
1799                   (goto-char (point-min))
1800                   (re-search-forward
1801                    (concat "\n" (regexp-quote mail-header-separator)
1802                            (if mime-ignore-preceding-spaces
1803                                "[ \t\n]*\n" "\n")) nil 'move)
1804                   (point)))
1805                (end
1806                 (progn
1807                   (goto-char (point-max))
1808                   (and mime-ignore-trailing-spaces
1809                        (re-search-backward "[^ \t\n]\n" beg t)
1810                        (forward-char 1))
1811                   (point))))
1812           (setq ret (mime-editor/translate-region
1813                      beg end
1814                      (format "%s-%d" boundary i)))
1815           ))
1816       (let ((contype (car ret))         ;Content-Type
1817             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1818             )
1819         ;; Make primary MIME headers.
1820         (or (mail-position-on-field "Mime-Version")
1821             (insert mime-editor/mime-version-value))
1822         ;; Remove old Content-Type and other fields.
1823         (save-restriction
1824           (goto-char (point-min))
1825           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1826           (narrow-to-region (point-min) (point))
1827           (goto-char (point-min))
1828           (mime-delete-field "Content-Type")
1829           (mime-delete-field "Content-Transfer-Encoding"))
1830         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1831         (mail-position-on-field "Content-Type")
1832         (insert contype)
1833         (if encoding
1834             (progn
1835               (mail-position-on-field "Content-Transfer-Encoding")
1836               (insert encoding)))
1837         ))))
1838
1839 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1840   (if (null boundary)
1841       (setq boundary
1842             (concat mime-multipart-boundary "_"
1843                     (replace-space-with-underline (current-time-string))))
1844     )
1845   (save-excursion
1846     (save-restriction
1847       (narrow-to-region beg end)
1848       (let ((tag nil)                   ;MIME tag
1849             (contype nil)               ;Content-Type
1850             (encoding nil)              ;Content-Transfer-Encoding
1851             (nparts 0))                 ;Number of body parts
1852         ;; Normalize the body part by inserting appropriate message
1853         ;; tags for every message contents.
1854         (mime-editor/normalize-body)
1855         ;; Counting the number of Content-Type.
1856         (goto-char (point-min))
1857         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1858           (setq nparts (1+ nparts)))
1859         ;; Begin translation.
1860         (cond ((and (<= nparts 1)(not multipart))
1861                ;; It's a singular message.
1862                (goto-char (point-min))
1863                (while (re-search-forward
1864                        mime-editor/single-part-tag-regexp nil t)
1865                  (setq tag
1866                        (buffer-substring (match-beginning 0) (match-end 0)))
1867                  (delete-region (match-beginning 0) (1+ (match-end 0)))
1868                  (setq contype (mime-editor/get-contype tag))
1869                  (setq encoding (mime-editor/get-encoding tag))
1870                  ))
1871               (t
1872                ;; It's a multipart message.
1873                (goto-char (point-min))
1874                (while (re-search-forward
1875                        mime-editor/single-part-tag-regexp nil t)
1876                  (setq tag
1877                        (buffer-substring (match-beginning 0) (match-end 0)))
1878                  (delete-region (match-beginning 0) (match-end 0))
1879                  (setq contype (mime-editor/get-contype tag))
1880                  (setq encoding (mime-editor/get-encoding tag))
1881                  (insert "--" boundary "\n")
1882                  (insert "Content-Type: " contype "\n")
1883                  (if encoding
1884                      (insert "Content-Transfer-Encoding: " encoding "\n"))
1885                  )
1886                ;; Define Content-Type as "multipart/mixed".
1887                (setq contype
1888                      (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1889                ;; Content-Transfer-Encoding must be "7bit".
1890                ;; The following encoding can be `nil', but is
1891                ;; specified as is since there is no way that a user
1892                ;; specifies it.
1893                (setq encoding "7bit")
1894                ;; Insert the trailer.
1895                (goto-char (point-max))
1896                (if multipart
1897                    (insert "--" boundary "--\n")
1898                  (insert "\n--" boundary "--\n")
1899                  )))
1900         (list contype encoding boundary nparts)
1901         ))))
1902
1903 (defun mime-editor/normalize-body ()
1904   "Normalize the body part by inserting appropriate message tags."
1905   ;; Insert the first MIME tags if necessary.
1906   (goto-char (point-min))
1907   (if (not (looking-at mime-editor/single-part-tag-regexp))
1908       (insert (mime-make-text-tag) "\n"))
1909   ;; Check each tag, and add new tag or correct it if necessary.
1910   (goto-char (point-min))
1911   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1912     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1913            (contype (mime-editor/get-contype tag))
1914            (charset (mime-get-parameter contype "charset"))
1915            (encoding (mime-editor/get-encoding tag)))
1916       ;; Remove extra whitespaces after the tag.
1917       (if (looking-at "[ \t]+$")
1918           (delete-region (match-beginning 0) (match-end 0)))
1919       (cond ((= (following-char) ?\^M)
1920              ;; It must be image, audio or video.
1921              (let ((beg (point))
1922                    (end (mime-editor/content-end)))
1923                ;; Insert explicit MIME tags after hidden messages.
1924                (forward-line 1)
1925                (if (and (not (eobp))
1926                         (not (looking-at mime-editor/single-part-tag-regexp)))
1927                    (progn
1928                      (insert (mime-make-text-tag) "\n")
1929                      (forward-line -1)  ;Process it again as text.
1930                      ))
1931                ;; Show a hidden message.  The point is not altered
1932                ;; after the conversion.
1933                (mime-flag-region beg end ?\n)))
1934             ((mime-test-content-type contype "message")
1935              ;; Content-type "message" should be sent as is.
1936              (forward-line 1))
1937             ((mime-test-content-type contype "text")
1938              ;; Define charset for text if necessary.
1939              (setq charset (or charset (mime-editor/choose-charset)))
1940              (mime-editor/define-charset charset)
1941              (if (string-equal contype "text/x-rot13-47")
1942                  (save-excursion
1943                    (forward-line)
1944                    (set-mark (point))
1945                    (goto-char (mime-editor/content-end))
1946                    (tm:caesar-region)
1947                    ))
1948              ;; Point is now on current tag.
1949              ;; Define encoding and encode text if necessary.
1950              (if (null encoding)        ;Encoding is not specified.
1951                  (let* ((encoding
1952                          (cdr
1953                           (assoc charset mime/charset-default-encoding-alist)
1954                           ))
1955                         (beg (mime-editor/content-beginning))
1956                         (end (mime-editor/content-end))
1957                         (body (buffer-substring beg end))
1958                         (encoded (funcall mime-string-encoder
1959                                           (cons charset encoding) body)))
1960                    (if (not (string-equal body encoded))
1961                        (progn
1962                          (goto-char beg)
1963                          (delete-region beg end)
1964                          (insert encoded)
1965                          (goto-char beg)))
1966                    (mime-editor/define-encoding encoding)))
1967              (forward-line 1))
1968             ((null encoding)            ;Encoding is not specified.
1969              ;; Application, image, audio, video, and any other
1970              ;; unknown content-type without encoding should be
1971              ;; encoded.
1972              (let* ((encoding "base64") ;Encode in BASE64 by default.
1973                     (beg (mime-editor/content-beginning))
1974                     (end (mime-editor/content-end))
1975                     (body (buffer-substring beg end))
1976                     (encoded (funcall mime-string-encoder
1977                                       (cons nil encoding) body)))
1978                (if (not (string-equal body encoded))
1979                    (progn
1980                      (goto-char beg)
1981                      (delete-region beg end)
1982                      (insert encoded)
1983                      (goto-char beg)))
1984                (mime-editor/define-encoding encoding))
1985              (forward-line 1))
1986             )
1987       )))
1988
1989 (defun mime-delete-field (field)
1990   "Delete header FIELD."
1991   (let ((regexp (format "^%s:[ \t]*" field)))
1992     (goto-char (point-min))
1993     (while (re-search-forward regexp nil t)
1994       (delete-region (match-beginning 0)
1995                      (progn (forward-line 1) (point)))
1996       )))
1997
1998 \f
1999 ;;;
2000 ;;; Platform dependent functions
2001 ;;;
2002
2003 ;; Emacs 18 implementations
2004
2005 (defun mime-string-encoder-for-emacs18 (method string)
2006   "For given METHOD that is a cons of charset and encoding, encode a STRING."
2007   (let ((charset (car method))
2008         (encoding (cdr method)))
2009     (cond ((stringp encoding)
2010            (mime-encode-string encoding string))
2011           ;; Return string without any encoding.
2012           (t string)
2013           )))
2014
2015 \f
2016 ;; Emacs 19 implementations
2017
2018 (defun mime-string-encoder-for-emacs19 (method string)
2019   "For given METHOD that is a cons of charset and encoding, encode a STRING."
2020   (let ((charset (car method))
2021         (encoding (cdr method)))
2022     (cond ((stringp encoding)
2023            (mime-encode-string encoding string))
2024           ;; Return string without any encoding.
2025           (t string)
2026           )))
2027
2028 \f
2029 ;; NEmacs implementations
2030
2031 (defun mime-string-encoder-for-nemacs (method string)
2032   "For given METHOD that is a cons of charset and encoding, encode a STRING.
2033 US-ASCII and ISO-2022-JP are supported on NEmacs."
2034   (let ((charset (car method))
2035         (encoding (cdr method)))
2036     (cond ((stringp encoding)
2037            (mime-encode-string encoding
2038                                ;; Convert internal (EUC) to JIS code.
2039                                (convert-string-kanji-code string 3 2)
2040                                ))
2041           ;; NEmacs can convert into ISO-2022-JP automatically,
2042           ;; but can do it myself as follows:
2043           ;;(t (convert-string-kanji-code string 3 2))
2044
2045           ;; Return string without any encoding.
2046           (t string)
2047           )))
2048
2049 \f
2050 ;; Mule implementations
2051 ;; Thanks to contributions by wkenji@flab.fujitsu.co.jp (Kenji
2052 ;; WAKAMIYA) and handa@etl.go.jp (Kenichi Handa).
2053
2054 (defun mime-string-encoder-for-mule (method string)
2055   "For given METHOD that is a cons of charset and encoding, encode a
2056 STRING.  US-ASCII, ISO-8859-* (except for ISO-8859-6), ISO-2022-JP,
2057 ISO-2022-JP-2 and ISO-2022-INT-1 are supported on Mule.  Either of
2058 charset ISO-2022-JP-2 or ISO-2022-INT-1 is used for multilingual
2059 text."
2060   (let* ((charset (car method))
2061          (encoding (cdr method))
2062          (coding-system
2063           (cdr (assoc (and (stringp charset) (upcase charset))
2064                       '(("ISO-8859-1" . *ctext*)
2065                         ("ISO-8859-2" . *iso-8859-2*)
2066                         ("ISO-8859-3" . *iso-8859-3*)
2067                         ("ISO-8859-4" . *iso-8859-4*)
2068                         ("ISO-8859-5" . *iso-8859-5*)
2069                         ;;("ISO-8859-6" . *iso-8859-6*)
2070                         ("ISO-8859-7" . *iso-8859-7*)
2071                         ("ISO-8859-8" . *iso-8859-8*)
2072                         ("ISO-8859-9" . *iso-8859-9*)
2073                         ("ISO-2022-JP" . *junet*)
2074                         ("ISO-2022-JP-2" . *iso-2022-ss2-7*)
2075                         ("ISO-2022-KR" . *korean-mail*)
2076                         ("ISO-2022-INT-1" . *iso-2022-int-1*)
2077                         )))))
2078     ;; In bilingual environment it may be unnecessary to convert the
2079     ;; coding system of the string unless transfer encoding is
2080     ;; required since such conversion may be performed by mule
2081     ;; automatically.
2082     (if (not (null coding-system))
2083         (setq string (code-convert-string string *internal* coding-system)))
2084     (if (stringp encoding)
2085         (setq string (mime-encode-string encoding string)))
2086     string
2087     ))
2088
2089 \f
2090 ;; Sun implementations
2091
2092 (defun mime-voice-recorder-for-sun ()
2093   "Record voice in a buffer using Sun audio device, and return the buffer.
2094 If the environment variable AUDIOHOST is defined, its value is used as
2095 a recording host instead of local host."
2096   (let ((buffer (get-buffer-create " *MIME audio*"))
2097         (host (getenv "AUDIOHOST")))
2098     (message "Start the recording on %s.  Type C-g to finish the recording..."
2099              (or host (system-name)))
2100     (save-excursion
2101       (set-buffer buffer)
2102       (erase-buffer)
2103       (condition-case errorcode
2104           (let ((selective-display nil) ;Disable ^M to nl translation.
2105                 (mc-flag nil)           ;Mule
2106                 (kanji-flag nil))       ;NEmacs
2107             ;; If AUDIOHOST is defined, use the value as recording host.
2108             (cond ((not (null host))
2109                    ;; Disable automatic conversion of coding system if Mule.
2110                    (if (featurep 'mule)
2111                        (define-program-coding-system nil "rsh" *noconv*))
2112                    (call-process "rsh"
2113                                  nil
2114                                  buffer
2115                                  nil
2116                                  host
2117                                  "cat"
2118                                  "/dev/audio"
2119                                  ))
2120                   (t
2121                    ;; Disable automatic conversion of coding system if Mule.
2122                    (if (featurep 'mule)
2123                        (define-program-coding-system nil "cat" *noconv*))
2124                    (call-process "cat"
2125                                  "/dev/audio"
2126                                  buffer
2127                                  nil
2128                                  ))))
2129         (quit (message "Type C-g to finish recording... done.")
2130               buffer                    ;Return the buffer
2131               )))))
2132
2133 \f
2134 ;;; @ Other useful commands.
2135 ;;;
2136
2137 ;; Message forwarding commands as content-type "message/rfc822".
2138
2139 (defun mime-editor/insert-message (&optional message)
2140   (interactive)
2141   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
2142     (if (and inserter (fboundp inserter))
2143         (progn
2144           (mime-editor/insert-tag "message" "rfc822")
2145           (funcall inserter message)
2146           )
2147       (message "Sorry, I don't have message inserter for your MUA.")
2148       )))
2149
2150 (defun mime-editor/insert-mail (&optional message)
2151   (interactive)
2152   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
2153     (if (and inserter (fboundp inserter))
2154         (progn
2155           (mime-editor/insert-tag "message" "rfc822")
2156           (funcall inserter message)
2157           )
2158       (message "Sorry, I don't have mail inserter for your MUA.")
2159       )))
2160
2161 (defun mime-editor/inserted-message-filter ()
2162   (save-excursion
2163     (save-restriction
2164       (let ((header-start (point))
2165             (case-fold-search t)
2166             beg end)
2167         ;; for Emacs 18
2168         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2169         (if (re-search-forward "^$" (mark t))
2170             (narrow-to-region header-start (match-beginning 0))
2171           )
2172         (goto-char header-start)
2173         (while (and (re-search-forward
2174                      mime-editor/yank-ignored-field-regexp nil t)
2175                     (setq beg (match-beginning 0))
2176                     (setq end (1+ (rfc822/field-end)))
2177                     )
2178           (delete-region beg end)
2179           )
2180         ))))
2181
2182
2183 ;;; @ multipart enclosure
2184 ;;;
2185
2186 (defun mime-editor/enclose-region (type beg end)
2187   (save-excursion
2188     (goto-char beg)
2189     (let ((current (point))
2190           exist-prev-tag)
2191       (save-excursion
2192         (if (mime-editor/goto-tag)
2193             (or (eq current (match-beginning 0))
2194                 (setq exist-prev-tag t)
2195                 )))
2196       (save-restriction
2197         (narrow-to-region beg end)
2198         (goto-char beg)
2199         (if exist-prev-tag
2200             (insert "\n")
2201           )
2202         (insert (format "--<<%s>>-{\n" type))
2203         (goto-char (point-max))
2204         (insert (format "\n--}-<<%s>>\n" type))
2205         (goto-char (point-max))
2206         )
2207       (if (and (not (looking-at mime-editor/single-part-tag-regexp))
2208                (not (eobp)))
2209           (insert (mime-make-text-tag) "\n")
2210         )
2211       )))
2212
2213 (defun mime-editor/enclose-mixed-region (beg end)
2214   (interactive "*r")
2215   (mime-editor/enclose-region "mixed" beg end)
2216   )
2217
2218 (defun mime-editor/enclose-parallel-region (beg end)
2219   (interactive "*r")
2220   (mime-editor/enclose-region "parallel" beg end)
2221   )
2222
2223 (defun mime-editor/enclose-digest-region (beg end)
2224   (interactive "*r")
2225   (mime-editor/enclose-region "digest" beg end)
2226   )
2227
2228 (defun mime-editor/enclose-alternative-region (beg end)
2229   (interactive "*r")
2230   (mime-editor/enclose-region "alternative" beg end)
2231   )
2232
2233 (defun mime-editor/enclose-signed-region (beg end)
2234   (interactive "*r")
2235   (if mime-editor/signing-type
2236       (mime-editor/enclose-region "signed" beg end)
2237     (message "Please specify signing type.")
2238     ))
2239
2240 (defun mime-editor/enclose-encrypted-region (beg end)
2241   (interactive "*r")
2242   (if mime-editor/signing-type
2243       (mime-editor/enclose-region "encrypted" beg end)
2244     (message "Please specify encrypting type.")
2245     ))
2246
2247 (defun mime-editor/insert-key (&optional arg)
2248   "Insert a pgp public key."
2249   (interactive "P")
2250   (mime-editor/insert-tag "application" "pgp-keys")
2251   (mime-editor/define-encoding "7bit")
2252   (mc-insert-public-key)
2253   )
2254
2255
2256 ;;; @ flag setting
2257 ;;;
2258
2259 (defun mime-editor/set-split (arg)
2260   (interactive
2261    (list
2262     (y-or-n-p "Do you want to enable split?")
2263     ))
2264   (setq mime-editor/split-message arg)
2265   (if arg
2266       (message "This message is enabled to split.")
2267     (message "This message is not enabled to split.")
2268     ))
2269
2270
2271 ;;; @ pgp
2272 ;;;
2273
2274 (defun mime-editor/set-sign (arg)
2275   (interactive
2276    (list
2277     (y-or-n-p "Do you want to sign?")
2278     ))
2279   (if arg
2280       (if mime-editor/signing-type
2281           (progn
2282             (setq mime-editor/pgp-processing 'sign)
2283             (message "This message will be signed.")
2284             )
2285         (message "Please specify signing type.")
2286         )
2287     (if (eq mime-editor/pgp-processing 'sign)
2288         (setq mime-editor/pgp-processing nil)
2289       )
2290     (message "This message will not be signed.")
2291     ))
2292
2293 (defun mime-editor/set-encrypt (arg)
2294   (interactive
2295    (list
2296     (y-or-n-p "Do you want to encrypt?")
2297     ))
2298   (if arg
2299       (if mime-editor/encrypting-type
2300           (progn
2301             (setq mime-editor/pgp-processing 'encrypt)
2302             (message "This message will be encrypt.")
2303             )
2304         (message "Please specify encrypting type.")
2305         )
2306     (if (eq mime-editor/pgp-processing 'encrypt)
2307         (setq mime-editor/pgp-processing nil)
2308       )
2309     (message "This message will not be encrypt.")
2310     ))
2311
2312 (defvar mime-editor/pgp-processing nil)
2313 (make-variable-buffer-local 'mime-editor/pgp-processing)
2314
2315 (defun mime-editor/pgp-enclose-buffer ()
2316   (let ((beg (save-excursion
2317                (goto-char (point-min))
2318                (if (search-forward (concat "\n" mail-header-separator "\n"))
2319                    (match-end 0)
2320                  )))
2321         (end (point-max))
2322         )
2323     (if beg
2324         (cond ((eq mime-editor/pgp-processing 'sign)
2325                (mime-editor/enclose-signed-region beg end)
2326                )
2327               ((eq mime-editor/pgp-processing 'encrypt)
2328                (mime-editor/enclose-encrypted-region beg end)
2329                ))
2330       )))
2331
2332
2333 ;;; @ split
2334 ;;;
2335
2336 (defun mime-editor/insert-partial-header
2337   (fields subject id number total separator)
2338   (insert fields)
2339   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2340   (insert (format "Mime-Version: 1.0 (split by tm-edit %s)\n"
2341                   mime-editor/version))
2342   (insert (format "\
2343 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2344                   id number total separator))
2345   )
2346
2347 (defun mime-editor/split-and-send
2348   (&optional cmd lines mime-editor/message-max-length)
2349   (interactive)
2350   (or lines
2351       (setq lines
2352             (count-lines (point-min) (point-max)))
2353       )
2354   (or mime-editor/message-max-length
2355       (setq mime-editor/message-max-length
2356             (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2357                 mime-editor/message-default-max-length))
2358       )
2359   (let* ((mime-editor/draft-file-name 
2360           (or (buffer-file-name)
2361               (make-temp-name
2362                (expand-file-name "tm-draft" mime/tmp-dir))))
2363          (separator mail-header-separator)
2364          (config
2365           (eval (cdr (assq major-mode mime-editor/window-config-alist))))
2366          (id (concat "\""
2367                      (replace-space-with-underline (current-time-string))
2368                      "@" (system-name) "\"")))
2369     (run-hooks 'mime-editor/before-split-hook)
2370     (let* ((header (rfc822/get-header-string-except
2371                     mime-editor/split-ignored-field-regexp separator))
2372            (subject (mail-fetch-field "subject"))
2373            (total (+ (/ lines mime-editor/message-max-length)
2374                      (if (> (mod lines mime-editor/message-max-length) 0)
2375                          1)))
2376            (the-buf (current-buffer))
2377            (buf (get-buffer "*tmp-send*"))
2378            (command
2379             (or cmd
2380                 (cdr
2381                  (assq major-mode
2382                        mime-editor/split-message-sender-alist))
2383                 (cdr
2384                  (assq major-mode
2385                        mime-editor/message-default-sender-alist))
2386                 ))
2387            data)
2388       (goto-char (point-min))
2389       (if (re-search-forward (concat "^" (regexp-quote separator) "$")
2390                              nil t)
2391           (replace-match "")
2392         )
2393       (if buf
2394           (progn
2395             (switch-to-buffer buf)
2396             (erase-buffer)
2397             (switch-to-buffer the-buf)
2398             )
2399         (setq buf (get-buffer-create "*tmp-send*"))
2400         )
2401       (switch-to-buffer buf)
2402       (make-local-variable 'mail-header-separator)
2403       (setq mail-header-separator separator)
2404       (switch-to-buffer the-buf)
2405       (goto-char (point-min))
2406       (re-search-forward "^$" nil t)
2407       (let ((mime-editor/partial-number 1))
2408         (setq data (buffer-substring
2409                     (point-min)
2410                     (progn
2411                       (goto-line mime-editor/message-max-length)
2412                       (point))
2413                     ))
2414         (delete-region (point-min)(point))
2415         (switch-to-buffer buf)
2416         (mime-editor/insert-partial-header
2417          header subject id mime-editor/partial-number total separator)
2418         (insert data)
2419         (save-excursion
2420           (save-restriction
2421             (goto-char (point-min))
2422             (search-forward (concat "\n" mail-header-separator "\n"))
2423             (narrow-to-region
2424              (match-end 0)
2425              (if (re-search-forward "^$" nil t)
2426                  (match-beginning 0)
2427                (point-max)
2428                ))
2429             (goto-char (point-min))
2430             (while (re-search-forward
2431                     mime-editor/split-blind-field-regexp nil t)
2432               (delete-region (match-beginning 0)
2433                              (let ((e (rfc822/field-end)))
2434                                (if (< e (point-max))
2435                                    (1+ e)
2436                                  e)))
2437               )
2438             ))
2439         (save-excursion
2440           (message (format "Sending %d/%d..."
2441                            mime-editor/partial-number total))
2442           (call-interactively command)
2443           (message (format "Sending %d/%d... done"
2444                            mime-editor/partial-number total))
2445           )
2446         (erase-buffer)
2447         (switch-to-buffer the-buf)
2448         (setq mime-editor/partial-number 2)
2449         (while (< mime-editor/partial-number total)
2450           (setq data (buffer-substring
2451                       (point-min)
2452                       (progn
2453                         (goto-line mime-editor/message-max-length)
2454                         (point))
2455                       ))
2456           (delete-region (point-min)(point))
2457           (switch-to-buffer buf)
2458           (mime-editor/insert-partial-header
2459            header subject id mime-editor/partial-number total separator)
2460           (insert data)
2461           (save-excursion
2462             (message (format "Sending %d/%d..."
2463                              mime-editor/partial-number total))
2464             (call-interactively command)
2465             (message (format "Sending %d/%d... done"
2466                              mime-editor/partial-number total))
2467             )
2468           (erase-buffer)
2469           (switch-to-buffer the-buf)
2470           (setq mime-editor/partial-number
2471                 (1+ mime-editor/partial-number))
2472           )
2473         (goto-char (point-min))
2474         (mime-editor/insert-partial-header
2475          header subject id mime-editor/partial-number total separator)
2476         (message (format "Sending %d/%d..."
2477                          mime-editor/partial-number total))
2478         ))))
2479
2480 (defun mime-editor/maybe-split-and-send (&optional cmd)
2481   (interactive)
2482   (run-hooks 'mime-editor/before-send-hook)
2483   (let ((mime-editor/message-max-length
2484          (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2485              mime-editor/message-default-max-length))
2486         (lines (count-lines (point-min) (point-max)))
2487         )
2488     (if (and (> lines mime-editor/message-max-length)
2489              mime-editor/split-message)
2490         (mime-editor/split-and-send cmd lines mime-editor/message-max-length)
2491       )))
2492
2493
2494 ;;; @ preview message
2495 ;;;
2496
2497 (defun mime-editor/preview-message ()
2498   "preview editing MIME message. [tm-edit.el]"
2499   (interactive)
2500   (let* ((str (buffer-string))
2501          (separator mail-header-separator)
2502          (the-buf (current-buffer))
2503          (buf-name (buffer-name))
2504          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2505          (buf (get-buffer temp-buf-name))
2506          )
2507     (if buf
2508         (progn
2509           (switch-to-buffer buf)
2510           (erase-buffer)
2511           )
2512       (setq buf (get-buffer-create temp-buf-name))
2513       (switch-to-buffer buf)
2514       )
2515     (insert str)
2516     (setq major-mode 'mime/temporary-message-mode)
2517     (make-local-variable 'mail-header-separator)
2518     (setq mail-header-separator separator)
2519     (make-local-variable 'mime/editing-buffer)
2520     (setq mime/editing-buffer the-buf)
2521     
2522     (run-hooks 'mime-editor/translate-hook)
2523     (mime-editor/translate-buffer)
2524     (goto-char (point-min))
2525     (if (re-search-forward
2526          (concat "^" (regexp-quote separator) "$"))
2527         (replace-match "")
2528       )
2529     (mime/viewer-mode)
2530     ))
2531
2532 (defun mime-editor/quitting-method ()
2533   (let ((temp mime::preview/article-buffer)
2534         buf)
2535     (mime-viewer/kill-buffer)
2536     (set-buffer temp)
2537     (setq buf mime/editing-buffer)
2538     (kill-buffer temp)
2539     (switch-to-buffer buf)
2540     ))
2541
2542 (set-alist 'mime-viewer/quitting-method-alist
2543            'mime/temporary-message-mode
2544            (function mime-editor/quitting-method)
2545            )
2546
2547
2548 ;;; @ draft preview
2549 ;;; 
2550 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2551 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2552
2553 (defvar mime-editor/draft-header-separator-alist
2554   '((news-reply-mode . mail-header-separator)
2555     (mh-letter-mode . mail-header-separator)
2556     ))
2557
2558 (defvar mime::article/draft-header-separator nil)
2559
2560 (defun mime-editor/draft-preview ()
2561   (interactive)
2562   (let ((sep (cdr (assq major-mode mime-editor/draft-header-separator-alist))))
2563     (or (stringp sep) (setq sep (eval sep)))
2564     (make-variable-buffer-local 'mime::article/draft-header-separator)
2565     (goto-char (point-min))
2566     (re-search-forward
2567      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2568     (setq mime::article/draft-header-separator
2569           (buffer-substring (match-beginning 0) (match-end 0)))
2570     (replace-match "")
2571     (mime/viewer-mode (current-buffer))
2572     (pop-to-buffer (current-buffer))
2573     ))
2574
2575 (defun mime-viewer::quitting-method/draft-preview ()
2576   (let ((mother mime::preview/mother-buffer))
2577     (save-excursion
2578       (switch-to-buffer mother)
2579       (goto-char (point-min))
2580       (if (and
2581            (re-search-forward
2582             (concat "^\\("
2583                     (regexp-quote mime::article/draft-header-separator)
2584                     "\\)?$") nil t)
2585            (bolp))
2586           (progn
2587             (insert mime::article/draft-header-separator)
2588             (set-buffer-modified-p (buffer-modified-p))
2589             )))
2590     (mime-viewer/kill-buffer)
2591     (pop-to-buffer mother)
2592     ))
2593
2594 (set-alist 'mime-viewer/quitting-method-alist
2595            'mh-letter-mode
2596            (function mime-viewer::quitting-method/draft-preview)
2597            )
2598
2599 (set-alist 'mime-viewer/quitting-method-alist
2600            'news-reply-mode
2601            (function mime-viewer::quitting-method/draft-preview)
2602            )
2603
2604
2605 ;;; @ etc
2606 ;;;
2607
2608 (defun replace-space-with-underline (str)
2609   (mapconcat (function
2610               (lambda (arg)
2611                 (char-to-string
2612                  (if (= arg 32)
2613                      ?_
2614                    arg)))) str "")
2615   )
2616
2617
2618 ;;; @ end
2619 ;;;
2620
2621 (provide 'tm-edit)
2622
2623 (run-hooks 'tm-edit-load-hook)
2624
2625 ;;; tm-edit.el ends here