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