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