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