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