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