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