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