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