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