9a81844fe9585bcc68e824b82fcc55c35393bc8e
[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      ("x-kiss" ("x-cnf")))
223     ("image"
224      ("gif")
225      ("jpeg")
226      ("png")
227      ("tiff")
228      ("x-pic")
229      ("x-mag")
230      ("x-xwd")
231      ("x-xbm")
232      )
233     ("audio" ("basic"))
234     ("video" ("mpeg"))
235     )
236   "*Alist of content-type, subtype, parameters and its values.")
237
238 (defcustom mime-file-types
239   '(
240
241     ;; Programming languages
242
243     ("\\.cc$"
244      "application" "octet-stream" (("type" . "C++"))
245      "7bit"
246      "attachment"       (("filename" . file))
247      )
248
249     ("\\.el$"
250      "application" "octet-stream" (("type" . "emacs-lisp"))
251      "7bit"
252      "attachment"       (("filename" . file))
253      )
254
255     ("\\.lsp$"
256      "application" "octet-stream" (("type" . "common-lisp"))
257      "7bit"
258      "attachment"       (("filename" . file))
259      )
260
261     ("\\.pl$"
262      "application" "octet-stream" (("type" . "perl"))
263      "7bit"
264      "attachment"       (("filename" . file))
265      )
266
267     ;; Text or translated text
268
269     ("\\.txt$"
270      "text"     "plain"         nil
271      nil
272      "inline"           (("filename" . file))
273      )
274
275      ;; .rc : procmail modules pm-xxxx.rc
276      ;; *rc : other resource files
277
278     ("\\.\\(rc\\|lst\\|log\\|sql\\|mak\\)$\\|\\..*rc$"
279      "text"     "plain"         nil
280      nil
281      "attachment"       (("filename" . file))
282      )
283
284     ("\\.html$"
285      "text"     "html"          nil
286      nil
287      nil                nil)
288
289     ("\\.diff$\\|\\.patch$"
290      "application" "octet-stream" (("type" . "patch"))
291      nil
292      "attachment"       (("filename" . file))
293      )
294
295     ("\\.signature"
296      "text"     "plain"         nil     nil     nil     nil)
297
298
299     ;;  Octect binary text
300
301     ("\\.doc$"                          ;MS Word
302      "application" "winword" nil
303      "base64"
304      "attachment" (("filename" . file))
305      )
306
307     ("\\.pln$"
308      "text"     "plain"         nil
309      nil
310      "inline"           (("filename" . file))
311      )
312     ("\\.ps$"
313      "application" "postscript" nil
314      "quoted-printable"
315      "attachment"       (("filename" . file))
316      )
317
318     ;;  Pure binary
319
320     ("\\.jpg$"
321      "image"    "jpeg"          nil
322      "base64"
323      "inline"           (("filename" . file))
324      )
325     ("\\.gif$"
326      "image"    "gif"           nil
327      "base64"
328      "inline"           (("filename" . file))
329      )
330     ("\\.png$"
331      "image"    "png"           nil
332      "base64"
333      "inline"           (("filename" . file))
334      )
335     ("\\.tiff$"
336      "image"    "tiff"          nil
337      "base64"
338      "inline"           (("filename" . file))
339      )
340     ("\\.pic$"
341      "image"    "x-pic"         nil
342      "base64"
343      "inline"           (("filename" . file))
344      )
345     ("\\.mag$"
346      "image"    "x-mag"         nil
347      "base64"
348      "inline"           (("filename" . file))
349      )
350     ("\\.xbm$"
351      "image"    "x-xbm"         nil
352      "base64"
353      "inline"           (("filename" . file))
354      )
355     ("\\.xwd$"
356      "image"    "x-xwd"         nil
357      "base64"
358      "inline"           (("filename" . file))
359      )
360     ("\\.au$"
361      "audio"    "basic"         nil
362      "base64"
363      "attachment"               (("filename" . file))
364      )
365     ("\\.mpg$"
366      "video"    "mpeg"          nil
367      "base64"
368      "attachment"       (("filename" . file))
369      )
370     ("\\.tar\\.gz$"
371      "application" "octet-stream" (("type" . "tar+gzip"))
372      "base64"
373      "attachment"       (("filename" . file))
374      )
375     ("\\.tgz$"
376      "application" "octet-stream" (("type" . "tar+gzip"))
377      "base64"
378      "attachment"       (("filename" . file))
379      )
380     ("\\.tar\\.Z$"
381      "application" "octet-stream" (("type" . "tar+compress"))
382      "base64"
383      "attachment"       (("filename" . file))
384      )
385     ("\\.taz$"
386      "application" "octet-stream" (("type" . "tar+compress"))
387      "base64"
388      "attachment"       (("filename" . file))
389      )
390     ("\\.gz$"
391      "application" "octet-stream" (("type" . "gzip"))
392      "base64"
393      "attachment"       (("filename" . file))
394      )
395     ("\\.Z$"
396      "application" "octet-stream" (("type" . "compress"))
397      "base64"
398      "attachment"       (("filename" . file))
399      )
400     ("\\.lzh$"
401      "application" "octet-stream" (("type" . "lha"))
402      "base64"
403      "attachment"       (("filename" . file))
404      )
405     ("\\.zip$"
406      "application" "zip" nil
407      "base64"
408      "attachment"       (("filename" . file))
409      )
410
411     ;; Rest
412
413     (".*"
414      "application" "octet-stream" nil
415      nil
416      "attachment"       (("filename" . file)))
417     )
418   "*Alist of file name, types, parameters, and default encoding.
419 If encoding is nil, it is determined from its contents."
420   :type `(repeat
421           (list regexp
422                 ;; primary-type
423                 (choice :tag "Primary-Type"
424                         ,@(nconc (mapcar (lambda (cell)
425                                            (list 'item (car cell))
426                                            )
427                                          mime-content-types)
428                                  '(string)))
429                 ;; subtype
430                 (choice :tag "Sub-Type"
431                         ,@(nconc
432                            (apply #'nconc
433                                   (mapcar (lambda (cell)
434                                             (mapcar (lambda (cell)
435                                                       (list 'item (car cell))
436                                                       )
437                                                     (cdr cell)))
438                                           mime-content-types))
439                            '(string)))
440                 ;; parameters
441                 (repeat :tag "Parameters of Content-Type field"
442                         (cons string (choice string symbol)))
443                 ;; content-transfer-encoding
444                 (choice :tag "Encoding"
445                         ,@(cons
446                            '(const nil)
447                            (mapcar (lambda (cell)
448                                      (list 'item cell)
449                                      )
450                                    (mime-encoding-list))))
451                 ;; disposition-type
452                 (choice :tag "Disposition-Type"
453                         (item nil)
454                         (item "inline")
455                         (item "attachment")
456                         string)
457                 ;; parameters
458                 (repeat :tag "Parameters of Content-Disposition field"
459                         (cons string (choice string symbol)))
460                 ))
461   :group 'mime-edit)
462
463
464 ;;; @@ about charset, encoding and transfer-level
465 ;;;
466
467 (defvar mime-charset-type-list
468   '((us-ascii           7 nil)
469     (iso-8859-1         8 "quoted-printable")
470     (iso-8859-2         8 "quoted-printable")
471     (iso-8859-3         8 "quoted-printable")
472     (iso-8859-4         8 "quoted-printable")
473     (iso-8859-5         8 "quoted-printable")
474     (koi8-r             8 "quoted-printable")
475     (iso-8859-7         8 "quoted-printable")
476     (iso-8859-8         8 "quoted-printable")
477     (iso-8859-9         8 "quoted-printable")
478     (iso-2022-jp        7 "base64")
479     (iso-2022-kr        7 "base64")
480     (euc-kr             8 "base64")
481     (cn-gb              8 "base64")
482     (gb2312             8 "base64")
483     (cn-big5            8 "base64")
484     (big5               8 "base64")
485     (shift_jis          8 "base64")
486     (iso-2022-jp-2      7 "base64")
487     (iso-2022-int-1     7 "base64")
488     ))
489
490 (defvar mime-transfer-level 7
491   "*A number of network transfer level.  It should be bigger than 7.")
492 (make-variable-buffer-local 'mime-transfer-level)
493
494 (defsubst mime-encoding-name (transfer-level &optional not-omit)
495   (cond ((> transfer-level 8) "binary")
496         ((= transfer-level 8) "8bit")
497         (not-omit "7bit")
498         ))
499
500 (defvar mime-transfer-level-string
501   (mime-encoding-name mime-transfer-level 'not-omit)
502   "A string formatted version of mime-transfer-level")
503 (make-variable-buffer-local 'mime-transfer-level-string)
504
505 (put 'iso-2022-jp-2 'mime-charset-comment "RFC1554")
506 (put 'iso-2022-jp 'mime-charset-comment "RFC1468 with trivial bugfix")
507
508 ;;; @@ about content transfer encoding
509
510 (defvar mime-content-transfer-encoding-priority-list
511   '(nil "8bit" "binary"))
512
513 ;;; @@ about message inserting
514 ;;;
515
516 (defvar mime-edit-yank-ignored-field-list
517   '("Received" "Approved" "Path" "Replied" "Status"
518     "Xref" "X-UIDL" "X-Filter" "X-Gnus-.*" "X-VM-.*")
519   "Delete these fields from original message when it is inserted
520 as message/rfc822 part.
521 Each elements are regexp of field-name.")
522
523 (defvar mime-edit-yank-ignored-field-regexp
524   (concat "^"
525           (apply (function regexp-or) mime-edit-yank-ignored-field-list)
526           ":"))
527
528 (defvar mime-edit-message-inserter-alist nil)
529 (defvar mime-edit-mail-inserter-alist nil)
530
531
532 ;;; @@ about message splitting
533 ;;;
534
535 (defcustom mime-edit-split-message t
536   "*Split large message if it is non-nil."
537   :group 'mime-edit
538   :type 'boolean)
539
540 (defcustom mime-edit-message-default-max-lines 1000
541   "*Default maximum lines of a message."
542   :group 'mime-edit
543   :type 'integer)
544
545 (defcustom mime-edit-message-max-lines-alist
546   '((news-reply-mode . 500))
547   "Alist of major-mode vs maximum lines of a message.
548 If it is not specified for a major-mode,
549 `mime-edit-message-default-max-lines' is used."
550   :group 'mime-edit
551   :type 'list)
552
553 (defconst mime-edit-split-ignored-field-regexp
554   "\\(^Content-\\|^Subject:\\|^Mime-Version:\\|^Message-Id:\\)")
555
556 (defcustom mime-edit-split-blind-field-regexp
557   "\\(^[BDFbdf]cc:\\|^cc:[ \t]*$\\)"
558   "*Regular expression to match field-name to be ignored when split sending."
559   :group 'mime-edit
560   :type 'regexp)
561
562 (defvar mime-edit-split-message-sender-alist nil)
563
564 (defvar mime-edit-news-reply-mode-server-running nil)
565
566
567 ;;; @@ about tag
568 ;;;
569
570 (defconst mime-edit-single-part-tag-regexp
571   "--[[][[]\\([^]]*\\)]\\([[]\\([^]]*\\)]\\|\\)]"
572   "*Regexp of MIME tag in the form of [[CONTENT-TYPE][ENCODING]].")
573
574 (defconst mime-edit-quoted-single-part-tag-regexp
575   (concat "- " (substring mime-edit-single-part-tag-regexp 1)))
576
577 (defconst mime-edit-multipart-beginning-regexp "--<<\\([^<>]+\\)>>-{\n")
578
579 (defconst mime-edit-multipart-end-regexp "--}-<<\\([^<>]+\\)>>\n")
580
581 (defconst mime-edit-beginning-tag-regexp
582   (regexp-or mime-edit-single-part-tag-regexp
583              mime-edit-multipart-beginning-regexp))
584
585 (defconst mime-edit-end-tag-regexp
586   (regexp-or mime-edit-single-part-tag-regexp
587              mime-edit-multipart-end-regexp))
588
589 (defconst mime-edit-tag-regexp
590   (regexp-or mime-edit-single-part-tag-regexp
591              mime-edit-multipart-beginning-regexp
592              mime-edit-multipart-end-regexp))
593
594 (defvar mime-tag-format "--[[%s]]"
595   "*Control-string making a MIME tag.")
596
597 (defvar mime-tag-format-with-encoding "--[[%s][%s]]"
598   "*Control-string making a MIME tag with encoding.")
599
600
601 ;;; @@ multipart boundary
602 ;;;
603
604 (defvar mime-multipart-boundary "Multipart"
605   "*Boundary of a multipart message.")
606
607
608 ;;; @@ optional header fields
609 ;;;
610
611 (defvar mime-edit-insert-user-agent-field t
612   "*If non-nil, insert User-Agent header field.")
613
614 (defvar mime-edit-user-agent-value
615   (concat (mime-product-name mime-user-interface-product)
616           "/"
617           (mapconcat #'number-to-string
618                      (mime-product-version mime-user-interface-product) ".")
619           " ("
620           (mime-product-code-name mime-user-interface-product)
621           ") "
622           (mime-product-name mime-library-product)
623           "/"
624           (mapconcat #'number-to-string
625                      (mime-product-version mime-library-product) ".")
626           " ("
627           (mime-product-code-name mime-library-product)
628           ") "
629           (if (featurep 'xemacs)
630               (concat (if (featurep 'mule) "MULE")
631                       " XEmacs"
632                       (if (string-match "\\s +\\\"" emacs-version)
633                           (concat "/"
634                                   (substring emacs-version 0
635                                              (match-beginning 0))
636                                   (if (and (boundp 'xemacs-betaname)
637                                            ;; It does not exist in XEmacs
638                                            ;; versions prior to 20.3.
639                                            xemacs-betaname)
640                                       (concat " " xemacs-betaname)
641                                     "")
642                                   " (" xemacs-codename ") ("
643                                   system-configuration ")")
644                         " (" emacs-version ")"))
645             (let ((ver (if (string-match "\\.[0-9]+$" emacs-version)
646                            (substring emacs-version 0 (match-beginning 0))
647                          emacs-version)))
648               (if (featurep 'mule)
649                   (if (boundp 'enable-multibyte-characters)
650                       (concat "Emacs/" ver
651                               " (" system-configuration ")"
652                               (if enable-multibyte-characters
653                                   (concat " MULE/" mule-version)
654                                 " (with unibyte mode)")
655                               (if (featurep 'meadow)
656                                   (let ((mver (Meadow-version)))
657                                     (if (string-match "^Meadow-" mver)
658                                         (concat " Meadow/"
659                                                 (substring mver
660                                                            (match-end 0)))
661                                       ))))
662                     (concat "MULE/" mule-version
663                             " (based on Emacs " ver ")"))
664                 (concat "Emacs/" ver " (" system-configuration ")")))))
665   "Body of User-Agent field.
666 If variable `mime-edit-insert-user-agent-field' is not nil, it is
667 inserted into message header.")
668
669 \f
670 ;;; @ constants
671 ;;;
672
673 (defconst mime-tspecials-regexp "[][()<>@,;:\\\"/?.= \t]"
674   "*Specify MIME tspecials.
675 Tspecials means any character that matches with it in header must be quoted.")
676
677 (defconst mime-edit-mime-version-value
678   (eval-when-compile
679     (concat "1.0 (generated by " mime-edit-version ")"))
680   "MIME version number.")
681
682 (defconst mime-edit-mime-version-field-for-message/partial
683   (eval-when-compile
684     (concat "MIME-Version: 1.0 (split by " mime-edit-version ")\n"))
685   "MIME version field for message/partial.")
686
687
688 ;;; @ keymap and menu
689 ;;;
690
691 (defvar mime-edit-mode-flag nil)
692 (make-variable-buffer-local 'mime-edit-mode-flag)
693
694 (defvar mime-edit-mode-entity-prefix "\C-c\C-x"
695   "Keymap prefix for MIME-Edit mode commands to insert entity or set status.")
696 (defvar mime-edit-mode-entity-map (make-sparse-keymap)
697   "Keymap for MIME-Edit mode commands to insert entity or set status.")
698
699 (define-key mime-edit-mode-entity-map "\C-t" 'mime-edit-insert-text)
700 (define-key mime-edit-mode-entity-map "\C-i" 'mime-edit-insert-file)
701 (define-key mime-edit-mode-entity-map "\C-e" 'mime-edit-insert-external)
702 (define-key mime-edit-mode-entity-map "\C-v" 'mime-edit-insert-voice)
703 (define-key mime-edit-mode-entity-map "\C-y" 'mime-edit-insert-message)
704 (define-key mime-edit-mode-entity-map "\C-m" 'mime-edit-insert-mail)
705 (define-key mime-edit-mode-entity-map "\C-w" 'mime-edit-insert-signature)
706 (define-key mime-edit-mode-entity-map "\C-s" 'mime-edit-insert-signature)
707 (define-key mime-edit-mode-entity-map "\C-k" 'mime-edit-insert-key)
708 (define-key mime-edit-mode-entity-map "t"    'mime-edit-insert-tag)
709
710 (define-key mime-edit-mode-entity-map "7" 'mime-edit-set-transfer-level-7bit)
711 (define-key mime-edit-mode-entity-map "8" 'mime-edit-set-transfer-level-8bit)
712 (define-key mime-edit-mode-entity-map "/" 'mime-edit-set-split)
713 (define-key mime-edit-mode-entity-map "s" 'mime-edit-set-sign)
714 (define-key mime-edit-mode-entity-map "v" 'mime-edit-set-sign)
715 (define-key mime-edit-mode-entity-map "e" 'mime-edit-set-encrypt)
716 (define-key mime-edit-mode-entity-map "h" 'mime-edit-set-encrypt)
717 (define-key mime-edit-mode-entity-map "p" 'mime-edit-preview-message)
718 (define-key mime-edit-mode-entity-map "\C-z" 'mime-edit-exit)
719 (define-key mime-edit-mode-entity-map "?" 'mime-edit-help)
720
721 (defvar mime-edit-mode-enclosure-prefix "\C-c\C-m"
722   "Keymap prefix for MIME-Edit mode commands about enclosure.")
723 (defvar mime-edit-mode-enclosure-map (make-sparse-keymap)
724   "Keymap for MIME-Edit mode commands about enclosure.")
725
726 (define-key mime-edit-mode-enclosure-map
727   "\C-a" 'mime-edit-enclose-alternative-region)
728 (define-key mime-edit-mode-enclosure-map
729   "\C-p" 'mime-edit-enclose-parallel-region)
730 (define-key mime-edit-mode-enclosure-map
731   "\C-m" 'mime-edit-enclose-mixed-region)
732 (define-key mime-edit-mode-enclosure-map
733   "\C-d" 'mime-edit-enclose-digest-region)
734 (define-key mime-edit-mode-enclosure-map
735   "\C-s" 'mime-edit-enclose-pgp-signed-region)
736 (define-key mime-edit-mode-enclosure-map
737   "\C-e" 'mime-edit-enclose-pgp-encrypted-region)
738 (define-key mime-edit-mode-enclosure-map
739   "\C-q" 'mime-edit-enclose-quote-region)
740
741 (defvar mime-edit-mode-map (make-sparse-keymap)
742   "Keymap for MIME-Edit mode commands.")
743 (define-key mime-edit-mode-map
744   mime-edit-mode-entity-prefix mime-edit-mode-entity-map)
745 (define-key mime-edit-mode-map
746   mime-edit-mode-enclosure-prefix mime-edit-mode-enclosure-map)
747
748 (defconst mime-edit-menu-title "MIME-Edit")
749
750 (defconst mime-edit-menu-list
751   '((mime-help  "Describe MIME editor mode" mime-edit-help)
752     (file       "Insert File"           mime-edit-insert-file)
753     (external   "Insert External"       mime-edit-insert-external)
754     (voice      "Insert Voice"          mime-edit-insert-voice)
755     (message    "Insert Message"        mime-edit-insert-message)
756     (mail       "Insert Mail"           mime-edit-insert-mail)
757     (signature  "Insert Signature"      mime-edit-insert-signature)
758     (text       "Insert Text"           mime-edit-insert-text)
759     (tag        "Insert Tag"            mime-edit-insert-tag)
760     (alternative "Enclose as alternative"
761                  mime-edit-enclose-alternative-region)
762     (parallel   "Enclose as parallel"   mime-edit-enclose-parallel-region)
763     (mixed      "Enclose as serial"     mime-edit-enclose-mixed-region)
764     (digest     "Enclose as digest"     mime-edit-enclose-digest-region)
765     (signed     "Enclose as signed"     mime-edit-enclose-pgp-signed-region)
766     (encrypted  "Enclose as encrypted"  mime-edit-enclose-pgp-encrypted-region)
767     (quote      "Verbatim region"       mime-edit-enclose-quote-region)
768     (key        "Insert Public Key"     mime-edit-insert-key)
769     (split      "About split"           mime-edit-set-split)
770     (sign       "About sign"            mime-edit-set-sign)
771     (encrypt    "About encryption"      mime-edit-set-encrypt)
772     (preview    "Preview Message"       mime-edit-preview-message)
773     (level      "Toggle transfer-level" mime-edit-toggle-transfer-level)
774     )
775   "MIME-edit menubar entry.")
776
777 (cond ((featurep 'xemacs)
778        ;; modified by Pekka Marjola <pema@iki.fi>
779        ;;       1995/9/5 (c.f. [tm-en:69])
780        (defun mime-edit-define-menu-for-xemacs ()
781          "Define menu for XEmacs."
782          (cond ((featurep 'menubar)
783                 (make-local-variable 'current-menubar)
784                 (set-buffer-menubar current-menubar)
785                 (add-submenu
786                  nil
787                  (cons mime-edit-menu-title
788                        (mapcar (function
789                                 (lambda (item)
790                                   (vector (nth 1 item)(nth 2 item)
791                                           mime-edit-mode-flag)
792                                   ))
793                                mime-edit-menu-list)))
794                 )))
795
796        ;; modified by Steven L. Baur <steve@miranova.com>
797        ;;       1995/12/6 (c.f. [tm-en:209])
798        (or (boundp 'mime-edit-popup-menu-for-xemacs)
799            (setq mime-edit-popup-menu-for-xemacs
800                  (append '("MIME Commands" "---")
801                          (mapcar (function (lambda (item)
802                                              (vector (nth 1 item)
803                                                      (nth 2 item)
804                                                      t)))
805                                  mime-edit-menu-list)))
806            )
807        )
808       ((>= emacs-major-version 19)
809        (define-key mime-edit-mode-map [menu-bar mime-edit]
810          (cons mime-edit-menu-title
811                (make-sparse-keymap mime-edit-menu-title)))
812        (mapcar (function
813                 (lambda (item)
814                   (define-key mime-edit-mode-map
815                     (vector 'menu-bar 'mime-edit (car item))
816                     (cons (nth 1 item)(nth 2 item))
817                     )
818                   ))
819                (reverse mime-edit-menu-list)
820                )
821        ))
822
823
824 ;;; @ functions
825 ;;;
826
827 (defvar mime-edit-touched-flag nil)
828
829 ;;;###autoload
830 (defun mime-edit-mode ()
831   "MIME minor mode for editing the tagged MIME message.
832
833 In this mode, basically, the message is composed in the tagged MIME
834 format. The message tag looks like:
835
836         --[[text/plain; charset=ISO-2022-JP][7bit]]
837
838 The tag specifies the MIME content type, subtype, optional parameters
839 and transfer encoding of the message following the tag.  Messages
840 without any tag are treated as `text/plain' by default.  Charset and
841 transfer encoding are automatically defined unless explicitly
842 specified.  Binary messages such as audio and image are usually
843 hidden.  The messages in the tagged MIME format are automatically
844 translated into a MIME compliant message when exiting this mode.
845
846 Available charsets depend on Emacs version being used.  The following
847 lists the available charsets of each emacs.
848
849 Without mule:   US-ASCII and ISO-8859-1 (or other charset) are available.
850 With mule:      US-ASCII, ISO-8859-* (except for ISO-8859-5), KOI8-R,
851                 ISO-2022-JP, ISO-2022-JP-2, EUC-KR, CN-GB-2312,
852                 CN-BIG5 and ISO-2022-INT-1 are available.
853
854 ISO-2022-JP-2 and ISO-2022-INT-1 charsets used in mule is expected to
855 be used to represent multilingual text in intermixed manner.  Any
856 languages that has no registered charset are represented as either
857 ISO-2022-JP-2 or ISO-2022-INT-1 in mule.
858
859 If you want to use non-ISO-8859-1 charset in Emacs 19 or XEmacs
860 without mule, please set variable `default-mime-charset'.  This
861 variable must be symbol of which name is a MIME charset.
862
863 If you want to add more charsets in mule, please set variable
864 `charsets-mime-charset-alist'.  This variable must be alist of which
865 key is list of charset and value is symbol of MIME charset.  If name
866 of coding-system is different as MIME charset, please set variable
867 `mime-charset-coding-system-alist'.  This variable must be alist of
868 which key is MIME charset and value is coding-system.
869
870 Following commands are available in addition to major mode commands:
871
872 \[make single part\]
873 \\[mime-edit-insert-text]       insert a text message.
874 \\[mime-edit-insert-file]       insert a (binary) file.
875 \\[mime-edit-insert-external]   insert a reference to external body.
876 \\[mime-edit-insert-voice]      insert a voice message.
877 \\[mime-edit-insert-message]    insert a mail or news message.
878 \\[mime-edit-insert-mail]       insert a mail message.
879 \\[mime-edit-insert-signature]  insert a signature file at end.
880 \\[mime-edit-insert-key]        insert PGP public key.
881 \\[mime-edit-insert-tag]        insert a new MIME tag.
882
883 \[make enclosure (maybe multipart)\]
884 \\[mime-edit-enclose-alternative-region]   enclose as multipart/alternative.
885 \\[mime-edit-enclose-parallel-region]      enclose as multipart/parallel.
886 \\[mime-edit-enclose-mixed-region]         enclose as multipart/mixed.
887 \\[mime-edit-enclose-digest-region]        enclose as multipart/digest.
888 \\[mime-edit-enclose-pgp-signed-region]    enclose as PGP signed.
889 \\[mime-edit-enclose-pgp-encrypted-region] enclose as PGP encrypted.
890 \\[mime-edit-enclose-quote-region]         enclose as verbose mode
891                                            (to avoid to expand tags)
892
893 \[other commands\]
894 \\[mime-edit-set-transfer-level-7bit]   set transfer-level as 7.
895 \\[mime-edit-set-transfer-level-8bit]   set transfer-level as 8.
896 \\[mime-edit-set-split]                 set message splitting mode.
897 \\[mime-edit-set-sign]                  set PGP-sign mode.
898 \\[mime-edit-set-encrypt]               set PGP-encryption mode.
899 \\[mime-edit-preview-message]           preview editing MIME message.
900 \\[mime-edit-exit]                      exit and translate into a MIME
901                                         compliant message.
902 \\[mime-edit-help]                      show this help.
903 \\[mime-edit-maybe-translate]           exit and translate if in MIME mode,
904                                         then split.
905
906 Additional commands are available in some major modes:
907 C-c C-c         exit, translate and run the original command.
908 C-c C-s         exit, translate and run the original command.
909
910 The following is a message example written in the tagged MIME format.
911 TABs at the beginning of the line are not a part of the message:
912
913         This is a conventional plain text.  It should be translated
914         into text/plain.
915         --[[text/plain]]
916         This is also a plain text.  But, it is explicitly specified as
917         is.
918         --[[text/plain; charset=ISO-8859-1]]
919         This is also a plain text.  But charset is specified as
920         iso-8859-1.
921
922         ¡Hola!  Buenos días.  ¿Cómo está usted?
923         --[[text/enriched]]
924         This is a <bold>enriched text</bold>.
925         --[[image/gif][base64]]...image encoded in base64 here...
926         --[[audio/basic][base64]]...audio encoded in base64 here...
927
928 User customizable variables (not documented all of them):
929  mime-edit-prefix
930     Specifies a key prefix for MIME minor mode commands.
931
932  mime-ignore-preceding-spaces
933     Preceding white spaces in a message body are ignored if non-nil.
934
935  mime-ignore-trailing-spaces
936     Trailing white spaces in a message body are ignored if non-nil.
937
938  mime-auto-hide-body
939     Hide a non-textual body message encoded in base64 after insertion
940     if non-nil.
941
942  mime-transfer-level
943     A number of network transfer level.  It should be bigger than 7.
944     If you are in 8bit-through environment, please set 8.
945
946  mime-edit-voice-recorder
947     Specifies a function to record a voice message and encode it.
948     The function `mime-edit-voice-recorder-for-sun' is for Sun
949     SparcStations.
950
951  mime-edit-mode-hook
952     Turning on MIME mode calls the value of mime-edit-mode-hook, if
953     it is non-nil.
954
955  mime-edit-translate-hook
956     The value of mime-edit-translate-hook is called just before translating
957     the tagged MIME format into a MIME compliant message if it is
958     non-nil.  If the hook call the function mime-edit-insert-signature,
959     the signature file will be inserted automatically.
960
961  mime-edit-exit-hook
962     Turning off MIME mode calls the value of mime-edit-exit-hook, if it is
963     non-nil."
964   (interactive)
965   (if mime-edit-mode-flag
966       (mime-edit-exit)
967     (if mime-edit-touched-flag
968         (mime-edit-again)
969       (make-local-variable 'mime-edit-touched-flag)
970       (setq mime-edit-touched-flag t)
971       (turn-on-mime-edit)
972       )))
973
974
975 (cond ((featurep 'xemacs)
976        (add-minor-mode 'mime-edit-mode-flag
977                        '((" MIME-Edit "  mime-transfer-level-string))
978                        mime-edit-mode-map
979                        nil
980                        'mime-edit-mode)
981        )
982       (t
983        (set-alist 'minor-mode-alist
984                   'mime-edit-mode-flag
985                   '((" MIME-Edit "  mime-transfer-level-string)))
986        (set-alist 'minor-mode-map-alist
987                   'mime-edit-mode-flag
988                   mime-edit-mode-map)
989        ))
990
991
992 ;;;###autoload
993 (defun turn-on-mime-edit ()
994   "Unconditionally turn on MIME-Edit mode."
995   (interactive)
996   (if mime-edit-mode-flag
997       (error "You are already editing a MIME message.")
998     (setq mime-edit-mode-flag t)
999
1000     ;; Set transfer level into mode line
1001     ;;
1002     (setq mime-transfer-level-string
1003           (mime-encoding-name mime-transfer-level 'not-omit))
1004     (force-mode-line-update)
1005
1006     ;; Define menu for XEmacs.
1007     (if (featurep 'xemacs)
1008         (mime-edit-define-menu-for-xemacs)
1009       )
1010
1011     (enable-invisible)
1012
1013     ;; I don't care about saving these.
1014     (setq paragraph-start
1015           (regexp-or mime-edit-single-part-tag-regexp
1016                      paragraph-start))
1017     (setq paragraph-separate
1018           (regexp-or mime-edit-single-part-tag-regexp
1019                      paragraph-separate))
1020     (run-hooks 'mime-edit-mode-hook)
1021     (message
1022      (substitute-command-keys
1023       "Type \\[mime-edit-exit] to exit MIME mode, and type \\[mime-edit-help] to get help."))
1024     ))
1025
1026 ;;;###autoload
1027 (defalias 'edit-mime 'turn-on-mime-edit) ; for convenience
1028
1029
1030 (defun mime-edit-exit (&optional nomime no-error)
1031   "Translate the tagged MIME message into a MIME compliant message.
1032 With no argument encode a message in the buffer into MIME, otherwise
1033 just return to previous mode."
1034   (interactive "P")
1035   (if (not mime-edit-mode-flag)
1036       (if (null no-error)
1037           (error "You aren't editing a MIME message.")
1038         )
1039     (if (not nomime)
1040         (progn
1041           (run-hooks 'mime-edit-translate-hook)
1042           (mime-edit-translate-buffer)))
1043     ;; Restore previous state.
1044     (setq mime-edit-mode-flag nil)
1045     (if (and (featurep 'xemacs)
1046              (featurep 'menubar))
1047         (delete-menu-item (list mime-edit-menu-title))
1048       )
1049     (end-of-invisible)
1050     (set-buffer-modified-p (buffer-modified-p))
1051     (run-hooks 'mime-edit-exit-hook)
1052     (message "Exit MIME editor mode.")
1053     ))
1054
1055 (defun mime-edit-maybe-translate ()
1056   (interactive)
1057   (mime-edit-exit nil t)
1058   (call-interactively 'mime-edit-maybe-split-and-send)
1059   )
1060
1061 (defun mime-edit-help ()
1062   "Show help message about MIME mode."
1063   (interactive)
1064   (with-output-to-temp-buffer "*Help*"
1065     (princ "MIME editor mode:\n")
1066     (princ (documentation 'mime-edit-mode))
1067     (print-help-return-message)))
1068
1069 (defun mime-edit-insert-text (&optional subtype)
1070   "Insert a text message.
1071 Charset is automatically obtained from the `charsets-mime-charset-alist'.
1072 If optional argument SUBTYPE is not nil, text/SUBTYPE tag is inserted."
1073   (interactive)
1074   (let ((ret (mime-edit-insert-tag "text" subtype nil)))
1075     (when ret
1076       (if (looking-at mime-edit-single-part-tag-regexp)
1077           (progn
1078             ;; Make a space between the following message.
1079             (insert "\n")
1080             (forward-char -1)
1081             ))
1082       (if (and (member (cadr ret) '("enriched"))
1083                (fboundp 'enriched-mode))
1084           (enriched-mode t)
1085         (if (boundp 'enriched-mode)
1086             (enriched-mode -1)
1087           ))
1088       )))
1089
1090 (defun mime-edit-insert-file (file &optional verbose)
1091   "Insert a message from a file."
1092   (interactive "fInsert file as MIME message: \nP")
1093   (let*  ((guess (mime-find-file-type file))
1094           (type (nth 0 guess))
1095           (subtype (nth 1 guess))
1096           (parameters (nth 2 guess))
1097           (encoding (nth 3 guess))
1098           (disposition-type (nth 4 guess))
1099           (disposition-params (nth 5 guess))
1100           )
1101     (if verbose
1102         (setq type    (mime-prompt-for-type type)
1103               subtype (mime-prompt-for-subtype type subtype)
1104               ))
1105     (if (or (interactive-p) verbose)
1106         (setq encoding (mime-prompt-for-encoding encoding))
1107       )
1108     (if (or (consp parameters) (stringp disposition-type))
1109         (let ((rest parameters) cell attribute value)
1110           (setq parameters "")
1111           (while rest
1112             (setq cell (car rest))
1113             (setq attribute (car cell))
1114             (setq value (cdr cell))
1115             (if (eq value 'file)
1116                 (setq value (std11-wrap-as-quoted-string
1117                              (file-name-nondirectory file)))
1118               )
1119             (setq parameters (concat parameters "; " attribute "=" value))
1120             (setq rest (cdr rest))
1121             )
1122           (if disposition-type
1123               (progn
1124                 (setq parameters
1125                       (concat parameters "\n"
1126                               "Content-Disposition: " disposition-type))
1127                 (setq rest disposition-params)
1128                 (while rest
1129                   (setq cell (car rest))
1130                   (setq attribute (car cell))
1131                   (setq value (cdr cell))
1132                   (if (eq value 'file)
1133                       (setq value (std11-wrap-as-quoted-string
1134                                    (file-name-nondirectory file)))
1135                     )
1136                   (setq parameters
1137                         (concat parameters "; " attribute "=" value))
1138                   (setq rest (cdr rest))
1139                   )
1140                 ))
1141           ))
1142     (mime-edit-insert-tag type subtype parameters)
1143     (mime-edit-insert-binary-file file encoding)
1144     ))
1145
1146 (defun mime-edit-insert-external ()
1147   "Insert a reference to external body."
1148   (interactive)
1149   (mime-edit-insert-tag "message" "external-body" nil ";\n\t")
1150   ;;(forward-char -1)
1151   ;;(insert "Content-Description: " (read-string "Content-Description: ") "\n")
1152   ;;(forward-line 1)
1153   (let* ((pritype (mime-prompt-for-type))
1154          (subtype (mime-prompt-for-subtype pritype))
1155          (parameters (mime-prompt-for-parameters pritype subtype ";\n\t")))
1156     (and pritype
1157          subtype
1158          (insert "Content-Type: "
1159                  pritype "/" subtype (or parameters "") "\n")))
1160   (if (and (not (eobp))
1161            (not (looking-at mime-edit-single-part-tag-regexp)))
1162       (insert (mime-make-text-tag) "\n")))
1163
1164 (defun mime-edit-insert-voice ()
1165   "Insert a voice message."
1166   (interactive)
1167   (let ((encoding
1168          (completing-read
1169           "What transfer encoding: "
1170           (mime-encoding-alist) nil t nil)))
1171     (mime-edit-insert-tag "audio" "basic" nil)
1172     (mime-edit-define-encoding encoding)
1173     (save-restriction
1174       (narrow-to-region (1- (point))(point))
1175       (unwind-protect
1176           (funcall mime-edit-voice-recorder encoding)
1177         (progn
1178           (insert "\n")
1179           (invisible-region (point-min)(point-max))
1180           (goto-char (point-max))
1181           )))))
1182
1183 (defun mime-edit-insert-signature (&optional arg)
1184   "Insert a signature file."
1185   (interactive "P")
1186   (let ((signature-insert-hook
1187          (function
1188           (lambda ()
1189             (let ((items (mime-find-file-type signature-file-name)))
1190               (apply (function mime-edit-insert-tag)
1191                      (car items) (cadr items) (list (caddr items))))
1192             )))
1193         )
1194     (insert-signature arg)
1195     ))
1196
1197 \f
1198 ;; Insert a new tag around a point.
1199
1200 (defun mime-edit-insert-tag (&optional pritype subtype parameters delimiter)
1201   "Insert new MIME tag and return a list of PRITYPE, SUBTYPE, and PARAMETERS.
1202 If nothing is inserted, return nil."
1203   (interactive)
1204   (let ((p (point)))
1205     (mime-edit-goto-tag)
1206     (if (and (re-search-forward mime-edit-tag-regexp nil t)
1207              (< (match-beginning 0) p)
1208              (< p (match-end 0))
1209              )
1210         (goto-char (match-beginning 0))
1211       (goto-char p)
1212       ))
1213   (let ((oldtag nil)
1214         (newtag nil)
1215         (current (point))
1216         )
1217     (setq pritype
1218           (or pritype
1219               (mime-prompt-for-type)))
1220     (setq subtype
1221           (or subtype
1222               (mime-prompt-for-subtype pritype)))
1223     (setq parameters
1224           (or parameters
1225               (mime-prompt-for-parameters pritype subtype delimiter)))
1226     ;; Make a new MIME tag.
1227     (setq newtag (mime-make-tag pritype subtype parameters))
1228     ;; Find an current MIME tag.
1229     (setq oldtag
1230           (save-excursion
1231             (if (mime-edit-goto-tag)
1232                 (buffer-substring (match-beginning 0) (match-end 0))
1233               ;; Assume content type is 'text/plan'.
1234               (mime-make-tag "text" "plain")
1235               )))
1236     ;; We are only interested in TEXT.
1237     (if (and oldtag
1238              (not (mime-test-content-type
1239                    (mime-edit-get-contype oldtag) "text")))
1240         (setq oldtag nil))
1241     ;; Make a new tag.
1242     (if (or (not oldtag)                ;Not text
1243             (or mime-ignore-same-text-tag
1244                 (not (string-equal oldtag newtag))))
1245         (progn
1246           ;; Mark the beginning of the tag for convenience.
1247           (push-mark (point) 'nomsg)
1248           (insert newtag "\n")
1249           (list pritype subtype parameters) ;New tag is created.
1250           )
1251       ;; Restore previous point.
1252       (goto-char current)
1253       nil                               ;Nothing is created.
1254       )
1255     ))
1256
1257 (defun mime-edit-insert-binary-file (file &optional encoding)
1258   "Insert binary FILE at point.
1259 Optional argument ENCODING specifies an encoding method such as base64."
1260   (let* ((tagend (1- (point)))          ;End of the tag
1261          (hide-p (and mime-auto-hide-body
1262                       (stringp encoding)
1263                       (not
1264                        (let ((en (downcase encoding)))
1265                          (or (string-equal en "7bit")
1266                              (string-equal en "8bit")
1267                              (string-equal en "binary")
1268                              )))))
1269          )
1270     (save-restriction
1271       (narrow-to-region tagend (point))
1272       (mime-insert-encoded-file file encoding)
1273       (if hide-p
1274           (progn
1275             (invisible-region (point-min) (point-max))
1276             (goto-char (point-max))
1277             )
1278         (goto-char (point-max))
1279         ))
1280     (or hide-p
1281         (looking-at mime-edit-tag-regexp)
1282         (= (point)(point-max))
1283         (mime-edit-insert-tag "text" "plain")
1284         )
1285     ;; Define encoding even if it is 7bit.
1286     (if (stringp encoding)
1287         (save-excursion
1288           (goto-char tagend) ; Make sure which line the tag is on.
1289           (mime-edit-define-encoding encoding)
1290           ))
1291     ))
1292
1293 \f
1294 ;; Commands work on a current message flagment.
1295
1296 (defun mime-edit-goto-tag ()
1297   "Search for the beginning of the tagged MIME message."
1298   (let ((current (point)))
1299     (if (looking-at mime-edit-tag-regexp)
1300         t
1301       ;; At first, go to the end.
1302       (cond ((re-search-forward mime-edit-beginning-tag-regexp nil t)
1303              (goto-char (1- (match-beginning 0))) ;For multiline tag
1304              )
1305             (t
1306              (goto-char (point-max))
1307              ))
1308       ;; Then search for the beginning.
1309       (re-search-backward mime-edit-end-tag-regexp nil t)
1310       (or (looking-at mime-edit-beginning-tag-regexp)
1311           ;; Restore previous point.
1312           (progn
1313             (goto-char current)
1314             nil
1315             ))
1316       )))
1317
1318 (defun mime-edit-content-beginning ()
1319   "Return the point of the beginning of content."
1320   (save-excursion
1321     (let ((beg (save-excursion
1322                  (beginning-of-line) (point))))
1323       (if (mime-edit-goto-tag)
1324           (let ((top (point)))
1325             (goto-char (match-end 0))
1326             (if (and (= beg top)
1327                      (= (following-char) ?\^M))
1328                 (point)
1329               (forward-line 1)
1330               (point)))
1331         ;; Default text/plain tag.
1332         (goto-char (point-min))
1333         (re-search-forward
1334          (concat "\n" (regexp-quote mail-header-separator)
1335                  (if mime-ignore-preceding-spaces
1336                      "[ \t\n]*\n" "\n")) nil 'move)
1337         (point))
1338       )))
1339
1340 (defun mime-edit-content-end ()
1341   "Return the point of the end of content."
1342   (save-excursion
1343     (if (mime-edit-goto-tag)
1344         (progn
1345           (goto-char (match-end 0))
1346           (if (invisible-p (point))
1347               (next-visible-point (point))
1348             ;; Move to the end of this text.
1349             (if (re-search-forward mime-edit-tag-regexp nil 'move)
1350                 ;; Don't forget a multiline tag.
1351                 (goto-char (match-beginning 0))
1352               )
1353             (point)
1354             ))
1355       ;; Assume the message begins with text/plain.
1356       (goto-char (mime-edit-content-beginning))
1357       (if (re-search-forward mime-edit-tag-regexp nil 'move)
1358           ;; Don't forget a multiline tag.
1359           (goto-char (match-beginning 0)))
1360       (point))
1361     ))
1362
1363 (defun mime-edit-define-charset (charset)
1364   "Set charset of current tag to CHARSET."
1365   (save-excursion
1366     (if (mime-edit-goto-tag)
1367         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1368           (delete-region (match-beginning 0) (match-end 0))
1369           (insert
1370            (mime-create-tag
1371             (mime-edit-set-parameter
1372              (mime-edit-get-contype tag)
1373              "charset"
1374              (let ((comment (get charset 'mime-charset-comment)))
1375                (if comment
1376                    (concat (upcase (symbol-name charset)) " (" comment ")")
1377                  (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                      (progn (forward-line 1) (point)))
2171       )))
2172
2173 \f
2174 ;;;
2175 ;;; Platform dependent functions
2176 ;;;
2177
2178 ;; Sun implementations
2179
2180 (defun mime-edit-voice-recorder-for-sun (encoding)
2181   "Record voice in a buffer using Sun audio device,
2182 and insert data encoded as ENCODING."
2183   (message "Start the recording on %s.  Type C-g to finish the recording..."
2184            (system-name))
2185   (mime-insert-encoded-file "/dev/audio" encoding)
2186   )
2187
2188 \f
2189 ;;; @ Other useful commands.
2190 ;;;
2191
2192 ;; Message forwarding commands as content-type "message/rfc822".
2193
2194 (defun mime-edit-insert-message (&optional message)
2195   (interactive)
2196   (let ((inserter (cdr (assq major-mode mime-edit-message-inserter-alist))))
2197     (if (and inserter (fboundp inserter))
2198         (progn
2199           (mime-edit-insert-tag "message" "rfc822")
2200           (funcall inserter message)
2201           )
2202       (message "Sorry, I don't have message inserter for your MUA.")
2203       )))
2204
2205 (defun mime-edit-insert-mail (&optional message)
2206   (interactive)
2207   (let ((inserter (cdr (assq major-mode mime-edit-mail-inserter-alist))))
2208     (if (and inserter (fboundp inserter))
2209         (progn
2210           (mime-edit-insert-tag "message" "rfc822")
2211           (funcall inserter message)
2212           )
2213       (message "Sorry, I don't have mail inserter for your MUA.")
2214       )))
2215
2216 (defun mime-edit-inserted-message-filter ()
2217   (save-excursion
2218     (save-restriction
2219       (let ((header-start (point))
2220             (case-fold-search t)
2221             beg end)
2222         ;; for Emacs 18
2223         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2224         (if (re-search-forward "^$" (mark t))
2225             (narrow-to-region header-start (match-beginning 0))
2226           )
2227         (goto-char header-start)
2228         (while (and (re-search-forward
2229                      mime-edit-yank-ignored-field-regexp nil t)
2230                     (setq beg (match-beginning 0))
2231                     (setq end (1+ (std11-field-end)))
2232                     )
2233           (delete-region beg end)
2234           )
2235         ))))
2236
2237
2238 ;;; @ multipart enclosure
2239 ;;;
2240
2241 (defun mime-edit-enclose-region-internal (type beg end)
2242   (save-excursion
2243     (goto-char beg)
2244     (save-restriction
2245       (narrow-to-region beg end)
2246       (insert (format "--<<%s>>-{\n" type))
2247       (goto-char (point-max))
2248       (insert (format "--}-<<%s>>\n" type))
2249       (goto-char (point-max))
2250       )
2251     (or (looking-at mime-edit-beginning-tag-regexp)
2252         (eobp)
2253         (insert (mime-make-text-tag) "\n")
2254         )
2255     ))
2256
2257 (defun mime-edit-enclose-quote-region (beg end)
2258   (interactive "*r")
2259   (mime-edit-enclose-region-internal 'quote beg end)
2260   )
2261
2262 (defun mime-edit-enclose-mixed-region (beg end)
2263   (interactive "*r")
2264   (mime-edit-enclose-region-internal 'mixed beg end)
2265   )
2266
2267 (defun mime-edit-enclose-parallel-region (beg end)
2268   (interactive "*r")
2269   (mime-edit-enclose-region-internal 'parallel beg end)
2270   )
2271
2272 (defun mime-edit-enclose-digest-region (beg end)
2273   (interactive "*r")
2274   (mime-edit-enclose-region-internal 'digest beg end)
2275   )
2276
2277 (defun mime-edit-enclose-alternative-region (beg end)
2278   (interactive "*r")
2279   (mime-edit-enclose-region-internal 'alternative beg end)
2280   )
2281
2282 (defun mime-edit-enclose-pgp-signed-region (beg end)
2283   (interactive "*r")
2284   (mime-edit-enclose-region-internal 'pgp-signed beg end)
2285   )
2286
2287 (defun mime-edit-enclose-pgp-encrypted-region (beg end)
2288   (interactive "*r")
2289   (mime-edit-enclose-region-internal 'pgp-encrypted beg end)
2290   )
2291
2292 (defun mime-edit-enclose-kazu-signed-region (beg end)
2293   (interactive "*r")
2294   (mime-edit-enclose-region-internal 'kazu-signed beg end)
2295   )
2296
2297 (defun mime-edit-enclose-kazu-encrypted-region (beg end)
2298   (interactive "*r")
2299   (mime-edit-enclose-region-internal 'kazu-encrypted beg end)
2300   )
2301
2302 (defun mime-edit-insert-key (&optional arg)
2303   "Insert a pgp public key."
2304   (interactive "P")
2305   (mime-edit-insert-tag "application" "pgp-keys")
2306   (mime-edit-define-encoding "7bit")
2307   (funcall (pgp-function 'insert-key))
2308   )
2309
2310
2311 ;;; @ flag setting
2312 ;;;
2313
2314 (defun mime-edit-set-split (arg)
2315   (interactive
2316    (list
2317     (y-or-n-p "Do you want to enable split? ")
2318     ))
2319   (setq mime-edit-split-message arg)
2320   (if arg
2321       (message "This message is enabled to split.")
2322     (message "This message is not enabled to split.")
2323     ))
2324
2325 (defun mime-edit-toggle-transfer-level (&optional transfer-level)
2326   "Toggle transfer-level is 7bit or 8bit through.
2327
2328 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2329   (interactive)
2330   (if (numberp transfer-level)
2331       (setq mime-transfer-level transfer-level)
2332     (if (< mime-transfer-level 8)
2333         (setq mime-transfer-level 8)
2334       (setq mime-transfer-level 7)
2335       ))
2336   (message (format "Current transfer-level is %d bit"
2337                    mime-transfer-level))
2338   (setq mime-transfer-level-string
2339         (mime-encoding-name mime-transfer-level 'not-omit))
2340   (force-mode-line-update)
2341   )
2342
2343 (defun mime-edit-set-transfer-level-7bit ()
2344   (interactive)
2345   (mime-edit-toggle-transfer-level 7)
2346   )
2347
2348 (defun mime-edit-set-transfer-level-8bit ()
2349   (interactive)
2350   (mime-edit-toggle-transfer-level 8)
2351   )
2352
2353
2354 ;;; @ pgp
2355 ;;;
2356
2357 (defvar mime-edit-pgp-processing nil)
2358 (make-variable-buffer-local 'mime-edit-pgp-processing)
2359
2360 (defun mime-edit-set-sign (arg)
2361   (interactive
2362    (list
2363     (y-or-n-p "Do you want to sign? ")
2364     ))
2365   (if arg
2366       (progn
2367         (setq mime-edit-pgp-processing 'sign)
2368         (message "This message will be signed.")
2369         )
2370     (if (eq mime-edit-pgp-processing 'sign)
2371         (setq mime-edit-pgp-processing nil)
2372       )
2373     (message "This message will not be signed.")
2374     ))
2375
2376 (defun mime-edit-set-encrypt (arg)
2377   (interactive
2378    (list
2379     (y-or-n-p "Do you want to encrypt? ")
2380     ))
2381   (if arg
2382       (progn
2383         (setq mime-edit-pgp-processing 'encrypt)
2384         (message "This message will be encrypt.")
2385         )
2386     (if (eq mime-edit-pgp-processing 'encrypt)
2387         (setq mime-edit-pgp-processing nil)
2388       )
2389     (message "This message will not be encrypt.")
2390     ))
2391
2392 (defun mime-edit-pgp-enclose-buffer ()
2393   (let ((beg (save-excursion
2394                (goto-char (point-min))
2395                (if (search-forward (concat "\n" mail-header-separator "\n"))
2396                    (match-end 0)
2397                  )))
2398         (end (point-max))
2399         )
2400     (if beg
2401         (cond ((eq mime-edit-pgp-processing 'sign)
2402                (mime-edit-enclose-pgp-signed-region beg end)
2403                )
2404               ((eq mime-edit-pgp-processing 'encrypt)
2405                (mime-edit-enclose-pgp-encrypted-region beg end)
2406                ))
2407       )))
2408
2409
2410 ;;; @ split
2411 ;;;
2412
2413 (defun mime-edit-insert-partial-header (fields subject
2414                                                id number total separator)
2415   (insert fields)
2416   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2417   (insert mime-edit-mime-version-field-for-message/partial)
2418   (insert (format "\
2419 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2420                   id number total separator))
2421   )
2422
2423 (defun mime-edit-split-and-send
2424   (&optional cmd lines mime-edit-message-max-length)
2425   (interactive)
2426   (or lines
2427       (setq lines
2428             (count-lines (point-min) (point-max)))
2429       )
2430   (or mime-edit-message-max-length
2431       (setq mime-edit-message-max-length
2432             (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2433                 mime-edit-message-default-max-lines))
2434       )
2435   (let* ((mime-edit-draft-file-name
2436           (or (buffer-file-name)
2437               (make-temp-name
2438                (expand-file-name "mime-draft" temporary-file-directory))))
2439          (separator mail-header-separator)
2440          (id (concat "\""
2441                      (replace-space-with-underline (current-time-string))
2442                      "@" (system-name) "\"")))
2443     (run-hooks 'mime-edit-before-split-hook)
2444     (let ((the-buf (current-buffer))
2445           (copy-buf (get-buffer-create " *Original Message*"))
2446           (header (std11-header-string-except
2447                    mime-edit-split-ignored-field-regexp separator))
2448           (subject (mail-fetch-field "subject"))
2449           (total (+ (/ lines mime-edit-message-max-length)
2450                     (if (> (mod lines mime-edit-message-max-length) 0)
2451                         1)))
2452           (command
2453            (or cmd
2454                (cdr
2455                 (assq major-mode
2456                       mime-edit-split-message-sender-alist))
2457                (function
2458                 (lambda ()
2459                   (interactive)
2460                   (error "Split sender is not specified for `%s'." major-mode)
2461                   ))
2462                ))
2463           (mime-edit-partial-number 1)
2464           data)
2465       (save-excursion
2466         (set-buffer copy-buf)
2467         (erase-buffer)
2468         (insert-buffer the-buf)
2469         (save-restriction
2470           (if (re-search-forward
2471                (concat "^" (regexp-quote separator) "$") nil t)
2472               (let ((he (match-beginning 0)))
2473                 (replace-match "")
2474                 (narrow-to-region (point-min) he)
2475                 ))
2476           (goto-char (point-min))
2477           (while (re-search-forward mime-edit-split-blind-field-regexp nil t)
2478             (delete-region (match-beginning 0)
2479                            (1+ (std11-field-end)))
2480             )))
2481       (while (< mime-edit-partial-number total)
2482         (erase-buffer)
2483         (save-excursion
2484           (set-buffer copy-buf)
2485           (setq data (buffer-substring
2486                       (point-min)
2487                       (progn
2488                         (goto-line mime-edit-message-max-length)
2489                         (point))
2490                       ))
2491           (delete-region (point-min)(point))
2492           )
2493         (mime-edit-insert-partial-header
2494          header subject id mime-edit-partial-number total separator)
2495         (insert data)
2496         (save-excursion
2497           (message (format "Sending %d/%d..."
2498                            mime-edit-partial-number total))
2499           (call-interactively command)
2500           (message (format "Sending %d/%d... done"
2501                            mime-edit-partial-number total))
2502           )
2503         (setq mime-edit-partial-number
2504               (1+ mime-edit-partial-number))
2505         )
2506       (erase-buffer)
2507       (save-excursion
2508         (set-buffer copy-buf)
2509         (setq data (buffer-string))
2510         (erase-buffer)
2511         )
2512       (mime-edit-insert-partial-header
2513        header subject id mime-edit-partial-number total separator)
2514       (insert data)
2515       (save-excursion
2516         (message (format "Sending %d/%d..."
2517                          mime-edit-partial-number total))
2518         (message (format "Sending %d/%d... done"
2519                          mime-edit-partial-number total))
2520         )
2521       )))
2522
2523 (defun mime-edit-maybe-split-and-send (&optional cmd)
2524   (interactive)
2525   (run-hooks 'mime-edit-before-send-hook)
2526   (let ((mime-edit-message-max-length
2527          (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2528              mime-edit-message-default-max-lines))
2529         (lines (count-lines (point-min) (point-max)))
2530         )
2531     (if (and (> lines mime-edit-message-max-length)
2532              mime-edit-split-message)
2533         (mime-edit-split-and-send cmd lines mime-edit-message-max-length)
2534       )))
2535
2536
2537 ;;; @ preview message
2538 ;;;
2539
2540 (defvar mime-edit-buffer nil) ; buffer local variable
2541
2542 (defun mime-edit-preview-message ()
2543   "preview editing MIME message."
2544   (interactive)
2545   (let* ((str (buffer-string))
2546          (separator mail-header-separator)
2547          (the-buf (current-buffer))
2548          (buf-name (buffer-name))
2549          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2550          (buf (get-buffer temp-buf-name))
2551          )
2552     (if buf
2553         (progn
2554           (switch-to-buffer buf)
2555           (erase-buffer)
2556           )
2557       (setq buf (get-buffer-create temp-buf-name))
2558       (switch-to-buffer buf)
2559       )
2560     (insert str)
2561     (setq major-mode 'mime-temp-message-mode)
2562     (make-local-variable 'mail-header-separator)
2563     (setq mail-header-separator separator)
2564     (make-local-variable 'mime-edit-buffer)
2565     (setq mime-edit-buffer the-buf)
2566
2567     (run-hooks 'mime-edit-translate-hook)
2568     (mime-edit-translate-buffer)
2569     (goto-char (point-min))
2570     (if (re-search-forward
2571          (concat "^" (regexp-quote separator) "$"))
2572         (replace-match "")
2573       )
2574     (mime-view-buffer)
2575     ))
2576
2577 (defun mime-edit-quitting-method ()
2578   "Quitting method for mime-view."
2579   (let ((temp mime-raw-buffer)
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         (decode-mime-charset-region (point-min)(point-max)
2707                                     (or charset default-mime-charset))
2708       )
2709     (let ((he (if (re-search-forward "^$" nil t)
2710                   (match-end 0)
2711                 (point-min)
2712                 )))
2713       (if (and (eq type 'text)
2714                (eq subtype 'x-rot13-47-48))
2715           (mule-caesar-region he (point-max))
2716         )
2717       (if (= (point-min) 1)
2718           (progn
2719             (goto-char he)
2720             (insert
2721              (concat "\n"
2722                      (mime-create-tag
2723                       (format "%s/%s%s" type subtype pstr)
2724                       encoding)))
2725             )
2726         (delete-region (point-min) he)
2727         (insert
2728          (mime-create-tag (format "%s/%s%s" type subtype pstr)
2729                           encoding))
2730         ))
2731     ))
2732
2733 ;;;###autoload
2734 (defun mime-edit-decode-message-in-buffer (&optional default-content-type
2735                                                      not-decode-text)
2736   (save-excursion
2737     (goto-char (point-min))
2738     (let ((ctl (or (mime-read-Content-Type)
2739                    default-content-type)))
2740       (if ctl
2741           (let ((type (mime-content-type-primary-type ctl)))
2742             (cond
2743              ((and (eq type 'application)
2744                    (eq (mime-content-type-subtype ctl) 'pgp-signature))
2745               (delete-region (point-min)(point-max))
2746               )
2747              ((eq type 'multipart)
2748               (mime-edit-decode-multipart-in-buffer ctl not-decode-text)
2749               )
2750              (t
2751               (mime-edit-decode-single-part-in-buffer ctl not-decode-text)
2752               )))
2753         (or not-decode-text
2754             (decode-mime-charset-region (point-min) (point-max)
2755                                         default-mime-charset))
2756         )
2757       (save-restriction
2758         (std11-narrow-to-header)
2759         (goto-char (point-min))
2760         (while (re-search-forward mime-edit-again-ignored-field-regexp nil t)
2761           (delete-region (match-beginning 0) (1+ (std11-field-end)))
2762           ))
2763       (mime-decode-header-in-buffer (not not-decode-text))
2764       )))
2765
2766 ;;;###autoload
2767 (defun mime-edit-again (&optional not-decode-text no-separator not-turn-on)
2768   "Convert current buffer to MIME-Edit buffer and turn on MIME-Edit mode.
2769 Content-Type and Content-Transfer-Encoding header fields will be
2770 converted to MIME-Edit tags."
2771   (interactive)
2772   (goto-char (point-min))
2773   (if (search-forward
2774        (concat "\n" (regexp-quote mail-header-separator) "\n")
2775        nil t)
2776       (replace-match "\n\n")
2777     )
2778   (mime-edit-decode-message-in-buffer nil not-decode-text)
2779   (goto-char (point-min))
2780   (or no-separator
2781       (and (re-search-forward "^$")
2782            (replace-match mail-header-separator)
2783            ))
2784   (or not-turn-on
2785       (turn-on-mime-edit)
2786       ))
2787
2788
2789 ;;; @ end
2790 ;;;
2791
2792 (provide 'mime-edit)
2793
2794 (run-hooks 'mime-edit-load-hook)
2795
2796 ;;; mime-edit.el ends here