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