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