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