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