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