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