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