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