(mime-edit-find-inmost): Abolish unused local variables.
[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)
1578         (setq end-exp (format "--}-<<%s>>\n" type))
1579         (widen)
1580         (if (re-search-forward end-exp nil t)
1581             (setq eb (match-beginning 0))
1582           (setq eb (point-max))
1583           )
1584         (narrow-to-region be eb)
1585         (goto-char be)
1586         (if (re-search-forward mime-edit-multipart-beginning-regexp nil t)
1587             (progn
1588               (narrow-to-region (match-beginning 0)(point-max))
1589               (mime-edit-find-inmost)
1590               )
1591           (widen)
1592           (list type bb be eb)
1593           ))))
1594
1595 (defun mime-edit-process-multipart-1 (boundary)
1596   (let ((ret (mime-edit-find-inmost)))
1597     (if ret
1598         (let ((type (car ret))
1599               (bb (nth 1 ret))(be (nth 2 ret))
1600               (eb (nth 3 ret))
1601               )
1602           (narrow-to-region bb eb)
1603           (delete-region bb be)
1604           (setq bb (point-min))
1605           (setq eb (point-max))
1606           (widen)
1607           (goto-char eb)
1608           (if (looking-at mime-edit-multipart-end-regexp)
1609               (let ((beg (match-beginning 0))
1610                     (end (match-end 0))
1611                     )
1612                 (delete-region beg end)
1613                 (or (looking-at mime-edit-beginning-tag-regexp)
1614                     (eobp)
1615                     (insert (concat (mime-make-text-tag) "\n"))
1616                     )))
1617           (cond ((string-equal type "quote")
1618                  (mime-edit-enquote-region bb eb)
1619                  )
1620                 ((string-equal type "signed")
1621                  (cond ((eq mime-edit-signing-type 'pgp-elkins)
1622                         (mime-edit-sign-pgp-elkins bb eb boundary)
1623                         )
1624                        ((eq mime-edit-signing-type 'pgp-kazu)
1625                         (mime-edit-sign-pgp-kazu bb eb boundary)
1626                         ))
1627                  )
1628                 ((string-equal type "encrypted")
1629                  (cond ((eq mime-edit-encrypting-type 'pgp-elkins)
1630                         (mime-edit-encrypt-pgp-elkins bb eb boundary)
1631                         )
1632                        ((eq mime-edit-encrypting-type 'pgp-kazu)
1633                         (mime-edit-encrypt-pgp-kazu bb eb boundary)
1634                         )))
1635                 (t
1636                  (setq boundary
1637                        (nth 2 (mime-edit-translate-region bb eb
1638                                                             boundary t)))
1639                  (goto-char bb)
1640                  (insert
1641                   (format "--[[multipart/%s;
1642  boundary=\"%s\"][7bit]]\n"
1643                           type boundary))
1644                  ))
1645           boundary))))
1646
1647 (defun mime-edit-enquote-region (beg end)
1648   (save-excursion
1649     (save-restriction
1650       (narrow-to-region beg end)
1651       (goto-char beg)
1652       (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
1653         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1654           (replace-match (concat "- " (substring tag 1)))
1655           )))))
1656
1657 (defun mime-edit-dequote-region (beg end)
1658   (save-excursion
1659     (save-restriction
1660       (narrow-to-region beg end)
1661       (goto-char beg)
1662       (while (re-search-forward
1663               mime-edit-quoted-single-part-tag-regexp nil t)
1664         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1665           (replace-match (concat "-" (substring tag 2)))
1666           )))))
1667
1668 (defun mime-edit-sign-pgp-elkins (beg end boundary)
1669   (save-excursion
1670     (save-restriction
1671       (narrow-to-region beg end)
1672       (let* ((ret
1673               (mime-edit-translate-region beg end boundary))
1674              (ctype    (car ret))
1675              (encoding (nth 1 ret))
1676              (parts    (nth 3 ret))
1677              (pgp-boundary (concat "pgp-sign-" boundary))
1678              )
1679         (goto-char beg)
1680         (insert (format "Content-Type: %s\n" ctype))
1681         (if encoding
1682             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1683           )
1684         (insert "\n")
1685         (or (as-binary-process
1686              (funcall (pgp-function 'mime-sign)
1687                       (point-min)(point-max) nil nil pgp-boundary))
1688             (throw 'mime-edit-error 'pgp-error)
1689             )
1690         ))))
1691
1692 (defvar mime-edit-encrypt-recipient-fields-list '("To" "cc"))
1693
1694 (defun mime-edit-make-encrypt-recipient-header ()
1695   (let* ((names mime-edit-encrypt-recipient-fields-list)
1696          (values
1697           (std11-field-bodies (cons "From" names)
1698                               nil mail-header-separator))
1699          (from (prog1
1700                    (car values)
1701                  (setq values (cdr values))))
1702          (header (and (stringp from)
1703                       (if (string-equal from "")
1704                           ""
1705                         (format "From: %s\n" from)
1706                         )))
1707          recipients)
1708     (while (and names values)
1709       (let ((name (car names))
1710             (value (car values))
1711             )
1712         (and (stringp value)
1713              (or (string-equal value "")
1714                  (progn
1715                    (setq header (concat header name ": " value "\n")
1716                          recipients (if recipients
1717                                         (concat recipients " ," value)
1718                                       value))
1719                    ))))
1720       (setq names (cdr names)
1721             values (cdr values))
1722       )
1723     (vector from recipients header)
1724     ))
1725
1726 (defun mime-edit-encrypt-pgp-elkins (beg end boundary)
1727   (save-excursion
1728     (save-restriction
1729       (let (from recipients header)
1730         (let ((ret (mime-edit-make-encrypt-recipient-header)))
1731           (setq from (aref ret 0)
1732                 recipients (aref ret 1)
1733                 header (aref ret 2))
1734           )
1735         (narrow-to-region beg end)
1736         (let* ((ret
1737                 (mime-edit-translate-region beg end boundary))
1738                (ctype    (car ret))
1739                (encoding (nth 1 ret))
1740                (parts    (nth 3 ret))
1741                (pgp-boundary (concat "pgp-" boundary))
1742                )
1743           (goto-char beg)
1744           (insert header)
1745           (insert (format "Content-Type: %s\n" ctype))
1746           (if encoding
1747               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1748             )
1749           (insert "\n")
1750           (or (funcall (pgp-function 'encrypt)
1751                        recipients (point-min) (point-max) from)
1752               (throw 'mime-edit-error 'pgp-error)
1753               )
1754           (goto-char beg)
1755           (insert (format "--[[multipart/encrypted;
1756  boundary=\"%s\";
1757  protocol=\"application/pgp-encrypted\"][7bit]]
1758 --%s
1759 Content-Type: application/pgp-encrypted
1760
1761 --%s
1762 Content-Type: application/octet-stream
1763 Content-Transfer-Encoding: 7bit
1764
1765 " pgp-boundary pgp-boundary pgp-boundary))
1766           (goto-char (point-max))
1767           (insert (format "\n--%s--\n" pgp-boundary))
1768           )))))
1769
1770 (defun mime-edit-sign-pgp-kazu (beg end boundary)
1771   (save-excursion
1772     (save-restriction
1773       (narrow-to-region beg end)
1774       (let* ((ret
1775               (mime-edit-translate-region beg end boundary))
1776              (ctype    (car ret))
1777              (encoding (nth 1 ret))
1778              (parts    (nth 3 ret))
1779              )
1780         (goto-char beg)
1781         (insert (format "Content-Type: %s\n" ctype))
1782         (if encoding
1783             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1784           )
1785         (insert "\n")
1786         (or (as-binary-process
1787              (funcall (pgp-function 'traditional-sign)
1788                       beg (point-max)))
1789             (throw 'mime-edit-error 'pgp-error)
1790             )
1791         (goto-char beg)
1792         (insert
1793          "--[[application/pgp; format=mime][7bit]]\n")
1794         ))
1795     ))
1796
1797 (defun mime-edit-encrypt-pgp-kazu (beg end boundary)
1798   (save-excursion
1799     (let (from recipients header)
1800       (let ((ret (mime-edit-make-encrypt-recipient-header)))
1801         (setq from (aref ret 0)
1802               recipients (aref ret 1)
1803               header (aref ret 2))
1804         )
1805       (save-restriction
1806         (narrow-to-region beg end)
1807         (let* ((ret
1808                 (mime-edit-translate-region beg end boundary))
1809                (ctype    (car ret))
1810                (encoding (nth 1 ret))
1811                (parts    (nth 3 ret))
1812                )
1813           (goto-char beg)
1814           (insert header)
1815           (insert (format "Content-Type: %s\n" ctype))
1816           (if encoding
1817               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1818             )
1819           (insert "\n")
1820           (or (as-binary-process
1821                (funcall (pgp-function 'encrypt)
1822                         recipients beg (point-max) nil 'maybe)
1823                )
1824               (throw 'mime-edit-error 'pgp-error)
1825               )
1826           (goto-char beg)
1827           (insert
1828            "--[[application/pgp; format=mime][7bit]]\n")
1829           ))
1830       )))
1831
1832 (defsubst replace-space-with-underline (str)
1833   (mapconcat (function
1834               (lambda (arg)
1835                 (char-to-string
1836                  (if (eq arg ?\ )
1837                      ?_
1838                    arg)))) str "")
1839   )
1840
1841 (defun mime-edit-make-boundary ()
1842   (concat mime-multipart-boundary "_"
1843           (replace-space-with-underline (current-time-string))
1844           ))
1845
1846 (defun mime-edit-translate-body ()
1847   "Encode the tagged MIME body in current buffer in MIME compliant message."
1848   (interactive)
1849   (save-excursion
1850     (let ((boundary (mime-edit-make-boundary))
1851           (i 1)
1852           ret)
1853       (while (mime-edit-process-multipart-1
1854               (format "%s-%d" boundary i))
1855         (setq i (1+ i))
1856         )
1857       (save-restriction
1858         ;; We are interested in message body.
1859         (let* ((beg
1860                 (progn
1861                   (goto-char (point-min))
1862                   (re-search-forward
1863                    (concat "\n" (regexp-quote mail-header-separator)
1864                            (if mime-ignore-preceding-spaces
1865                                "[ \t\n]*\n" "\n")) nil 'move)
1866                   (point)))
1867                (end
1868                 (progn
1869                   (goto-char (point-max))
1870                   (and mime-ignore-trailing-spaces
1871                        (re-search-backward "[^ \t\n]\n" beg t)
1872                        (forward-char 1))
1873                   (point))))
1874           (setq ret (mime-edit-translate-region
1875                      beg end
1876                      (format "%s-%d" boundary i)))
1877           ))
1878       (mime-edit-dequote-region (point-min)(point-max))
1879       (let ((contype (car ret))         ;Content-Type
1880             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1881             )
1882         ;; Insert X-Emacs field
1883         (and mime-edit-insert-x-emacs-field
1884              (or (mail-position-on-field "X-Emacs")
1885                  (insert mime-edit-x-emacs-value)
1886                  ))
1887         ;; Make primary MIME headers.
1888         (or (mail-position-on-field "MIME-Version")
1889             (insert mime-edit-mime-version-value))
1890         ;; Remove old Content-Type and other fields.
1891         (save-restriction
1892           (goto-char (point-min))
1893           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1894           (narrow-to-region (point-min) (point))
1895           (goto-char (point-min))
1896           (mime-delete-field "Content-Type")
1897           (mime-delete-field "Content-Transfer-Encoding"))
1898         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1899         (mail-position-on-field "Content-Type")
1900         (insert contype)
1901         (if encoding
1902             (progn
1903               (mail-position-on-field "Content-Transfer-Encoding")
1904               (insert encoding)))
1905         ))))
1906
1907 (defun mime-edit-translate-single-part-tag (&optional prefix)
1908   "Translate single-part-tag to MIME header."
1909   (if (re-search-forward mime-edit-single-part-tag-regexp nil t)
1910       (let* ((beg (match-beginning 0))
1911              (end (match-end 0))
1912              (tag (buffer-substring beg end))
1913              )
1914         (delete-region beg end)
1915         (let ((contype (mime-edit-get-contype tag))
1916               (encoding (mime-edit-get-encoding tag))
1917               )
1918           (insert (concat prefix "--" boundary "\n"))
1919           (save-restriction
1920             (narrow-to-region (point)(point))
1921             (insert "Content-Type: " contype "\n")
1922             (if encoding
1923                 (insert "Content-Transfer-Encoding: " encoding "\n"))
1924             (eword-encode-header)
1925             ))
1926         t)))
1927
1928 (defun mime-edit-translate-region (beg end &optional boundary multipart)
1929   (or boundary
1930       (setq boundary (mime-edit-make-boundary))
1931       )
1932   (save-excursion
1933     (save-restriction
1934       (narrow-to-region beg end)
1935       (let ((tag nil)                   ;MIME tag
1936             (contype nil)               ;Content-Type
1937             (encoding nil)              ;Content-Transfer-Encoding
1938             (nparts 0))                 ;Number of body parts
1939         ;; Normalize the body part by inserting appropriate message
1940         ;; tags for every message contents.
1941         (mime-edit-normalize-body)
1942         ;; Counting the number of Content-Type.
1943         (goto-char (point-min))
1944         (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
1945           (setq nparts (1+ nparts)))
1946         ;; Begin translation.
1947         (cond
1948          ((and (<= nparts 1)(not multipart))
1949           ;; It's a singular message.
1950           (goto-char (point-min))
1951           (while (re-search-forward
1952                   mime-edit-single-part-tag-regexp nil t)
1953             (setq tag
1954                   (buffer-substring (match-beginning 0) (match-end 0)))
1955             (delete-region (match-beginning 0) (1+ (match-end 0)))
1956             (setq contype (mime-edit-get-contype tag))
1957             (setq encoding (mime-edit-get-encoding tag))
1958             ))
1959          (t
1960           ;; It's a multipart message.
1961           (goto-char (point-min))
1962           (and (mime-edit-translate-single-part-tag)
1963                (while (mime-edit-translate-single-part-tag "\n"))
1964                )
1965           ;; Define Content-Type as "multipart/mixed".
1966           (setq contype
1967                 (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1968           ;; Content-Transfer-Encoding must be "7bit".
1969           ;; The following encoding can be `nil', but is
1970           ;; specified as is since there is no way that a user
1971           ;; specifies it.
1972           (setq encoding "7bit")
1973           ;; Insert the trailer.
1974           (goto-char (point-max))
1975           (insert "\n--" boundary "--\n")
1976           ))
1977         (list contype encoding boundary nparts)
1978         ))))
1979
1980 (defun mime-edit-normalize-body ()
1981   "Normalize the body part by inserting appropriate message tags."
1982   ;; Insert the first MIME tags if necessary.
1983   (goto-char (point-min))
1984   (if (not (looking-at mime-edit-single-part-tag-regexp))
1985       (insert (mime-make-text-tag) "\n"))
1986   ;; Check each tag, and add new tag or correct it if necessary.
1987   (goto-char (point-min))
1988   (while (re-search-forward mime-edit-single-part-tag-regexp nil t)
1989     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1990            (contype (mime-edit-get-contype tag))
1991            (charset (mime-get-parameter contype "charset"))
1992            (encoding (mime-edit-get-encoding tag)))
1993       ;; Remove extra whitespaces after the tag.
1994       (if (looking-at "[ \t]+$")
1995           (delete-region (match-beginning 0) (match-end 0)))
1996       (let ((beg (point))
1997             (end (mime-edit-content-end))
1998             )
1999         (if (= end (point-max))
2000             nil
2001           (goto-char end)
2002           (or (looking-at mime-edit-beginning-tag-regexp)
2003               (eobp)
2004               (insert (mime-make-text-tag) "\n")
2005               ))
2006         (visible-region beg end)
2007         (goto-char beg)
2008         )
2009       (cond
2010        ((mime-test-content-type contype "message")
2011         ;; Content-type "message" should be sent as is.
2012         (forward-line 1)
2013         )
2014        ((mime-test-content-type contype "text")
2015         ;; Define charset for text if necessary.
2016         (setq charset (if charset
2017                           (intern (downcase charset))
2018                         (mime-edit-choose-charset)))
2019         (mime-edit-define-charset charset)
2020         (cond ((string-equal contype "text/x-rot13-47-48")
2021                (save-excursion
2022                  (forward-line)
2023                  (mule-caesar-region (point) (mime-edit-content-end))
2024                  ))
2025               ((string-equal contype "text/enriched")
2026                (save-excursion
2027                  (let ((beg (progn
2028                               (forward-line)
2029                               (point)))
2030                        (end (mime-edit-content-end))
2031                        )
2032                    ;; Patch for hard newlines
2033                    ;; (save-excursion
2034                    ;;   (goto-char beg)
2035                    ;;   (while (search-forward "\n" end t)
2036                    ;;     (put-text-property (match-beginning 0)
2037                    ;;                        (point)
2038                    ;;                        'hard t)))
2039                    ;; End patch for hard newlines
2040                    (enriched-encode beg end)
2041                    (goto-char beg)
2042                    (if (search-forward "\n\n")
2043                        (delete-region beg (match-end 0))
2044                      )
2045                    ))))
2046         ;; Point is now on current tag.
2047         ;; Define encoding and encode text if necessary.
2048         (or encoding    ;Encoding is not specified.
2049             (let* ((encoding
2050                     (cdr
2051                      (assq charset
2052                            mime-edit-charset-default-encoding-alist)
2053                      ))
2054                    (beg (mime-edit-content-beginning))
2055                    )
2056               (encode-mime-charset-region beg (mime-edit-content-end)
2057                                           charset)
2058               ;; Protect "From " in beginning of line
2059               (save-restriction
2060                 (narrow-to-region beg (mime-edit-content-end))
2061                 (goto-char beg)
2062                 (let (case-fold-search)
2063                   (if (re-search-forward "^From " nil t)
2064                       (unless encoding
2065                         (if (memq charset '(iso-2022-jp
2066                                             iso-2022-jp-2
2067                                             iso-2022-int-1
2068                                             x-ctext))
2069                             (while (progn
2070                                      (replace-match "\e(BFrom ")
2071                                      (re-search-forward "^From " nil t)
2072                                      ))
2073                           (setq encoding "quoted-printable")
2074                           )))))
2075               ;; canonicalize line break code
2076               (or (member encoding '(nil "7bit" "8bit" "quoted-printable"))
2077                   (save-restriction
2078                     (narrow-to-region beg (mime-edit-content-end))
2079                     (goto-char beg)
2080                     (while (re-search-forward "\\([^\r]\\)\n" nil t)
2081                       (replace-match
2082                        (concat (buffer-substring (match-beginning 0)
2083                                                  (match-end 1)) "\r\n"))
2084                       )))
2085               (goto-char beg)
2086               (mime-encode-region beg (mime-edit-content-end) encoding)
2087               (mime-edit-define-encoding encoding)
2088               ))
2089         (goto-char (mime-edit-content-end))
2090         )
2091        ((null encoding)         ;Encoding is not specified.
2092         ;; Application, image, audio, video, and any other
2093         ;; unknown content-type without encoding should be
2094         ;; encoded.
2095         (let* ((encoding "base64")      ;Encode in BASE64 by default.
2096                (beg (mime-edit-content-beginning))
2097                (end (mime-edit-content-end))
2098                (body (buffer-substring beg end))
2099                )
2100           (mime-encode-region beg end encoding)
2101           (mime-edit-define-encoding encoding))
2102         (forward-line 1)
2103         ))
2104       )))
2105
2106 (defun mime-delete-field (field)
2107   "Delete header FIELD."
2108   (let ((regexp (format "^%s:[ \t]*" field)))
2109     (goto-char (point-min))
2110     (while (re-search-forward regexp nil t)
2111       (delete-region (match-beginning 0)
2112                      (progn (forward-line 1) (point)))
2113       )))
2114
2115 \f
2116 ;;;
2117 ;;; Platform dependent functions
2118 ;;;
2119
2120 ;; Sun implementations
2121
2122 (defun mime-edit-voice-recorder-for-sun (encoding)
2123   "Record voice in a buffer using Sun audio device,
2124 and insert data encoded as ENCODING."
2125   (message "Start the recording on %s.  Type C-g to finish the recording..."
2126            (system-name))
2127   (mime-insert-encoded-file "/dev/audio" encoding)
2128   )
2129
2130 \f
2131 ;;; @ Other useful commands.
2132 ;;;
2133
2134 ;; Message forwarding commands as content-type "message/rfc822".
2135
2136 (defun mime-edit-insert-message (&optional message)
2137   (interactive)
2138   (let ((inserter (cdr (assq major-mode mime-edit-message-inserter-alist))))
2139     (if (and inserter (fboundp inserter))
2140         (progn
2141           (mime-edit-insert-tag "message" "rfc822")
2142           (funcall inserter message)
2143           )
2144       (message "Sorry, I don't have message inserter for your MUA.")
2145       )))
2146
2147 (defun mime-edit-insert-mail (&optional message)
2148   (interactive)
2149   (let ((inserter (cdr (assq major-mode mime-edit-mail-inserter-alist))))
2150     (if (and inserter (fboundp inserter))
2151         (progn
2152           (mime-edit-insert-tag "message" "rfc822")
2153           (funcall inserter message)
2154           )
2155       (message "Sorry, I don't have mail inserter for your MUA.")
2156       )))
2157
2158 (defun mime-edit-inserted-message-filter ()
2159   (save-excursion
2160     (save-restriction
2161       (let ((header-start (point))
2162             (case-fold-search t)
2163             beg end)
2164         ;; for Emacs 18
2165         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2166         (if (re-search-forward "^$" (mark t))
2167             (narrow-to-region header-start (match-beginning 0))
2168           )
2169         (goto-char header-start)
2170         (while (and (re-search-forward
2171                      mime-edit-yank-ignored-field-regexp nil t)
2172                     (setq beg (match-beginning 0))
2173                     (setq end (1+ (std11-field-end)))
2174                     )
2175           (delete-region beg end)
2176           )
2177         ))))
2178
2179
2180 ;;; @ multipart enclosure
2181 ;;;
2182
2183 (defun mime-edit-enclose-region-internal (type beg end)
2184   (save-excursion
2185     (goto-char beg)
2186     (let ((current (point)))
2187       (save-restriction
2188         (narrow-to-region beg end)
2189         (insert (format "--<<%s>>-{\n" type))
2190         (goto-char (point-max))
2191         (insert (format "--}-<<%s>>\n" type))
2192         (goto-char (point-max))
2193         )
2194       (or (looking-at mime-edit-beginning-tag-regexp)
2195           (eobp)
2196           (insert (mime-make-text-tag) "\n")
2197           )
2198       )))
2199
2200 (defun mime-edit-enclose-quote-region (beg end)
2201   (interactive "*r")
2202   (mime-edit-enclose-region-internal 'quote beg end)
2203   )
2204
2205 (defun mime-edit-enclose-mixed-region (beg end)
2206   (interactive "*r")
2207   (mime-edit-enclose-region-internal 'mixed beg end)
2208   )
2209
2210 (defun mime-edit-enclose-parallel-region (beg end)
2211   (interactive "*r")
2212   (mime-edit-enclose-region-internal 'parallel beg end)
2213   )
2214
2215 (defun mime-edit-enclose-digest-region (beg end)
2216   (interactive "*r")
2217   (mime-edit-enclose-region-internal 'digest beg end)
2218   )
2219
2220 (defun mime-edit-enclose-alternative-region (beg end)
2221   (interactive "*r")
2222   (mime-edit-enclose-region-internal 'alternative beg end)
2223   )
2224
2225 (defun mime-edit-enclose-signed-region (beg end)
2226   (interactive "*r")
2227   (if mime-edit-signing-type
2228       (mime-edit-enclose-region-internal 'signed beg end)
2229     (message "Please specify signing type.")
2230     ))
2231
2232 (defun mime-edit-enclose-encrypted-region (beg end)
2233   (interactive "*r")
2234   (if mime-edit-signing-type
2235       (mime-edit-enclose-region-internal 'encrypted beg end)
2236     (message "Please specify encrypting type.")
2237     ))
2238
2239 (defun mime-edit-insert-key (&optional arg)
2240   "Insert a pgp public key."
2241   (interactive "P")
2242   (mime-edit-insert-tag "application" "pgp-keys")
2243   (mime-edit-define-encoding "7bit")
2244   (funcall (pgp-function 'insert-key))
2245   )
2246
2247
2248 ;;; @ flag setting
2249 ;;;
2250
2251 (defun mime-edit-set-split (arg)
2252   (interactive
2253    (list
2254     (y-or-n-p "Do you want to enable split? ")
2255     ))
2256   (setq mime-edit-split-message arg)
2257   (if arg
2258       (message "This message is enabled to split.")
2259     (message "This message is not enabled to split.")
2260     ))
2261
2262 (defun mime-edit-toggle-transfer-level (&optional transfer-level)
2263   "Toggle transfer-level is 7bit or 8bit through.
2264
2265 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2266   (interactive)
2267   (if (numberp transfer-level)
2268       (setq mime-transfer-level transfer-level)
2269     (if (< mime-transfer-level 8)
2270         (setq mime-transfer-level 8)
2271       (setq mime-transfer-level 7)
2272       ))
2273   (setq mime-edit-charset-default-encoding-alist
2274         (mime-make-charset-default-encoding-alist mime-transfer-level))
2275   (message (format "Current transfer-level is %d bit"
2276                    mime-transfer-level))
2277   (setq mime-transfer-level-string
2278         (mime-encoding-name mime-transfer-level 'not-omit))
2279   (force-mode-line-update)
2280   )
2281
2282 (defun mime-edit-set-transfer-level-7bit ()
2283   (interactive)
2284   (mime-edit-toggle-transfer-level 7)
2285   )
2286
2287 (defun mime-edit-set-transfer-level-8bit ()
2288   (interactive)
2289   (mime-edit-toggle-transfer-level 8)
2290   )
2291
2292
2293 ;;; @ pgp
2294 ;;;
2295
2296 (defun mime-edit-set-sign (arg)
2297   (interactive
2298    (list
2299     (y-or-n-p "Do you want to sign? ")
2300     ))
2301   (if arg
2302       (if mime-edit-signing-type
2303           (progn
2304             (setq mime-edit-pgp-processing 'sign)
2305             (message "This message will be signed.")
2306             )
2307         (message "Please specify signing type.")
2308         )
2309     (if (eq mime-edit-pgp-processing 'sign)
2310         (setq mime-edit-pgp-processing nil)
2311       )
2312     (message "This message will not be signed.")
2313     ))
2314
2315 (defun mime-edit-set-encrypt (arg)
2316   (interactive
2317    (list
2318     (y-or-n-p "Do you want to encrypt? ")
2319     ))
2320   (if arg
2321       (if mime-edit-encrypting-type
2322           (progn
2323             (setq mime-edit-pgp-processing 'encrypt)
2324             (message "This message will be encrypt.")
2325             )
2326         (message "Please specify encrypting type.")
2327         )
2328     (if (eq mime-edit-pgp-processing 'encrypt)
2329         (setq mime-edit-pgp-processing nil)
2330       )
2331     (message "This message will not be encrypt.")
2332     ))
2333
2334 (defvar mime-edit-pgp-processing nil)
2335 (make-variable-buffer-local 'mime-edit-pgp-processing)
2336
2337 (defun mime-edit-pgp-enclose-buffer ()
2338   (let ((beg (save-excursion
2339                (goto-char (point-min))
2340                (if (search-forward (concat "\n" mail-header-separator "\n"))
2341                    (match-end 0)
2342                  )))
2343         (end (point-max))
2344         )
2345     (if beg
2346         (cond ((eq mime-edit-pgp-processing 'sign)
2347                (mime-edit-enclose-signed-region beg end)
2348                )
2349               ((eq mime-edit-pgp-processing 'encrypt)
2350                (mime-edit-enclose-encrypted-region beg end)
2351                ))
2352       )))
2353
2354
2355 ;;; @ split
2356 ;;;
2357
2358 (defun mime-edit-insert-partial-header (fields subject
2359                                                id number total separator)
2360   (insert fields)
2361   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2362   (insert mime-edit-mime-version-field-for-message/partial)
2363   (insert (format "\
2364 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2365                   id number total separator))
2366   )
2367
2368 (defun mime-edit-split-and-send
2369   (&optional cmd lines mime-edit-message-max-length)
2370   (interactive)
2371   (or lines
2372       (setq lines
2373             (count-lines (point-min) (point-max)))
2374       )
2375   (or mime-edit-message-max-length
2376       (setq mime-edit-message-max-length
2377             (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2378                 mime-edit-message-default-max-lines))
2379       )
2380   (let* ((mime-edit-draft-file-name
2381           (or (buffer-file-name)
2382               (make-temp-name
2383                (expand-file-name "mime-draft" mime-temp-directory))))
2384          (separator mail-header-separator)
2385          (id (concat "\""
2386                      (replace-space-with-underline (current-time-string))
2387                      "@" (system-name) "\"")))
2388     (run-hooks 'mime-edit-before-split-hook)
2389     (let ((the-buf (current-buffer))
2390           (copy-buf (get-buffer-create " *Original Message*"))
2391           (header (std11-header-string-except
2392                    mime-edit-split-ignored-field-regexp separator))
2393           (subject (mail-fetch-field "subject"))
2394           (total (+ (/ lines mime-edit-message-max-length)
2395                     (if (> (mod lines mime-edit-message-max-length) 0)
2396                         1)))
2397           (command
2398            (or cmd
2399                (cdr
2400                 (assq major-mode
2401                       mime-edit-split-message-sender-alist))
2402                (function
2403                 (lambda ()
2404                   (interactive)
2405                   (error "Split sender is not specified for `%s'." major-mode)
2406                   ))
2407                ))
2408           (mime-edit-partial-number 1)
2409           data)
2410       (save-excursion
2411         (set-buffer copy-buf)
2412         (erase-buffer)
2413         (insert-buffer the-buf)
2414         (save-restriction
2415           (if (re-search-forward
2416                (concat "^" (regexp-quote separator) "$") nil t)
2417               (let ((he (match-beginning 0)))
2418                 (replace-match "")
2419                 (narrow-to-region (point-min) he)
2420                 ))
2421           (goto-char (point-min))
2422           (while (re-search-forward mime-edit-split-blind-field-regexp nil t)
2423             (delete-region (match-beginning 0)
2424                            (1+ (std11-field-end)))
2425             )))
2426       (while (< mime-edit-partial-number total)
2427         (erase-buffer)
2428         (save-excursion
2429           (set-buffer copy-buf)
2430           (setq data (buffer-substring
2431                       (point-min)
2432                       (progn
2433                         (goto-line mime-edit-message-max-length)
2434                         (point))
2435                       ))
2436           (delete-region (point-min)(point))
2437           )
2438         (mime-edit-insert-partial-header
2439          header subject id mime-edit-partial-number total separator)
2440         (insert data)
2441         (save-excursion
2442           (message (format "Sending %d/%d..."
2443                            mime-edit-partial-number total))
2444           (call-interactively command)
2445           (message (format "Sending %d/%d... done"
2446                            mime-edit-partial-number total))
2447           )
2448         (setq mime-edit-partial-number
2449               (1+ mime-edit-partial-number))
2450         )
2451       (erase-buffer)
2452       (save-excursion
2453         (set-buffer copy-buf)
2454         (setq data (buffer-string))
2455         (erase-buffer)
2456         )
2457       (mime-edit-insert-partial-header
2458        header subject id mime-edit-partial-number total separator)
2459       (insert data)
2460       (save-excursion
2461         (message (format "Sending %d/%d..."
2462                          mime-edit-partial-number total))
2463         (message (format "Sending %d/%d... done"
2464                          mime-edit-partial-number total))
2465         )
2466       )))
2467
2468 (defun mime-edit-maybe-split-and-send (&optional cmd)
2469   (interactive)
2470   (run-hooks 'mime-edit-before-send-hook)
2471   (let ((mime-edit-message-max-length
2472          (or (cdr (assq major-mode mime-edit-message-max-lines-alist))
2473              mime-edit-message-default-max-lines))
2474         (lines (count-lines (point-min) (point-max)))
2475         )
2476     (if (and (> lines mime-edit-message-max-length)
2477              mime-edit-split-message)
2478         (mime-edit-split-and-send cmd lines mime-edit-message-max-length)
2479       )))
2480
2481
2482 ;;; @ preview message
2483 ;;;
2484
2485 (defvar mime-edit-buffer nil) ; buffer local variable
2486
2487 (defun mime-edit-preview-message ()
2488   "preview editing MIME message."
2489   (interactive)
2490   (let* ((str (buffer-string))
2491          (separator mail-header-separator)
2492          (the-buf (current-buffer))
2493          (buf-name (buffer-name))
2494          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2495          (buf (get-buffer temp-buf-name))
2496          )
2497     (if buf
2498         (progn
2499           (switch-to-buffer buf)
2500           (erase-buffer)
2501           )
2502       (setq buf (get-buffer-create temp-buf-name))
2503       (switch-to-buffer buf)
2504       )
2505     (insert str)
2506     (setq major-mode 'mime-temp-message-mode)
2507     (make-local-variable 'mail-header-separator)
2508     (setq mail-header-separator separator)
2509     (make-local-variable 'mime-edit-buffer)
2510     (setq mime-edit-buffer the-buf)
2511
2512     (run-hooks 'mime-edit-translate-hook)
2513     (mime-edit-translate-buffer)
2514     (goto-char (point-min))
2515     (if (re-search-forward
2516          (concat "^" (regexp-quote separator) "$"))
2517         (replace-match "")
2518       )
2519     (mime-view-mode)
2520     ))
2521
2522 (defun mime-edit-quitting-method ()
2523   "Quitting method for mime-view."
2524   (let ((temp mime-raw-buffer)
2525         buf)
2526     (mime-preview-kill-buffer)
2527     (set-buffer temp)
2528     (setq buf mime-edit-buffer)
2529     (kill-buffer temp)
2530     (switch-to-buffer buf)
2531     ))
2532
2533 (set-alist 'mime-preview-quitting-method-alist
2534            'mime-temp-message-mode
2535            #'mime-edit-quitting-method)
2536
2537
2538 ;;; @ edit again
2539 ;;;
2540
2541 (defvar mime-edit-again-ignored-field-regexp
2542   (concat "^\\(" "Content-.*\\|Mime-Version"
2543           (if mime-edit-insert-x-emacs-field "\\|X-Emacs")
2544           "\\):")
2545   "Regexp for deleted header fields when `mime-edit-again' is called.")
2546
2547 (defun mime-edit-decode-buffer (not-decode-text)
2548   (save-excursion
2549     (goto-char (point-min))
2550     (let ((ctl (mime-read-Content-Type)))
2551       (if ctl
2552           (let ((type (mime-content-type-primary-type ctl))
2553                 (stype (mime-content-type-subtype ctl))
2554                 (params (mime-content-type-parameters ctl)))
2555             (cond
2556              ((and (eq type 'application)(eq stype 'pgp-signature))
2557               (delete-region (point-min)(point-max))
2558               )
2559              ((eq type 'multipart)
2560               (let* ((boundary (cdr (assoc "boundary" params)))
2561                      (boundary-pat
2562                       (concat "\n--" (regexp-quote boundary) "[ \t]*\n"))
2563                      )
2564                 (re-search-forward boundary-pat nil t)
2565                 (let ((bb (match-beginning 0)) eb tag)
2566                   (setq tag (format "\n--<<%s>>-{\n" stype))
2567                   (goto-char bb)
2568                   (insert tag)
2569                   (setq bb (+ bb (length tag)))
2570                   (re-search-forward
2571                    (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2572                    nil t)
2573                   (setq eb (match-beginning 0))
2574                   (replace-match (format "--}-<<%s>>\n" stype))
2575                   (save-restriction
2576                     (narrow-to-region bb eb)
2577                     (goto-char (point-min))
2578                     (while (re-search-forward boundary-pat nil t)
2579                       (let ((beg (match-beginning 0))
2580                             end)
2581                         (delete-region beg (match-end 0))
2582                         (save-excursion
2583                           (if (re-search-forward boundary-pat nil t)
2584                               (setq end (match-beginning 0))
2585                             (setq end (point-max))
2586                             )
2587                           (save-restriction
2588                             (narrow-to-region beg end)
2589                             (mime-edit-decode-buffer not-decode-text)
2590                             (goto-char (point-max))
2591                             ))))
2592                     ))
2593                 (goto-char (point-min))
2594                 (or (= (point-min) 1)
2595                     (delete-region (point-min)
2596                                    (if (search-forward "\n\n" nil t)
2597                                        (match-end 0)
2598                                      (point-min)
2599                                      )))
2600                 ))
2601              (t
2602               (let* ((ctype (format "%s/%s" type stype))
2603                      charset
2604                      (pstr
2605                       (let ((bytes (+ 14 (length ctype))))
2606                         (mapconcat (function
2607                                     (lambda (attr)
2608                                       (if (string= (car attr) "charset")
2609                                           (progn
2610                                             (setq charset (cdr attr))
2611                                             "")
2612                                         (let* ((str
2613                                                 (concat (car attr)
2614                                                         "=" (cdr attr))
2615                                                 )
2616                                                (bs (length str))
2617                                                )
2618                                           (setq bytes (+ bytes bs 2))
2619                                           (if (< bytes 76)
2620                                               (concat "; " str)
2621                                             (setq bytes (+ bs 1))
2622                                             (concat ";\n " str)
2623                                             )
2624                                           ))))
2625                                    params "")))
2626                      encoding
2627                      encoded)
2628                 (save-excursion
2629                   (if (re-search-forward
2630                        "Content-Transfer-Encoding:" nil t)
2631                       (let ((beg (match-beginning 0))
2632                             (hbeg (match-end 0))
2633                             (end (std11-field-end)))
2634                         (setq encoding
2635                               (eliminate-top-spaces
2636                                (std11-unfold-string
2637                                 (buffer-substring hbeg end))))
2638                         (if (or charset (eq type 'text))
2639                             (progn
2640                               (delete-region beg (1+ end))
2641                               (goto-char (point-min))
2642                               (if (search-forward "\n\n" nil t)
2643                                   (progn
2644                                     (mime-decode-region
2645                                      (match-end 0)(point-max) encoding)
2646                                     (setq encoded t
2647                                           encoding nil)
2648                                     )))))))
2649                 (if (or encoded (not not-decode-text))
2650                     (decode-mime-charset-region
2651                      (point-min)(point-max)
2652                      (or charset default-mime-charset))
2653                   )
2654                 (let ((he
2655                        (if (re-search-forward "^$" nil t)
2656                            (match-end 0)
2657                          (point-min)
2658                          )))
2659                   (if (= (point-min) 1)
2660                       (progn
2661                         (goto-char he)
2662                         (insert
2663                          (concat "\n"
2664                                  (mime-create-tag
2665                                   (format "%s/%s%s" type stype pstr)
2666                                   encoding)))
2667                         )
2668                     (delete-region (point-min) he)
2669                     (insert
2670                      (mime-create-tag
2671                       (format "%s/%s%s" type stype pstr)
2672                       encoding))
2673                     ))
2674                 ))))
2675         (or not-decode-text
2676             (decode-mime-charset-region (point-min) (point-max)
2677                                         default-mime-charset)
2678             )
2679         ))))
2680
2681 (defun mime-edit-again (&optional not-decode-text no-separator not-turn-on)
2682   "Convert current buffer to MIME-Edit buffer and turn on MIME-Edit mode.
2683 Content-Type and Content-Transfer-Encoding header fields will be
2684 converted to MIME-Edit tags."
2685   (interactive)
2686   (goto-char (point-min))
2687   (if (search-forward
2688        (concat "\n" (regexp-quote mail-header-separator) "\n")
2689        nil t)
2690       (replace-match "\n\n")
2691     )
2692   (mime-edit-decode-buffer not-decode-text)
2693   (goto-char (point-min))
2694   (save-restriction
2695     (std11-narrow-to-header)
2696     (goto-char (point-min))
2697     (while (re-search-forward mime-edit-again-ignored-field-regexp nil t)
2698       (delete-region (match-beginning 0) (1+ (std11-field-end)))
2699       ))
2700   (or no-separator
2701       (and (re-search-forward "^$")
2702            (replace-match mail-header-separator)
2703            ))
2704   (or not-turn-on
2705       (turn-on-mime-edit)
2706       ))
2707
2708
2709 ;;; @ end
2710 ;;;
2711
2712 (provide 'mime-edit)
2713
2714 (run-hooks 'mime-edit-load-hook)
2715
2716 ;;; mime-edit.el ends here