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