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