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