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