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