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