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