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