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