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