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