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