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