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