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