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