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