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