tm 7.76.
[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.76 $
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.76 1996/08/06 12:29:11 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 (defun mime-editor/encrypt-pgp-elkins (beg end boundary)
1666   (save-excursion
1667     (save-restriction
1668       (let (from to cc recipients)
1669         (let ((ret (rfc822/get-field-bodies
1670                     '("From" "To" "cc") nil mail-header-separator)))
1671           (setq from (car ret)  ret (cdr ret)
1672                 to (car ret)    ret (cdr ret)
1673                 cc (car ret))
1674           )
1675         (narrow-to-region beg end)
1676         (let* ((ret
1677                 (mime-editor/translate-region beg end boundary))
1678                (ctype    (car ret))
1679                (encoding (nth 1 ret))
1680                (parts    (nth 3 ret))
1681                (pgp-boundary (concat "pgp-" boundary))
1682                )
1683           (goto-char beg)
1684           (if (and (stringp from)
1685                    (not (string-equal from "")))
1686               (insert (format "From: %s\n" from))
1687             )
1688           (if (and (stringp to)
1689                    (not (string-equal to "")))
1690               (progn
1691                 (insert (format "To: %s\n" to))
1692                 (setq recipients to)
1693                 ))
1694           (if (and (stringp cc)
1695                    (not (string-equal cc "")))
1696               (progn
1697                 (insert (format "cc: %s\n" cc))
1698                 (if recipients
1699                     (setq recipients (concat recipients "," cc))
1700                   (setq recipients cc)
1701                   )))
1702           (insert (format "Content-Type: %s\n" ctype))
1703           (if encoding
1704               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1705             )
1706           (insert "\n")
1707           (if (null
1708                (let ((mc-pgp-always-sign 'never))
1709                  (mc-pgp-encrypt-region
1710                   (mc-split "\\([ \t\n]*,[ \t\n]*\\)+" recipients)
1711                   (point-min) (point-max) from nil)
1712                  ))
1713               (throw 'mime-editor/error 'pgp-error)
1714             )
1715           (goto-char beg)
1716           (insert (format "--[[multipart/encrypted;
1717  boundary=\"%s\";
1718  protocol=\"application/pgp-encrypted\"][7bit]]
1719 --%s
1720 Content-Type: application/pgp-encrypted
1721
1722 --%s
1723 Content-Type: application/octet-stream
1724 Content-Transfer-Encoding: 7bit
1725
1726 " pgp-boundary pgp-boundary pgp-boundary))
1727           (goto-char (point-max))
1728           (insert (format "\n--%s--\n" pgp-boundary))
1729           )))))
1730
1731 (defun mime-editor/sign-pgp-kazu (beg end boundary)
1732   (save-excursion
1733     (save-restriction
1734       (narrow-to-region beg end)
1735       (let* ((ret
1736               (mime-editor/translate-region beg end boundary))
1737              (ctype    (car ret))
1738              (encoding (nth 1 ret))
1739              (parts    (nth 3 ret))
1740              )
1741         (goto-char beg)
1742         (insert (format "Content-Type: %s\n" ctype))
1743         (if encoding
1744             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1745           )
1746         (insert "\n")
1747         (or (as-binary-process (mc-pgp-sign-region beg (point-max)))
1748             (throw 'mime-editor/error 'pgp-error)
1749             )
1750         (goto-char beg)
1751         (insert
1752          "--[[application/pgp; format=mime][7bit]]\n")
1753         ))
1754     ))
1755
1756 (defun mime-editor/encrypt-pgp-kazu (beg end boundary)
1757   (save-excursion
1758     (let ((from (rfc822/get-field-body "From"))
1759           (to (rfc822/get-field-body "To"))
1760           (cc (rfc822/get-field-body "cc"))
1761           recipients)
1762       (save-restriction
1763         (narrow-to-region beg end)
1764         (let* ((ret
1765                 (mime-editor/translate-region beg end boundary))
1766                (ctype    (car ret))
1767                (encoding (nth 1 ret))
1768                (parts    (nth 3 ret))
1769                )
1770           (goto-char beg)
1771           (if (and (stringp from)
1772                    (not (string-equal from "")))
1773               (insert (format "From: %s\n" from))
1774             )
1775           (if (and (stringp to)
1776                    (not (string-equal to "")))
1777               (progn
1778                 (insert (format "To: %s\n" to))
1779                 (setq recipients to)
1780                 ))
1781           (if (and (stringp cc)
1782                    (not (string-equal cc "")))
1783               (progn
1784                 (insert (format "cc: %s\n" cc))
1785                 (if recipients
1786                     (setq recipients (concat recipients "," cc))
1787                   (setq recipients cc)
1788                   )))
1789           (insert (format "Content-Type: %s\n" ctype))
1790           (if encoding
1791               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1792             )
1793           (insert "\n")
1794           (or (as-binary-process
1795                (mc-pgp-encrypt-region
1796                 (mc-split "\\([ \t\n]*,[ \t\n]*\\)+" recipients)
1797                 beg (point-max))
1798                )
1799               (throw 'mime-editor/error 'pgp-error)
1800               )
1801           (goto-char beg)
1802           (insert
1803            "--[[application/pgp; format=mime][7bit]]\n")
1804           ))
1805       )))
1806
1807 (defun mime-editor/translate-body ()
1808   "Encode the tagged MIME body in current buffer in MIME compliant message."
1809   (interactive)
1810   (save-excursion
1811     (let ((boundary
1812            (concat mime-multipart-boundary "_"
1813                    (replace-space-with-underline (current-time-string))
1814                    ))
1815           (i 1)
1816           ret)
1817       (while (mime-editor/process-multipart-1
1818               (format "%s-%d" boundary i))
1819         (setq i (1+ i))
1820         )
1821       (save-restriction
1822         ;; We are interested in message body.
1823         (let* ((beg
1824                 (progn
1825                   (goto-char (point-min))
1826                   (re-search-forward
1827                    (concat "\n" (regexp-quote mail-header-separator)
1828                            (if mime-ignore-preceding-spaces
1829                                "[ \t\n]*\n" "\n")) nil 'move)
1830                   (point)))
1831                (end
1832                 (progn
1833                   (goto-char (point-max))
1834                   (and mime-ignore-trailing-spaces
1835                        (re-search-backward "[^ \t\n]\n" beg t)
1836                        (forward-char 1))
1837                   (point))))
1838           (setq ret (mime-editor/translate-region
1839                      beg end
1840                      (format "%s-%d" boundary i)))
1841           ))
1842       (mime-editor/dequote-region (point-min)(point-max))
1843       (let ((contype (car ret))         ;Content-Type
1844             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1845             )
1846         ;; Make primary MIME headers.
1847         (or (mail-position-on-field "Mime-Version")
1848             (insert mime-editor/mime-version-value))
1849         ;; Remove old Content-Type and other fields.
1850         (save-restriction
1851           (goto-char (point-min))
1852           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1853           (narrow-to-region (point-min) (point))
1854           (goto-char (point-min))
1855           (mime-delete-field "Content-Type")
1856           (mime-delete-field "Content-Transfer-Encoding"))
1857         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1858         (mail-position-on-field "Content-Type")
1859         (insert contype)
1860         (if encoding
1861             (progn
1862               (mail-position-on-field "Content-Transfer-Encoding")
1863               (insert encoding)))
1864         ))))
1865
1866 (defun mime-editor/translate-single-part-tag (&optional prefix)
1867   (if (re-search-forward mime-editor/single-part-tag-regexp nil t)
1868       (let* ((beg (match-beginning 0))
1869              (end (match-end 0))
1870              (tag (buffer-substring beg end))
1871              )
1872         (delete-region beg end)
1873         (setq contype (mime-editor/get-contype tag))
1874         (setq encoding (mime-editor/get-encoding tag))
1875         (insert (concat prefix "--" boundary "\n"))
1876         (save-restriction
1877           (narrow-to-region (point)(point))
1878           (insert "Content-Type: " contype "\n")
1879           (if encoding
1880               (insert "Content-Transfer-Encoding: " encoding "\n"))
1881           (mime/encode-message-header)
1882           )
1883         t)))
1884
1885 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1886   (if (null boundary)
1887       (setq boundary
1888             (concat mime-multipart-boundary "_"
1889                     (replace-space-with-underline (current-time-string))))
1890     )
1891   (save-excursion
1892     (save-restriction
1893       (narrow-to-region beg end)
1894       (let ((tag nil)                   ;MIME tag
1895             (contype nil)               ;Content-Type
1896             (encoding nil)              ;Content-Transfer-Encoding
1897             (nparts 0))                 ;Number of body parts
1898         ;; Normalize the body part by inserting appropriate message
1899         ;; tags for every message contents.
1900         (mime-editor/normalize-body)
1901         ;; Counting the number of Content-Type.
1902         (goto-char (point-min))
1903         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1904           (setq nparts (1+ nparts)))
1905         ;; Begin translation.
1906         (cond
1907          ((and (<= nparts 1)(not multipart))
1908           ;; It's a singular message.
1909           (goto-char (point-min))
1910           (while (re-search-forward
1911                   mime-editor/single-part-tag-regexp nil t)
1912             (setq tag
1913                   (buffer-substring (match-beginning 0) (match-end 0)))
1914             (delete-region (match-beginning 0) (1+ (match-end 0)))
1915             (setq contype (mime-editor/get-contype tag))
1916             (setq encoding (mime-editor/get-encoding tag))
1917             ))
1918          (t
1919           ;; It's a multipart message.
1920           (goto-char (point-min))
1921           (and (mime-editor/translate-single-part-tag)
1922                (while (mime-editor/translate-single-part-tag "\n"))
1923                )
1924           ;; Define Content-Type as "multipart/mixed".
1925           (setq contype
1926                 (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1927           ;; Content-Transfer-Encoding must be "7bit".
1928           ;; The following encoding can be `nil', but is
1929           ;; specified as is since there is no way that a user
1930           ;; specifies it.
1931           (setq encoding "7bit")
1932           ;; Insert the trailer.
1933           (goto-char (point-max))
1934           (insert "\n--" boundary "--\n")
1935           ))
1936         (list contype encoding boundary nparts)
1937         ))))
1938
1939 (defun mime-editor/normalize-body ()
1940   "Normalize the body part by inserting appropriate message tags."
1941   ;; Insert the first MIME tags if necessary.
1942   (goto-char (point-min))
1943   (if (not (looking-at mime-editor/single-part-tag-regexp))
1944       (insert (mime-make-text-tag) "\n"))
1945   ;; Check each tag, and add new tag or correct it if necessary.
1946   (goto-char (point-min))
1947   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1948     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1949            (contype (mime-editor/get-contype tag))
1950            (charset (mime-get-parameter contype "charset"))
1951            (encoding (mime-editor/get-encoding tag)))
1952       ;; Remove extra whitespaces after the tag.
1953       (if (looking-at "[ \t]+$")
1954           (delete-region (match-beginning 0) (match-end 0)))
1955       (let ((beg (point))
1956             (end (mime-editor/content-end))
1957             )
1958         (goto-char end)
1959         (or (looking-at mime-editor/beginning-tag-regexp)
1960             (eobp)
1961             (insert (mime-make-text-tag) "\n")
1962             )
1963         (visible-region beg end)
1964         (goto-char beg)
1965         )
1966       (cond
1967        ((mime-test-content-type contype "message")
1968         ;; Content-type "message" should be sent as is.
1969         (forward-line 1)
1970         )
1971        ((mime-test-content-type contype "text")
1972         ;; Define charset for text if necessary.
1973         (setq charset (if charset
1974                           (intern (downcase charset))
1975                         (mime-editor/choose-charset)))
1976         (mime-editor/define-charset charset)
1977         (cond ((string-equal contype "text/x-rot13-47")
1978                (save-excursion
1979                  (forward-line)
1980                  (set-mark (point))
1981                  (goto-char (mime-editor/content-end))
1982                  (tm:caesar-region)
1983                  ))
1984               ((string-equal contype "text/enriched")
1985                (save-excursion
1986                  (let ((beg (progn
1987                               (forward-line)
1988                               (point)))
1989                        (end (mime-editor/content-end))
1990                        )
1991                    (enriched-encode beg end)
1992                    (goto-char beg)
1993                    (if (search-forward "\n\n")
1994                        (delete-region beg (match-end 0))
1995                      )
1996                    ))))
1997         ;; Point is now on current tag.
1998         ;; Define encoding and encode text if necessary.
1999         (or encoding    ;Encoding is not specified.
2000             (let* ((encoding
2001                     (cdr
2002                      (assq charset
2003                            mime-editor/charset-default-encoding-alist)
2004                      ))
2005                    (beg (mime-editor/content-beginning))
2006                    )
2007               (encode-mime-charset-region beg (mime-editor/content-end)
2008                                           charset)
2009               (mime-encode-region beg (mime-editor/content-end) encoding)
2010               (mime-editor/define-encoding encoding)
2011               ))
2012         (goto-char (mime-editor/content-end))
2013         )
2014        ((null encoding)         ;Encoding is not specified.
2015         ;; Application, image, audio, video, and any other
2016         ;; unknown content-type without encoding should be
2017         ;; encoded.
2018         (let* ((encoding "base64")      ;Encode in BASE64 by default.
2019                (beg (mime-editor/content-beginning))
2020                (end (mime-editor/content-end))
2021                (body (buffer-substring beg end))
2022                )
2023           (mime-encode-region beg end encoding)
2024           (mime-editor/define-encoding encoding))
2025         (forward-line 1)
2026         ))
2027       )))
2028
2029 (defun mime-delete-field (field)
2030   "Delete header FIELD."
2031   (let ((regexp (format "^%s:[ \t]*" field)))
2032     (goto-char (point-min))
2033     (while (re-search-forward regexp nil t)
2034       (delete-region (match-beginning 0)
2035                      (progn (forward-line 1) (point)))
2036       )))
2037
2038 \f
2039 ;;;
2040 ;;; Platform dependent functions
2041 ;;;
2042
2043 ;; Sun implementations
2044
2045 (defun mime-voice-recorder-for-sun ()
2046   "Record voice in a buffer using Sun audio device, and return the buffer.
2047 If the environment variable AUDIOHOST is defined, its value is used as
2048 a recording host instead of local host."
2049   (let ((buffer (get-buffer-create " *MIME audio*"))
2050         (host (getenv "AUDIOHOST")))
2051     (message "Start the recording on %s.  Type C-g to finish the recording..."
2052              (or host (system-name)))
2053     (save-excursion
2054       (set-buffer buffer)
2055       (erase-buffer)
2056       (condition-case errorcode
2057           (let ((selective-display nil) ;Disable ^M to nl translation.
2058                 (mc-flag nil)           ;Mule
2059                 (kanji-flag nil))       ;NEmacs
2060             ;; If AUDIOHOST is defined, use the value as recording host.
2061             (cond ((not (null host))
2062                    ;; Disable automatic conversion of coding system if Mule.
2063                    (if (featurep 'mule)
2064                        (define-program-coding-system nil "rsh" *noconv*))
2065                    (call-process "rsh"
2066                                  nil
2067                                  buffer
2068                                  nil
2069                                  host
2070                                  "cat"
2071                                  "/dev/audio"
2072                                  ))
2073                   (t
2074                    ;; Disable automatic conversion of coding system if Mule.
2075                    (if (featurep 'mule)
2076                        (define-program-coding-system nil "cat" *noconv*))
2077                    (call-process "cat"
2078                                  "/dev/audio"
2079                                  buffer
2080                                  nil
2081                                  ))))
2082         (quit (message "Type C-g to finish recording... done.")
2083               buffer                    ;Return the buffer
2084               )))))
2085
2086 \f
2087 ;;; @ Other useful commands.
2088 ;;;
2089
2090 ;; Message forwarding commands as content-type "message/rfc822".
2091
2092 (defun mime-editor/insert-message (&optional message)
2093   (interactive)
2094   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
2095     (if (and inserter (fboundp inserter))
2096         (progn
2097           (mime-editor/insert-tag "message" "rfc822")
2098           (funcall inserter message)
2099           )
2100       (message "Sorry, I don't have message inserter for your MUA.")
2101       )))
2102
2103 (defun mime-editor/insert-mail (&optional message)
2104   (interactive)
2105   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
2106     (if (and inserter (fboundp inserter))
2107         (progn
2108           (mime-editor/insert-tag "message" "rfc822")
2109           (funcall inserter message)
2110           )
2111       (message "Sorry, I don't have mail inserter for your MUA.")
2112       )))
2113
2114 (defun mime-editor/inserted-message-filter ()
2115   (save-excursion
2116     (save-restriction
2117       (let ((header-start (point))
2118             (case-fold-search t)
2119             beg end)
2120         ;; for Emacs 18
2121         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2122         (if (re-search-forward "^$" (mark t))
2123             (narrow-to-region header-start (match-beginning 0))
2124           )
2125         (goto-char header-start)
2126         (while (and (re-search-forward
2127                      mime-editor/yank-ignored-field-regexp nil t)
2128                     (setq beg (match-beginning 0))
2129                     (setq end (1+ (rfc822/field-end)))
2130                     )
2131           (delete-region beg end)
2132           )
2133         ))))
2134
2135
2136 ;;; @ multipart enclosure
2137 ;;;
2138
2139 (defun mime-editor/enclose-region (type beg end)
2140   (save-excursion
2141     (goto-char beg)
2142     (let ((current (point)))
2143       (save-restriction
2144         (narrow-to-region beg end)
2145         (insert (format "--<<%s>>-{\n" type))
2146         (goto-char (point-max))
2147         (insert (format "--}-<<%s>>\n" type))
2148         (goto-char (point-max))
2149         )
2150       (or (looking-at mime-editor/beginning-tag-regexp)
2151           (eobp)
2152           (insert (mime-make-text-tag) "\n")
2153           )
2154       )))
2155
2156 (defun mime-editor/enclose-quote-region (beg end)
2157   (interactive "*r")
2158   (mime-editor/enclose-region "quote" beg end)
2159   )
2160
2161 (defun mime-editor/enclose-mixed-region (beg end)
2162   (interactive "*r")
2163   (mime-editor/enclose-region "mixed" beg end)
2164   )
2165
2166 (defun mime-editor/enclose-parallel-region (beg end)
2167   (interactive "*r")
2168   (mime-editor/enclose-region "parallel" beg end)
2169   )
2170
2171 (defun mime-editor/enclose-digest-region (beg end)
2172   (interactive "*r")
2173   (mime-editor/enclose-region "digest" beg end)
2174   )
2175
2176 (defun mime-editor/enclose-alternative-region (beg end)
2177   (interactive "*r")
2178   (mime-editor/enclose-region "alternative" beg end)
2179   )
2180
2181 (defun mime-editor/enclose-signed-region (beg end)
2182   (interactive "*r")
2183   (if mime-editor/signing-type
2184       (mime-editor/enclose-region "signed" beg end)
2185     (message "Please specify signing type.")
2186     ))
2187
2188 (defun mime-editor/enclose-encrypted-region (beg end)
2189   (interactive "*r")
2190   (if mime-editor/signing-type
2191       (mime-editor/enclose-region "encrypted" beg end)
2192     (message "Please specify encrypting type.")
2193     ))
2194
2195 (defun mime-editor/insert-key (&optional arg)
2196   "Insert a pgp public key."
2197   (interactive "P")
2198   (mime-editor/insert-tag "application" "pgp-keys")
2199   (mime-editor/define-encoding "7bit")
2200   (mc-insert-public-key)
2201   )
2202
2203
2204 ;;; @ flag setting
2205 ;;;
2206
2207 (defun mime-editor/set-split (arg)
2208   (interactive
2209    (list
2210     (y-or-n-p "Do you want to enable split?")
2211     ))
2212   (setq mime-editor/split-message arg)
2213   (if arg
2214       (message "This message is enabled to split.")
2215     (message "This message is not enabled to split.")
2216     ))
2217
2218 (defun mime-editor/toggle-transfer-level (&optional transfer-level)
2219   "Toggle transfer-level is 7bit or 8bit through.
2220
2221 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2222   (interactive)
2223   (if (numberp transfer-level)
2224       (setq mime-editor/transfer-level transfer-level)
2225     (if (< mime-editor/transfer-level 8)
2226         (setq mime-editor/transfer-level 8)
2227       (setq mime-editor/transfer-level 7)
2228       ))
2229   (setq mime-editor/charset-default-encoding-alist
2230         (mime-editor/make-charset-default-encoding-alist
2231          mime-editor/transfer-level))
2232   (message (format "Current transfer-level is %d bit"
2233                    mime-editor/transfer-level))
2234   (setq mime-editor/transfer-level-string
2235         (mime/encoding-name mime-editor/transfer-level 'not-omit))
2236   (force-mode-line-update)
2237   )
2238
2239
2240 ;;; @ pgp
2241 ;;;
2242
2243 (defun mime-editor/set-sign (arg)
2244   (interactive
2245    (list
2246     (y-or-n-p "Do you want to sign?")
2247     ))
2248   (if arg
2249       (if mime-editor/signing-type
2250           (progn
2251             (setq mime-editor/pgp-processing 'sign)
2252             (message "This message will be signed.")
2253             )
2254         (message "Please specify signing type.")
2255         )
2256     (if (eq mime-editor/pgp-processing 'sign)
2257         (setq mime-editor/pgp-processing nil)
2258       )
2259     (message "This message will not be signed.")
2260     ))
2261
2262 (defun mime-editor/set-encrypt (arg)
2263   (interactive
2264    (list
2265     (y-or-n-p "Do you want to encrypt?")
2266     ))
2267   (if arg
2268       (if mime-editor/encrypting-type
2269           (progn
2270             (setq mime-editor/pgp-processing 'encrypt)
2271             (message "This message will be encrypt.")
2272             )
2273         (message "Please specify encrypting type.")
2274         )
2275     (if (eq mime-editor/pgp-processing 'encrypt)
2276         (setq mime-editor/pgp-processing nil)
2277       )
2278     (message "This message will not be encrypt.")
2279     ))
2280
2281 (defvar mime-editor/pgp-processing nil)
2282 (make-variable-buffer-local 'mime-editor/pgp-processing)
2283
2284 (defun mime-editor/pgp-enclose-buffer ()
2285   (let ((beg (save-excursion
2286                (goto-char (point-min))
2287                (if (search-forward (concat "\n" mail-header-separator "\n"))
2288                    (match-end 0)
2289                  )))
2290         (end (point-max))
2291         )
2292     (if beg
2293         (cond ((eq mime-editor/pgp-processing 'sign)
2294                (mime-editor/enclose-signed-region beg end)
2295                )
2296               ((eq mime-editor/pgp-processing 'encrypt)
2297                (mime-editor/enclose-encrypted-region beg end)
2298                ))
2299       )))
2300
2301
2302 ;;; @ split
2303 ;;;
2304
2305 (defun mime-editor/insert-partial-header
2306   (fields subject id number total separator)
2307   (insert fields)
2308   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2309   (insert (format "Mime-Version: 1.0 (split by %s)\n"
2310                   mime-editor/version-name))
2311   (insert (format "\
2312 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2313                   id number total separator))
2314   )
2315
2316 (defun mime-editor/split-and-send
2317   (&optional cmd lines mime-editor/message-max-length)
2318   (interactive)
2319   (or lines
2320       (setq lines
2321             (count-lines (point-min) (point-max)))
2322       )
2323   (or mime-editor/message-max-length
2324       (setq mime-editor/message-max-length
2325             (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2326                 mime-editor/message-default-max-length))
2327       )
2328   (let* ((mime-editor/draft-file-name 
2329           (or (buffer-file-name)
2330               (make-temp-name
2331                (expand-file-name "tm-draft" mime/tmp-dir))))
2332          (separator mail-header-separator)
2333          (id (concat "\""
2334                      (replace-space-with-underline (current-time-string))
2335                      "@" (system-name) "\"")))
2336     (run-hooks 'mime-editor/before-split-hook)
2337     (let ((the-buf (current-buffer))
2338           (copy-buf (get-buffer-create " *Original Message*"))
2339           (header (rfc822/get-header-string-except
2340                    mime-editor/split-ignored-field-regexp separator))
2341           (subject (mail-fetch-field "subject"))
2342           (total (+ (/ lines mime-editor/message-max-length)
2343                     (if (> (mod lines mime-editor/message-max-length) 0)
2344                         1)))
2345           (command
2346            (or cmd
2347                (cdr
2348                 (assq major-mode
2349                       mime-editor/split-message-sender-alist))
2350                ))
2351           (mime-editor/partial-number 1)
2352           data)
2353       (save-excursion
2354         (set-buffer copy-buf)
2355         (erase-buffer)
2356         (insert-buffer the-buf)
2357         (save-restriction
2358           (if (re-search-forward
2359                (concat "^" (regexp-quote separator) "$") nil t)
2360               (let ((he (match-beginning 0)))
2361                 (replace-match "")
2362                 (narrow-to-region (point-min) he)
2363                 ))
2364           (goto-char (point-min))
2365           (while (re-search-forward mime-editor/split-blind-field-regexp nil t)
2366             (delete-region (match-beginning 0)
2367                            (1+ (rfc822/field-end)))
2368             )))
2369       (while (< mime-editor/partial-number total)
2370         (erase-buffer)
2371         (save-excursion
2372           (set-buffer copy-buf)
2373           (setq data (buffer-substring
2374                       (point-min)
2375                       (progn
2376                         (goto-line mime-editor/message-max-length)
2377                         (point))
2378                       ))
2379           (delete-region (point-min)(point))
2380           )
2381         (mime-editor/insert-partial-header
2382          header subject id mime-editor/partial-number total separator)
2383         (insert data)
2384         (save-excursion
2385           (message (format "Sending %d/%d..."
2386                            mime-editor/partial-number total))
2387           (call-interactively command)
2388           (message (format "Sending %d/%d... done"
2389                            mime-editor/partial-number total))
2390           )
2391         (setq mime-editor/partial-number
2392               (1+ mime-editor/partial-number))
2393         )
2394       (erase-buffer)
2395       (save-excursion
2396         (set-buffer copy-buf)
2397         (setq data (buffer-string))
2398         (erase-buffer)
2399         )
2400       (mime-editor/insert-partial-header
2401        header subject id mime-editor/partial-number total separator)
2402       (insert data)
2403       (save-excursion
2404         (message (format "Sending %d/%d..."
2405                          mime-editor/partial-number total))
2406         (message (format "Sending %d/%d... done"
2407                          mime-editor/partial-number total))
2408         )
2409       )))
2410
2411 (defun mime-editor/maybe-split-and-send (&optional cmd)
2412   (interactive)
2413   (run-hooks 'mime-editor/before-send-hook)
2414   (let ((mime-editor/message-max-length
2415          (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2416              mime-editor/message-default-max-length))
2417         (lines (count-lines (point-min) (point-max)))
2418         )
2419     (if (and (> lines mime-editor/message-max-length)
2420              mime-editor/split-message)
2421         (mime-editor/split-and-send cmd lines mime-editor/message-max-length)
2422       )))
2423
2424
2425 ;;; @ preview message
2426 ;;;
2427
2428 (defun mime-editor/preview-message ()
2429   "preview editing MIME message. [tm-edit.el]"
2430   (interactive)
2431   (let* ((str (buffer-string))
2432          (separator mail-header-separator)
2433          (the-buf (current-buffer))
2434          (buf-name (buffer-name))
2435          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2436          (buf (get-buffer temp-buf-name))
2437          )
2438     (if buf
2439         (progn
2440           (switch-to-buffer buf)
2441           (erase-buffer)
2442           )
2443       (setq buf (get-buffer-create temp-buf-name))
2444       (switch-to-buffer buf)
2445       )
2446     (insert str)
2447     (setq major-mode 'mime/temporary-message-mode)
2448     (make-local-variable 'mail-header-separator)
2449     (setq mail-header-separator separator)
2450     (make-local-variable 'mime/editing-buffer)
2451     (setq mime/editing-buffer the-buf)
2452     
2453     (run-hooks 'mime-editor/translate-hook)
2454     (mime-editor/translate-buffer)
2455     (goto-char (point-min))
2456     (if (re-search-forward
2457          (concat "^" (regexp-quote separator) "$"))
2458         (replace-match "")
2459       )
2460     (mime/viewer-mode)
2461     ))
2462
2463 (defun mime-editor/quitting-method ()
2464   (let ((temp mime::preview/article-buffer)
2465         buf)
2466     (mime-viewer/kill-buffer)
2467     (set-buffer temp)
2468     (setq buf mime/editing-buffer)
2469     (kill-buffer temp)
2470     (switch-to-buffer buf)
2471     ))
2472
2473 (set-alist 'mime-viewer/quitting-method-alist
2474            'mime/temporary-message-mode
2475            (function mime-editor/quitting-method)
2476            )
2477
2478
2479 ;;; @ draft preview
2480 ;;; 
2481 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2482 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2483
2484 (defvar mime-editor/draft-header-separator-alist
2485   '((news-reply-mode . mail-header-separator)
2486     (mh-letter-mode . mail-header-separator)
2487     ))
2488
2489 (defvar mime::article/draft-header-separator nil)
2490
2491 (defun mime-editor/draft-preview ()
2492   (interactive)
2493   (let ((sep (cdr (assq major-mode mime-editor/draft-header-separator-alist))))
2494     (or (stringp sep) (setq sep (eval sep)))
2495     (make-variable-buffer-local 'mime::article/draft-header-separator)
2496     (goto-char (point-min))
2497     (re-search-forward
2498      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2499     (setq mime::article/draft-header-separator
2500           (buffer-substring (match-beginning 0) (match-end 0)))
2501     (replace-match "")
2502     (mime/viewer-mode (current-buffer))
2503     (pop-to-buffer (current-buffer))
2504     ))
2505
2506 (defun mime-viewer::quitting-method/draft-preview ()
2507   (let ((mother mime::preview/mother-buffer))
2508     (save-excursion
2509       (switch-to-buffer mother)
2510       (goto-char (point-min))
2511       (if (and
2512            (re-search-forward
2513             (concat "^\\("
2514                     (regexp-quote mime::article/draft-header-separator)
2515                     "\\)?$") nil t)
2516            (bolp))
2517           (progn
2518             (insert mime::article/draft-header-separator)
2519             (set-buffer-modified-p (buffer-modified-p))
2520             )))
2521     (mime-viewer/kill-buffer)
2522     (pop-to-buffer mother)
2523     ))
2524
2525 (set-alist 'mime-viewer/quitting-method-alist
2526            'mh-letter-mode
2527            (function mime-viewer::quitting-method/draft-preview)
2528            )
2529
2530 (set-alist 'mime-viewer/quitting-method-alist
2531            'news-reply-mode
2532            (function mime-viewer::quitting-method/draft-preview)
2533            )
2534
2535
2536 ;;; @ edit again
2537 ;;;
2538
2539 (defun mime-editor::edit-again (code-conversion)
2540   (save-excursion
2541     (goto-char (point-min))
2542     (let ((ctl (mime/Content-Type)))
2543       (if ctl
2544           (let ((ctype (car ctl))
2545                 (params (cdr ctl))
2546                 type stype)
2547             (if (string-match "/" ctype)
2548                 (progn
2549                   (setq type (substring ctype 0 (match-beginning 0)))
2550                   (setq stype (substring ctype (match-end 0)))
2551                   )
2552               (setq type ctype)
2553               )
2554             (cond
2555              ((string-equal type "multipart")
2556               (let* ((boundary (assoc-value "boundary" params))
2557                      (boundary-pat
2558                       (concat "\n--" (regexp-quote boundary) "[ \t]*\n"))
2559                      )
2560                 (re-search-forward boundary-pat nil t)
2561                 (let ((bb (match-beginning 0)) eb tag)
2562                   (setq tag (format "\n--<<%s>>-{\n" stype))
2563                   (goto-char bb)
2564                   (insert tag)
2565                   (setq bb (+ bb (length tag)))
2566                   (re-search-forward
2567                    (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2568                    nil t)
2569                   (setq eb (match-beginning 0))
2570                   (replace-match (format "--}-<<%s>>\n" stype))
2571                   (save-restriction
2572                     (narrow-to-region bb eb)
2573                     (goto-char (point-min))
2574                     (while (re-search-forward boundary-pat nil t)
2575                       (let ((beg (match-beginning 0))
2576                             end)
2577                         (delete-region beg (match-end 0))
2578                         (save-excursion
2579                           (if (re-search-forward boundary-pat nil t)
2580                               (setq end (match-beginning 0))
2581                             (setq end (point-max))
2582                             )
2583                           (save-restriction
2584                             (narrow-to-region beg end)
2585                             (mime-editor::edit-again code-conversion)
2586                             (goto-char (point-max))
2587                             ))))
2588                     ))
2589                 (goto-char (point-min))
2590                 (or (= (point-min) 1)
2591                     (delete-region (point-min)
2592                                    (if (search-forward "\n\n" nil t)
2593                                        (match-end 0)
2594                                      (point-min)
2595                                      )))
2596                 ))
2597              (t
2598               (let* (charset
2599                      (pstr
2600                       (mapconcat (function
2601                                   (lambda (attr)
2602                                     (if (string-equal (car attr)
2603                                                       "charset")
2604                                         (progn
2605                                           (setq charset (cdr attr))
2606                                           "")
2607                                       (concat ";" (car attr)
2608                                               "=" (cdr attr))
2609                                       )
2610                                     ))
2611                                  params ""))
2612                      encoding
2613                      encoded)
2614                 (save-excursion
2615                   (if (re-search-forward
2616                        "Content-Transfer-Encoding:" nil t)
2617                       (let ((beg (match-beginning 0))
2618                             (hbeg (match-end 0))
2619                             (end (rfc822/field-end)))
2620                         (setq encoding
2621                               (eliminate-top-spaces
2622                                (rfc822/unfolding-string
2623                                 (buffer-substring hbeg end))))
2624                         (if (or charset (string-equal type "text"))
2625                             (progn
2626                               (delete-region beg (1+ end))
2627                               (goto-char (point-min))
2628                               (if (search-forward "\n\n" nil t)
2629                                   (progn
2630                                     (mime-decode-region
2631                                      (match-end 0)(point-max) encoding)
2632                                     (setq encoded t
2633                                           encoding nil)
2634                                     )))))))
2635                 (if (or code-conversion encoded)
2636                     (decode-mime-charset-region
2637                      (point-min)(point-max)
2638                      (or charset default-mime-charset))
2639                   )
2640                 (let ((he
2641                        (if (re-search-forward "^$" nil t)
2642                            (match-end 0)
2643                          (point-min)
2644                          )))
2645                   (if (= (point-min) 1)
2646                       (progn
2647                         (goto-char he)
2648                         (insert
2649                          (concat "\n"
2650                                  (mime-create-tag
2651                                   (concat type "/" stype pstr) encoding)))
2652                         )
2653                     (delete-region (point-min) he)
2654                     (insert
2655                      (mime-create-tag
2656                       (concat type "/" stype pstr) encoding))
2657                     ))
2658                 ))))
2659         (if code-conversion
2660             (decode-mime-charset-region (point-min) (point-max)
2661                                         default-mime-charset)
2662           )
2663         ))))
2664
2665 (defun mime/edit-again (&optional code-conversion no-separator no-mode)
2666   (interactive)
2667   (mime-editor::edit-again code-conversion)
2668   (goto-char (point-min))
2669   (save-restriction
2670     (narrow-to-region
2671      (point-min)
2672      (if (re-search-forward
2673           (concat "^\\(" (regexp-quote mail-header-separator) "\\)?$")
2674           nil t)
2675          (match-end 0)
2676        (point-max)
2677        ))
2678     (goto-char (point-min))
2679     (while (re-search-forward
2680             "^\\(Content-.*\\|Mime-Version\\):" nil t)
2681       (delete-region (match-beginning 0) (1+ (rfc822/field-end)))
2682       ))
2683   (or no-separator
2684       (and (re-search-forward "^$")
2685            (replace-match mail-header-separator)
2686            ))
2687   (or no-mode
2688       (mime/editor-mode)
2689       ))
2690
2691
2692 ;;; @ end
2693 ;;;
2694
2695 (provide 'tm-edit)
2696
2697 (run-hooks 'tm-edit-load-hook)
2698
2699 ;;; tm-edit.el ends here