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