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