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