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