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