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