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