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