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