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