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