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