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