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