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