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