03587b0fafdff18ea0c7045ecab1c7032f112f95
[elisp/tm.git] / tm-edit.el
1 ;;; tm-edit.el --- Simple MIME Composer for GNU Emacs
2
3 ;; Copyright (C) 1993 .. 1996 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 ;; Version: $Revision: 7.98 $
10 ;; Keywords: mail, news, MIME, multimedia, multilingual
11
12 ;; This file is part of tm (Tools for MIME).
13
14 ;; This program is free software; you can redistribute it and/or
15 ;; modify it under the terms of the GNU General Public License as
16 ;; published by the Free Software Foundation; either version 2, or (at
17 ;; your option) any later version.
18
19 ;; This program is distributed in the hope that it will be useful, but
20 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22 ;; General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
26 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28
29 ;;; Commentary:
30
31 ;; This is an Emacs minor mode for editing Internet multimedia
32 ;; messages formatted in MIME (RFC 2045, 2046, 2047, 2048 and 2049).
33 ;; All messages in this mode are composed in the tagged MIME format,
34 ;; that are described in the following examples.  The messages
35 ;; composed in the tagged MIME format are automatically translated
36 ;; into a MIME compliant message when exiting the mode.
37
38 ;; Mule (a multilingual extension to Emacs 18 and 19) has a capability
39 ;; of handling multilingual text in limited ISO-2022 manner that is
40 ;; based on early experiences in Japanese Internet community and
41 ;; resulted in RFC 1468 (ISO-2022-JP charset for MIME).  In order to
42 ;; enable multilingual capability in single text message in MIME,
43 ;; charset of multilingual text written in Mule is declared as either
44 ;; `ISO-2022-JP-2' [RFC 1554] or `ISO-2022-INT-1'.  Mule is required
45 ;; for reading the such messages.
46
47 ;; This MIME composer can work with Mail mode, mh-e letter Mode, and
48 ;; News mode.  First of all, you need the following autoload
49 ;; definition to load mime/editor-mode automatically:
50 ;;
51 ;; (autoload 'mime/editor-mode "tm-edit"
52 ;;           "Minor mode for editing MIME message." t)
53 ;;
54 ;; In case of Mail mode (includes VM mode), you need the following
55 ;; hook definition:
56 ;;
57 ;; (add-hook 'mail-mode-hook 'mime/editor-mode)
58 ;; (add-hook 'mail-send-hook 'mime-editor/maybe-translate)
59 ;;
60 ;; In case of MH-E, you need the following hook definition:
61 ;;
62 ;; (add-hook 'mh-letter-mode-hook
63 ;;           (function
64 ;;            (lambda ()
65 ;;              (mime/editor-mode)
66 ;;              (make-local-variable 'mail-header-separator)
67 ;;              (setq mail-header-separator "--------")
68 ;;              ))))
69 ;; (add-hook 'mh-before-send-letter-hook 'mime-editor/maybe-translate)
70 ;;
71 ;; In case of News mode, you need the following hook definition:
72 ;;
73 ;; (add-hook 'news-reply-mode-hook 'mime/editor-mode)
74 ;; (add-hook 'news-inews-hook 'mime-editor/maybe-translate)
75 ;;
76 ;; In case of Emacs 19, it is possible to emphasize the message tags
77 ;; using font-lock mode as follows:
78 ;;
79 ;; (add-hook 'mime/editor-mode-hook
80 ;;           (function
81 ;;            (lambda ()
82 ;;              (font-lock-mode 1)
83 ;;              (setq font-lock-keywords (list mime-editor/tag-regexp))
84 ;;              ))))
85
86 ;; The message tag looks like:
87 ;;
88 ;;      --[[TYPE/SUBTYPE;PARAMETERS][ENCODING]]
89 ;;
90 ;; The tagged MIME message examples:
91 ;;
92 ;; This is a conventional plain text.  It should be translated into
93 ;; text/plain.
94 ;; 
95 ;;--[[text/plain]]
96 ;; This is also a plain text.  But, it is explicitly specified as is.
97 ;;
98 ;;--[[text/plain; charset=ISO-2022-JP]]
99 ;; \e$B$3$l$O\e(B charset \e$B$r\e(B ISO-2022-JP \e$B$K;XDj$7$?F|K\8l$N\e(B plain \e$B%F%-%9%H$G$9\e(B.
100 ;;
101 ;;--[[text/richtext]]
102 ;; <center>This is a richtext.</center>
103 ;;
104 ;;--[[image/gif][base64]]^M...image encoded in base64 comes here...
105 ;;
106 ;;--[[audio/basic][base64]]^M...audio encoded in base64 comes here...
107
108 ;;; Code:
109
110 (require 'sendmail)
111 (require 'mail-utils)
112 (require 'mel)
113 (require 'tl-list)
114 (require 'tm-view)
115 (require 'tm-ew-e)
116 (require 'signature)
117
118
119 ;;; @ version
120 ;;;
121
122 (defconst mime-editor/RCS-ID
123   "$Id: tm-edit.el,v 7.98 1996/12/23 14:49:34 morioka Exp $")
124
125 (defconst mime-editor/version (get-version-string mime-editor/RCS-ID))
126
127 (defconst mime-editor/version-name
128   (concat "tm-edit " mime-editor/version))
129
130
131 ;;; @ variables
132 ;;;
133
134 (defvar mime-prefix "\C-c\C-x"
135   "*Keymap prefix for MIME commands.")
136
137 (defvar mime-ignore-preceding-spaces nil
138   "*Ignore preceding white spaces if non-nil.")
139
140 (defvar mime-ignore-trailing-spaces nil
141   "*Ignore trailing white spaces if non-nil.")
142
143 (defvar mime-ignore-same-text-tag t
144   "*Ignore preceding text content-type tag that is same with new one.
145 If non-nil, the text tag is not inserted unless something different.")
146
147 (defvar mime-auto-hide-body t
148   "*Hide non-textual body encoded in base64 after insertion if non-nil.")
149
150 (defvar mime-editor/voice-recorder
151   (function mime-editor/voice-recorder-for-sun)
152   "*Function to record a voice message and encode it. [tm-edit.el]")
153
154 (defvar mime/editor-mode-hook nil
155   "*Hook called when enter MIME mode.")
156
157 (defvar mime-editor/translate-hook nil
158   "*Hook called before translating into a MIME compliant message.
159 To insert a signature file automatically, call the function
160 `mime-editor/insert-signature' from this hook.")
161
162 (defvar mime-editor/exit-hook nil
163   "*Hook called when exit MIME mode.")
164
165 (defvar mime-content-types
166   '(("text"
167      ;; Charset parameter need not to be specified, since it is
168      ;; defined automatically while translation.
169      ("plain"
170       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
171       )
172      ("richtext"
173       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
174       )
175      ("enriched"
176       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
177       )
178      ("x-latex"
179       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
180       )
181      ("html"
182       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
183       )
184      ("x-rot13-47")
185      )
186     ("message"
187      ("external-body"
188       ("access-type"
189        ("anon-ftp"
190         ("site" "ftp.jaist.ac.jp" "wnoc-fuk.wide.ad.jp" "nic.karrn.ad.jp")
191         ("directory" "/pub/GNU/elisp/mime")
192         ("name")
193         ("mode" "image" "ascii" "local8"))
194        ("ftp"
195         ("site")
196         ("directory")
197         ("name")
198         ("mode" "image" "ascii" "local8"))
199        ("tftp"        ("site") ("name"))
200        ("afs"         ("site") ("name"))
201        ("local-file"  ("site") ("name"))
202        ("mail-server" ("server" "ftpmail@nic.karrn.ad.jp"))
203        ))
204      ("rfc822")
205      )
206     ("application"
207      ("octet-stream" ("type" "" "tar" "shar"))
208      ("postscript")
209      ("x-kiss" ("x-cnf")))
210     ("image"
211      ("gif")
212      ("jpeg")
213      ("tiff")
214      ("x-pic")
215      ("x-mag")
216      ("x-xwd")
217      ("x-xbm")
218      )
219     ("audio" ("basic"))
220     ("video" ("mpeg"))
221     )
222   "*Alist of content-type, subtype, parameters and its values.")
223
224 (defvar mime-file-types
225   '(("\\.rtf$"
226      "text"     "richtext"      nil
227      nil
228      nil                nil)
229     ("\\.html$"
230      "text"     "html"          nil
231      nil
232      nil                nil)
233     ("\\.ps$"
234      "application" "postscript" nil
235      "quoted-printable"
236      "attachment"       (("filename" . file))
237      )
238     ("\\.jpg$"
239      "image"    "jpeg"          nil
240      "base64"
241      "inline"           (("filename" . file))
242      )
243     ("\\.gif$"
244      "image"    "gif"           nil
245      "base64"
246      "inline"           (("filename" . file))
247      )
248     ("\\.tiff$"
249      "image"    "tiff"          nil
250      "base64"
251      "inline"           (("filename" . file))
252      )
253     ("\\.pic$"
254      "image"    "x-pic"         nil
255      "base64"
256      "inline"           (("filename" . file))
257      )
258     ("\\.mag$"
259      "image"    "x-mag"         nil
260      "base64"
261      "inline"           (("filename" . file))
262      )
263     ("\\.xbm$"
264      "image"    "x-xbm"         nil
265      "base64"
266      "inline"           (("filename" . file))
267      )
268     ("\\.xwd$"
269      "image"    "x-xwd"         nil
270      "base64"
271      "inline"           (("filename" . file))
272      )
273     ("\\.au$"
274      "audio"    "basic"         nil
275      "base64"
276      "attachment"               (("filename" . file))
277      )
278     ("\\.mpg$"
279      "video"    "mpeg"          nil
280      "base64"
281      "attachment"       (("filename" . file))
282      )
283     ("\\.el$"
284      "application" "octet-stream" (("type" . "emacs-lisp"))
285      "7bit"
286      "attachment"       (("filename" . file))
287      )
288     ("\\.lsp$"
289      "application" "octet-stream" (("type" . "common-lisp"))
290      "7bit"
291      "attachment"       (("filename" . file))
292      )
293     ("\\.tar\\.gz$"
294      "application" "octet-stream" (("type" . "tar+gzip"))
295      nil
296      "attachment"       (("filename" . file))
297      )
298     ("\\.tgz$"
299      "application" "octet-stream" (("type" . "tar+gzip"))
300      nil
301      "attachment"       (("filename" . file))
302      )
303     ("\\.tar\\.Z$"
304      "application" "octet-stream" (("type" . "tar+compress"))
305      nil
306      "attachment"       (("filename" . file))
307      )
308     ("\\.taz$"
309      "application" "octet-stream" (("type" . "tar+compress"))
310      nil
311      "attachment"       (("filename" . file))
312      )
313     ("\\.gz$"
314      "application" "octet-stream" (("type" . "gzip"))
315      nil
316      "attachment"       (("filename" . file))
317      )
318     ("\\.Z$"
319      "application" "octet-stream" (("type" . "compress"))
320      nil
321      "attachment"       (("filename" . file))
322      )
323     ("\\.lzh$"
324      "application" "octet-stream" (("type" . "lha"))
325      nil
326      "attachment"       (("filename" . file))
327      )
328     ("\\.zip$"
329      "application" "zip" nil
330      nil
331      "attachment"       (("filename" . file))
332      )
333     ("\\.diff$"
334      "application" "octet-stream" (("type" . "patch"))
335      nil
336      "attachment"       (("filename" . file))
337      )
338     ("\\.patch$"
339      "application" "octet-stream" (("type" . "patch"))
340      nil
341      "attachment"       (("filename" . file))
342      )
343     ("\\.signature"
344      "text"     "plain"         nil     nil)
345     (".*"
346      "application" "octet-stream" nil
347      nil
348      "attachment"       (("filename" . file))
349      )
350     )
351   "*Alist of file name, types, parameters, and default encoding.
352 If encoding is nil, it is determined from its contents.")
353
354 ;;; @@ about charset, encoding and transfer-level
355 ;;;
356
357 (defvar mime-editor/transfer-level 7
358   "*A number of network transfer level. It should be bigger than 7.")
359 (make-variable-buffer-local 'mime-editor/transfer-level)
360
361 (defvar mime-editor/transfer-level-string
362   (mime/encoding-name mime-editor/transfer-level 'not-omit)
363   "*A string formatted version of mime/defaul-transfer-level")
364 (make-variable-buffer-local 'mime-editor/transfer-level-string)
365
366 (defun mime-editor/make-charset-default-encoding-alist (transfer-level)
367   (mapcar (function
368            (lambda (charset-type)
369              (let ((charset  (car charset-type))
370                    (type     (nth 1 charset-type))
371                    (encoding (nth 2 charset-type))
372                    )
373                (if (<= type transfer-level)
374                    (cons charset (mime/encoding-name type))
375                  (cons charset encoding)
376                  ))))
377           mime-charset-type-list))
378
379 (defvar mime-editor/charset-default-encoding-alist
380   (mime-editor/make-charset-default-encoding-alist mime-editor/transfer-level))
381 (make-variable-buffer-local 'mime-editor/charset-default-encoding-alist)
382
383 ;;; @@ about message inserting
384 ;;;
385
386 (defvar mime-editor/yank-ignored-field-list
387   '("Received" "Approved" "Path" "Replied" "Status"
388     "Xref" "X-UIDL" "X-Filter" "X-Gnus-.*" "X-VM-.*")
389   "Delete these fields from original message when it is inserted
390 as message/rfc822 part.
391 Each elements are regexp of field-name. [tm-edit.el]")
392
393 (defvar mime-editor/yank-ignored-field-regexp
394   (concat "^"
395           (apply (function regexp-or) mime-editor/yank-ignored-field-list)
396           ":"))
397
398 (defvar mime-editor/message-inserter-alist nil)
399 (defvar mime-editor/mail-inserter-alist nil)
400
401 ;;; @@ about message splitting
402 ;;;
403
404 (defvar mime-editor/split-message t
405   "*Split large message if it is non-nil. [tm-edit.el]")
406
407 (defvar mime-editor/message-default-max-lines 1000
408   "*Default maximum lines of a message. [tm-edit.el]")
409
410 (defvar mime-editor/message-max-lines-alist
411   '((news-reply-mode . 500))
412   "Alist of major-mode vs maximum lines of a message.
413 If it is not specified for a major-mode,
414 `mime-editor/message-default-max-lines' is used. [tm-edit.el]")
415
416 (defconst mime-editor/split-ignored-field-regexp
417   "\\(^Content-\\|^Subject:\\|^Mime-Version:\\)")
418
419 (defvar mime-editor/split-blind-field-regexp
420   "\\(^[BDFbdf]cc:\\|^cc:[ \t]*$\\)")
421
422 (defvar mime-editor/split-message-sender-alist nil)
423
424 (defvar mime-editor/news-reply-mode-server-running nil)
425
426
427 ;;; @@ about PGP
428 ;;;
429
430 (defvar mime-editor/signing-type 'pgp-elkins
431   "*PGP signing type (pgp-elkins, pgp-kazu or nil). [tm-edit.el]")
432
433 (defvar mime-editor/encrypting-type 'pgp-elkins
434   "*PGP encrypting type (pgp-elkins, pgp-kazu or nil). [tm-edit.el]")
435
436 (defvar mime-editor/pgp-sign-function 'tm:mc-pgp-sign-region)
437 (defvar mime-editor/pgp-encrypt-function 'tm:mc-pgp-encrypt-region)
438 (defvar mime-editor/traditional-pgp-sign-function 'mc-pgp-sign-region)
439 (defvar mime-editor/pgp-insert-public-key-function 'mc-insert-public-key)
440
441 (autoload mime-editor/pgp-sign-function "tm-edit-mc")
442 (autoload mime-editor/pgp-encrypt-function "tm-edit-mc")
443 (autoload mime-editor/traditional-pgp-sign-function "mc-pgp")
444 (autoload mime-editor/pgp-insert-public-key-function "mc-toplev")
445
446
447 ;;; @@ about tag
448 ;;;
449
450 (defconst mime-editor/single-part-tag-regexp
451   "--[[][[]\\([^]]*\\)]\\([[]\\([^]]*\\)]\\|\\)]"
452   "*Regexp of MIME tag in the form of [[CONTENT-TYPE][ENCODING]].")
453
454 (defconst mime-editor/quoted-single-part-tag-regexp
455   (concat "- " (substring mime-editor/single-part-tag-regexp 1)))
456
457 (defconst mime-editor/multipart-beginning-regexp "--<<\\([^<>]+\\)>>-{\n")
458
459 (defconst mime-editor/multipart-end-regexp "--}-<<\\([^<>]+\\)>>\n")
460
461 (defconst mime-editor/beginning-tag-regexp
462   (regexp-or mime-editor/single-part-tag-regexp
463              mime-editor/multipart-beginning-regexp))
464
465 (defconst mime-editor/end-tag-regexp
466   (regexp-or mime-editor/single-part-tag-regexp
467              mime-editor/multipart-end-regexp))
468
469 (defconst mime-editor/tag-regexp
470   (regexp-or mime-editor/single-part-tag-regexp
471              mime-editor/multipart-beginning-regexp
472              mime-editor/multipart-end-regexp))
473
474 (defvar mime-tag-format "--[[%s]]"
475   "*Control-string making a MIME tag.")
476
477 (defvar mime-tag-format-with-encoding "--[[%s][%s]]"
478   "*Control-string making a MIME tag with encoding.")
479
480 ;;; @@ multipart boundary
481 ;;;
482
483 (defvar mime-multipart-boundary "Multipart"
484   "*Boundary of a multipart message.")
485
486
487 ;;; @@ buffer local variables
488 ;;;
489
490 (defvar mime/editor-mode-old-local-map nil)
491 (defvar mime/editing-buffer nil)
492
493 \f
494 ;;; @ constants
495 ;;;
496
497 (defconst mime-tspecials-regexp "[][()<>@,;:\\\"/?.= \t]"
498   "*Specify MIME tspecials.
499 Tspecials means any character that matches with it in header must be quoted.")
500
501 (defconst mime-editor/mime-version-value
502   (concat "1.0 (generated by " mime-editor/version-name ")")
503   "MIME version number.")
504
505 (defconst mime-editor/mime-map (make-sparse-keymap)
506   "Keymap for MIME commands.")
507
508 ;;; @ keymap and menu
509 ;;;
510
511 (defvar mime/editor-mode-flag nil)
512 (make-variable-buffer-local 'mime/editor-mode-flag)
513
514 (defun mime-editor/define-keymap (keymap)
515   "Add mime-editor commands to KEYMAP."
516   (if (not (keymapp keymap))
517       nil
518     (define-key keymap "\C-t" 'mime-editor/insert-text)
519     (define-key keymap "\C-i" 'mime-editor/insert-file)
520     (define-key keymap "\C-e" 'mime-editor/insert-external)
521     (define-key keymap "\C-v" 'mime-editor/insert-voice)
522     (define-key keymap "\C-y" 'mime-editor/insert-message)
523     (define-key keymap "\C-m" 'mime-editor/insert-mail)
524     (define-key keymap "\C-w" 'mime-editor/insert-signature)
525     (define-key keymap "\C-s" 'mime-editor/insert-signature)
526     (define-key keymap "\C-k" 'mime-editor/insert-key)
527     (define-key keymap "t"    'mime-editor/insert-tag)
528     (define-key keymap "a"    'mime-editor/enclose-alternative-region)
529     (define-key keymap "p"    'mime-editor/enclose-parallel-region)
530     (define-key keymap "m"    'mime-editor/enclose-mixed-region)
531     (define-key keymap "d"    'mime-editor/enclose-digest-region)
532     (define-key keymap "s"    'mime-editor/enclose-signed-region)
533     (define-key keymap "e"    'mime-editor/enclose-encrypted-region)
534     (define-key keymap "q"    'mime-editor/enclose-quote-region)
535     (define-key keymap "7"    'mime-editor/set-transfer-level-7bit)
536     (define-key keymap "8"    'mime-editor/set-transfer-level-8bit)
537     (define-key keymap "/"    'mime-editor/set-split)
538     (define-key keymap "v"    'mime-editor/set-sign)
539     (define-key keymap "h"    'mime-editor/set-encrypt)
540     (define-key keymap "\C-p" 'mime-editor/preview-message)
541     (define-key keymap "\C-z" 'mime-editor/exit)
542     (define-key keymap "?"    'mime-editor/help)
543     ))
544
545 (mime-editor/define-keymap mime-editor/mime-map)
546
547 (defun mime-editor/toggle-mode ()
548   (interactive)
549   (if mime/editor-mode-flag
550       (mime-editor/exit 'nomime)
551     (mime/editor-mode)
552     ))
553
554 (cond (running-xemacs
555        (defconst mime-editor/minor-mime-map nil "Keymap for MIME commands.")
556        (or mime-editor/minor-mime-map
557            (progn
558              (setq mime-editor/minor-mime-map 
559                    (make-sparse-keymap 'mime-editor/minor-mime-map))
560              (define-key
561                mime-editor/minor-mime-map mime-prefix mime-editor/mime-map)
562              ))
563        (add-minor-mode 'mime/editor-mode-flag
564                        '((" MIME-Edit "  mime-editor/transfer-level-string))
565                        mime-editor/minor-mime-map
566                        nil
567                        'mime-editor/toggle-mode)
568        )
569       (t
570        (set-alist 'minor-mode-alist
571                   'mime/editor-mode-flag
572                   '((" MIME-Edit "  mime-editor/transfer-level-string))))
573       )
574
575 (defconst mime-editor/menu-title "MIME-Edit")
576
577 (defconst mime-editor/menu-list
578   '((mime-help  "Describe MIME editor mode" mime-editor/help)
579     (file       "Insert File"           mime-editor/insert-file)
580     (external   "Insert External"       mime-editor/insert-external)
581     (voice      "Insert Voice"          mime-editor/insert-voice)
582     (message    "Insert Message"        mime-editor/insert-message)
583     (mail       "Insert Mail"           mime-editor/insert-mail)
584     (signature  "Insert Signature"      mime-editor/insert-signature)
585     (text       "Insert Text"           mime-editor/insert-text)
586     (tag        "Insert Tag"            mime-editor/insert-tag)
587     (alternative "Enclose as alternative"
588                  mime-editor/enclose-alternative-region)
589     (parallel   "Enclose as parallel"   mime-editor/enclose-parallel-region)
590     (mixed      "Enclose as serial"     mime-editor/enclose-mixed-region)
591     (digest     "Enclose as digest"     mime-editor/enclose-digest-region)
592     (signed     "Enclose as signed"     mime-editor/enclose-signed-region)
593     (encrypted  "Enclose as encrypted"  mime-editor/enclose-encrypted-region)
594     (quote      "Verbatim region"       mime-editor/enclose-quote-region)
595     (key        "Insert Public Key"     mime-editor/insert-key)
596     (split      "About split"           mime-editor/set-split)
597     (sign       "About sign"            mime-editor/set-sign)
598     (encrypt    "About encryption"      mime-editor/set-encrypt)
599     (preview    "Preview Message"       mime-editor/preview-message)
600     (level      "Toggle transfer-level" mime-editor/toggle-transfer-level)
601     )
602   "MIME-edit menubar entry.")
603
604 (defun mime-editor/define-menu-for-emacs19 ()
605   "Define menu for Emacs 19."
606   (define-key (current-local-map) [menu-bar mime-edit]
607     (cons mime-editor/menu-title
608           (make-sparse-keymap mime-editor/menu-title)))
609   (mapcar (function
610            (lambda (item)
611              (define-key (current-local-map)
612                (vector 'menu-bar 'mime-edit (car item))
613                (cons (nth 1 item)(nth 2 item))
614                )
615              ))
616           (reverse mime-editor/menu-list)
617           ))
618
619 ;;; modified by Pekka Marjola <pema@iki.fi>
620 ;;;     1995/9/5 (c.f. [tm-en:69])
621 (defun mime-editor/define-menu-for-xemacs ()
622   "Define menu for Emacs 19."
623   (cond ((featurep 'menubar)
624          (make-local-variable 'current-menubar)
625          (set-buffer-menubar current-menubar)
626          (add-submenu nil
627                       (cons mime-editor/menu-title
628                             (mapcar (function
629                                      (lambda (item)
630                                        (vector (nth 1 item)(nth 2 item)
631                                                mime/editor-mode-flag)
632                                        ))
633                                     mime-editor/menu-list)))
634          )))
635
636 ;;; modified by Steven L. Baur <steve@miranova.com>
637 ;;;     1995/12/6 (c.f. [tm-en:209])
638 (if (and running-xemacs (not (boundp 'mime-editor/popup-menu-for-xemacs)))
639     (setq mime-editor/popup-menu-for-xemacs
640           (append '("MIME Commands" "---")
641                   (mapcar (function (lambda (item)
642                                       (vector (nth 1 item)
643                                               (nth 2 item)
644                                               t)))
645                           mime-editor/menu-list)))
646   )
647 ;;; end
648
649
650 ;;; @ functions
651 ;;;
652
653 ;;;###autoload
654 (defun mime/editor-mode ()
655   "MIME minor mode for editing the tagged MIME message.
656
657 In this mode, basically, the message is composed in the tagged MIME
658 format. The message tag looks like:
659
660         `--[[text/plain; charset=ISO-2022-JP][7bit]]'.
661
662 The tag specifies the MIME content type, subtype, optional parameters
663 and transfer encoding of the message following the tag. Messages
664 without any tag are treated as `text/plain' by default. Charset and
665 transfer encoding are automatically defined unless explicitly
666 specified. Binary messages such as audio and image are usually hidden.
667 The messages in the tagged MIME format are automatically translated
668 into a MIME compliant message when exiting this mode.
669
670 Available charsets depend on Emacs version being used. The following
671 lists the available charsets of each emacs.
672
673 EMACS 18:       US-ASCII is only available.
674 NEmacs:         US-ASCII and ISO-2022-JP are available.
675 EMACS 19:       US-ASCII and ISO-8859-1 (or other charset) are available.
676 XEmacs 19:      US-ASCII and ISO-8859-1 (or other charset) are available.
677 Mule:           US-ASCII, ISO-8859-* (except for ISO-8859-5), KOI8-R,
678                 ISO-2022-JP, ISO-2022-JP-2, ISO-2022-KR, BIG5 and
679                 ISO-2022-INT-1 are available.
680
681 ISO-2022-JP-2 and ISO-2022-INT-1 charsets used in mule is expected to
682 be used to represent multilingual text in intermixed manner. Any
683 languages that has no registered charset are represented as either
684 ISO-2022-JP-2 or ISO-2022-INT-1 in mule.
685
686 If you want to use non-ISO-8859-1 charset in EMACS 19 or XEmacs 19,
687 please set variable `default-mime-charset'. This variable must be
688 symbol of which name is a MIME charset.
689
690 If you want to add more charsets in mule, please set variable
691 `charsets-mime-charset-alist'. This variable must be alist of which
692 key is list of leading-char/charset and value is symbol of MIME
693 charset. (leading-char is a term of MULE 1.* and 2.*. charset is a
694 term of XEmacs/mule, mule merged EMACS and MULE 3.*) If name of
695 coding-system is different as MIME charset, please set variable
696 `mime-charset-coding-system-alist'. This variable must be alist of
697 which key is MIME charset and value is coding-system.
698
699 Following commands are available in addition to major mode commands:
700 \\[mime-editor/insert-text]     insert a text message.
701 \\[mime-editor/insert-file]     insert a (binary) file.
702 \\[mime-editor/insert-external] insert a reference to external body.
703 \\[mime-editor/insert-voice]    insert a voice message.
704 \\[mime-editor/insert-message]  insert a mail or news message.
705 \\[mime-editor/insert-mail]     insert a mail message.
706 \\[mime-editor/insert-signature]        insert a signature file at end.
707 \\[mime-editor/insert-tag]      insert a new MIME tag.
708 \\[mime-editor/enclose-alternative-region]      enclose as multipart/alternative.
709 \\[mime-editor/enclose-parallel-region] enclose as multipart/parallel.
710 \\[mime-editor/enclose-mixed-region]    enclose as multipart/mixed.
711 \\[mime-editor/enclose-digest-region]   enclose as multipart/digest.
712 \\[mime-editor/enclose-signed-region]   enclose as PGP signed.
713 \\[mime-editor/enclose-encrypted-region]        enclose as PGP encrypted.
714 \\[mime-editor/insert-key]      insert PGP public key.
715 \\[mime-editor/preview-message] preview editing MIME message.
716 \\[mime-editor/exit]    exit and translate into a MIME compliant message.
717 \\[mime-editor/maybe-translate] exit and translate if in MIME mode, then split.
718 \\[mime-editor/help]    show this help.
719
720 Additional commands are available in some major modes:
721 C-c C-c         exit, translate and run the original command.
722 C-c C-s         exit, translate and run the original command.
723
724 The following is a message example written in the tagged MIME format.
725 TABs at the beginning of the line are not a part of the message:
726
727         This is a conventional plain text.  It should be translated
728         into text/plain.
729         --[[text/plain]]
730         This is also a plain text.  But, it is explicitly specified as
731         is.
732         --[[text/plain; charset=ISO-2022-JP]]
733         \e$B$3$l$O\e(B charset \e$B$r\e(B ISO-2022-JP \e$B$K;XDj$7$?F|K\8l$N\e(B plain \e$B%F%-%9\e(B
734         \e$B%H$G$9\e(B.
735         --[[text/richtext]]
736         <center>This is a richtext.</center>
737         --[[image/gif][base64]]^M...image encoded in base64 here...
738         --[[audio/basic][base64]]^M...audio encoded in base64 here...
739
740 User customizable variables (not documented all of them):
741  mime-prefix
742     Specifies a key prefix for MIME minor mode commands.
743
744  mime-ignore-preceding-spaces
745     Preceding white spaces in a message body are ignored if non-nil.
746
747  mime-ignore-trailing-spaces
748     Trailing white spaces in a message body are ignored if non-nil.
749
750  mime-auto-fill-header
751     Fill header fields that contain encoded-words if non-nil.
752
753  mime-auto-hide-body
754     Hide a non-textual body message encoded in base64 after insertion
755     if non-nil.
756
757  mime-editor/voice-recorder
758     Specifies a function to record a voice message and encode it.
759     The function `mime-editor/voice-recorder-for-sun' is for Sun
760     SparcStations.
761
762  mime/editor-mode-hook
763     Turning on MIME mode calls the value of mime/editor-mode-hook, if
764     it is non-nil.
765
766  mime-editor/translate-hook
767     The value of mime-editor/translate-hook is called just before translating
768     the tagged MIME format into a MIME compliant message if it is
769     non-nil.  If the hook call the function mime-editor/insert-signature,
770     the signature file will be inserted automatically.
771
772  mime-editor/exit-hook
773     Turning off MIME mode calls the value of mime-editor/exit-hook, if it is
774     non-nil."
775   (interactive)
776   (if mime/editor-mode-flag
777       (error "You are already editing a MIME message.")
778     (setq mime/editor-mode-flag t)
779     ;; Remember old key bindings.
780     (if running-xemacs
781         (use-local-map (or (current-local-map) (make-sparse-keymap)))
782       (make-local-variable 'mime/editor-mode-old-local-map)
783       (setq mime/editor-mode-old-local-map (current-local-map))
784       ;; Add MIME commands to current local map.
785       (use-local-map (copy-keymap (or (current-local-map)
786                                       (make-sparse-keymap))))
787       )
788     (if (not (lookup-key (current-local-map) mime-prefix))
789         (define-key (current-local-map) mime-prefix mime-editor/mime-map))
790
791     ;; Set transfer level into mode line
792     ;;
793     (setq mime-editor/transfer-level-string
794           (mime/encoding-name mime-editor/transfer-level 'not-omit))
795     (force-mode-line-update)
796     
797     ;; Define menu.  Menus for other emacs implementations are
798     ;; welcome.
799     (cond (running-xemacs
800            (mime-editor/define-menu-for-xemacs))
801           ((>= emacs-major-version 19)
802            (mime-editor/define-menu-for-emacs19)
803            ))
804     ;; end
805     
806     (enable-invisible)
807     
808     ;; I don't care about saving these.
809     (setq paragraph-start
810           (regexp-or mime-editor/single-part-tag-regexp
811                      paragraph-start))
812     (setq paragraph-separate
813           (regexp-or mime-editor/single-part-tag-regexp
814                      paragraph-separate))
815     (run-hooks 'mime/editor-mode-hook)
816     (message
817      (substitute-command-keys
818       "Type \\[mime-editor/exit] to exit MIME mode, and type \\[mime-editor/help] to get help."))
819     ))
820
821 ;;;###autoload
822 (defalias 'edit-mime 'mime/editor-mode)         ; for convenience
823 (defalias 'mime-mode 'mime/editor-mode)         ; for convenience
824
825 (defun mime-editor/exit (&optional nomime no-error)
826   "Translate the tagged MIME message into a MIME compliant message.
827 With no argument encode a message in the buffer into MIME, otherwise
828 just return to previous mode."
829   (interactive "P")
830   (if (not mime/editor-mode-flag)
831       (if (null no-error)
832           (error "You aren't editing a MIME message.")
833         )
834     (if (not nomime)
835         (progn
836           (run-hooks 'mime-editor/translate-hook)
837           (mime-editor/translate-buffer)))
838     ;; Restore previous state.
839     (setq mime/editor-mode-flag nil)
840     (cond (running-xemacs
841            (delete-menu-item (list mime-editor/menu-title)))
842           (t
843            (use-local-map mime/editor-mode-old-local-map)))
844     
845     (end-of-invisible)
846     (set-buffer-modified-p (buffer-modified-p))
847     (run-hooks 'mime-editor/exit-hook)
848     (message "Exit MIME editor mode.")
849     ))
850
851 (defun mime-editor/maybe-translate ()
852   (interactive)
853   (mime-editor/exit nil t)
854   (call-interactively 'mime-editor/maybe-split-and-send)
855   )
856
857 (defun mime-editor/help ()
858   "Show help message about MIME mode."
859   (interactive)
860   (with-output-to-temp-buffer "*Help*"
861     (princ "MIME editor mode:\n")
862     (princ (documentation 'mime/editor-mode))
863     (print-help-return-message)))
864
865 (defun mime-editor/insert-text ()
866   "Insert a text message.
867 Charset is automatically obtained from the `mime/lc-charset-alist'."
868   (interactive)
869   (let ((ret (mime-editor/insert-tag "text" nil nil)))
870   (if ret
871       (progn
872         (if (looking-at mime-editor/single-part-tag-regexp)
873             (progn
874               ;; Make a space between the following message.
875               (insert "\n")
876               (forward-char -1)
877               ))
878         (if (and (member (second ret) '("enriched" "richtext"))
879                  (fboundp 'enriched-mode)
880                  )
881             (enriched-mode t)
882           (if (boundp 'enriched-mode)
883               (enriched-mode nil)
884             ))))))
885
886 (defun mime-editor/insert-file (file &optional verbose)
887   "Insert a message from a file."
888   (interactive "fInsert file as MIME message: \nP")
889   (let*  ((guess (mime-find-file-type file))
890           (type (nth 0 guess))
891           (subtype (nth 1 guess))
892           (parameters (nth 2 guess))
893           (encoding (nth 3 guess))
894           (disposition-type (nth 4 guess))
895           (disposition-params (nth 5 guess))
896           )
897     (if verbose
898         (setq type    (mime-prompt-for-type type)
899               subtype (mime-prompt-for-subtype type subtype)
900               ))
901     (if (interactive-p)
902         (setq encoding (mime-prompt-for-encoding encoding))
903       )
904     (if (or (consp parameters) (stringp disposition-type))
905         (let ((rest parameters) cell attribute value)
906           (setq parameters "")
907           (while rest
908             (setq cell (car rest))
909             (setq attribute (car cell))
910             (setq value (cdr cell))
911             (if (eq value 'file)
912                 (setq value (std11-wrap-as-quoted-string
913                              (file-name-nondirectory file)))
914               )
915             (setq parameters (concat parameters "; " attribute "=" value))
916             (setq rest (cdr rest))
917             )
918           (if disposition-type
919               (progn
920                 (setq parameters
921                       (concat parameters "\n"
922                               "Content-Disposition: " disposition-type))
923                 (setq rest disposition-params)
924                 (while rest
925                   (setq cell (car rest))
926                   (setq attribute (car cell))
927                   (setq value (cdr cell))
928                   (if (eq value 'file)
929                       (setq value (std11-wrap-as-quoted-string
930                                    (file-name-nondirectory file)))
931                     )
932                   (setq parameters
933                         (concat parameters "; " attribute "=" value))
934                   (setq rest (cdr rest))
935                   )
936                 ))
937           ))
938     (mime-editor/insert-tag type subtype parameters)
939     (mime-editor/insert-binary-file file encoding)
940     ))
941
942 (defun mime-editor/insert-external ()
943   "Insert a reference to external body."
944   (interactive)
945   (mime-editor/insert-tag "message" "external-body" nil ";\n\t")
946   ;;(forward-char -1)
947   ;;(insert "Content-Description: " (read-string "Content-Description: ") "\n")
948   ;;(forward-line 1)
949   (let* ((pritype (mime-prompt-for-type))
950          (subtype (mime-prompt-for-subtype pritype))
951          (parameters (mime-prompt-for-parameters pritype subtype ";\n\t")))
952     (and pritype
953          subtype
954          (insert "Content-Type: "
955                  pritype "/" subtype (or parameters "") "\n")))
956   (if (and (not (eobp))
957            (not (looking-at mime-editor/single-part-tag-regexp)))
958       (insert (mime-make-text-tag) "\n")))
959
960 (defun mime-editor/insert-voice ()
961   "Insert a voice message."
962   (interactive)
963   (let ((encoding
964          (completing-read
965           "What transfer encoding: "
966           mime-file-encoding-method-alist nil t nil)))
967     (mime-editor/insert-tag "audio" "basic" nil)
968     (mime-editor/define-encoding encoding)
969     (save-restriction
970       (narrow-to-region (1- (point))(point))
971       (unwind-protect
972           (funcall mime-editor/voice-recorder encoding)
973         (progn
974           (insert "\n")
975           (invisible-region (point-min)(point-max))
976           (goto-char (point-max))
977           )))))
978
979 (defun mime-editor/insert-signature (&optional arg)
980   "Insert a signature file."
981   (interactive "P")
982   (let ((signature-insert-hook
983          (function
984           (lambda ()
985             (apply (function mime-editor/insert-tag)
986                    (mime-find-file-type signature-file-name))
987             )))
988         )
989     (insert-signature arg)
990     ))
991
992 \f
993 ;; Insert a new tag around a point.
994
995 (defun mime-editor/insert-tag (&optional pritype subtype parameters delimiter)
996   "Insert new MIME tag and return a list of PRITYPE, SUBTYPE, and PARAMETERS.
997 If nothing is inserted, return nil."
998   (interactive)
999   (let ((p (point)))
1000     (mime-editor/goto-tag)
1001     (if (and (re-search-forward mime-editor/tag-regexp nil t)
1002              (< (match-beginning 0) p)
1003              (< p (match-end 0))
1004              )
1005         (goto-char (match-beginning 0))
1006       (goto-char p)
1007       ))
1008   (let ((oldtag nil)
1009         (newtag nil)
1010         (current (point))
1011         )
1012     (setq pritype
1013           (or pritype
1014               (mime-prompt-for-type)))
1015     (setq subtype
1016           (or subtype
1017               (mime-prompt-for-subtype pritype)))
1018     (setq parameters
1019           (or parameters
1020               (mime-prompt-for-parameters pritype subtype delimiter)))
1021     ;; Make a new MIME tag.
1022     (setq newtag (mime-make-tag pritype subtype parameters))
1023     ;; Find an current MIME tag.
1024     (setq oldtag
1025           (save-excursion
1026             (if (mime-editor/goto-tag)
1027                 (buffer-substring (match-beginning 0) (match-end 0))
1028               ;; Assume content type is 'text/plan'.
1029               (mime-make-tag "text" "plain")
1030               )))
1031     ;; We are only interested in TEXT.
1032     (if (and oldtag
1033              (not (mime-test-content-type
1034                    (mime-editor/get-contype oldtag) "text")))
1035         (setq oldtag nil))
1036     ;; Make a new tag.
1037     (if (or (not oldtag)                ;Not text
1038             (or mime-ignore-same-text-tag
1039                 (not (string-equal oldtag newtag))))
1040         (progn
1041           ;; Mark the beginning of the tag for convenience.
1042           (push-mark (point) 'nomsg)
1043           (insert newtag "\n")
1044           (list pritype subtype parameters) ;New tag is created.
1045           )
1046       ;; Restore previous point.
1047       (goto-char current)
1048       nil                               ;Nothing is created.
1049       )
1050     ))
1051
1052 (defun mime-editor/insert-binary-file (file &optional encoding)
1053   "Insert binary FILE at point.
1054 Optional argument ENCODING specifies an encoding method such as base64."
1055   (let* ((tagend (1- (point)))          ;End of the tag
1056          (hide-p (and mime-auto-hide-body
1057                       (stringp encoding)
1058                       (not
1059                        (let ((en (downcase encoding)))
1060                          (or (string-equal en "7bit")
1061                              (string-equal en "8bit")
1062                              (string-equal en "binary")
1063                              )))))
1064          )
1065     (save-restriction
1066       (narrow-to-region tagend (point))
1067       (mime-insert-encoded-file file encoding)
1068       (if hide-p
1069           (progn
1070             (invisible-region (point-min) (point-max))
1071             (goto-char (point-max))
1072             )
1073         (goto-char (point-max))
1074         ))
1075     (or hide-p
1076         (looking-at mime-editor/tag-regexp)
1077         (= (point)(point-max))
1078         (mime-editor/insert-tag "text" "plain")
1079         )
1080     ;; Define encoding even if it is 7bit.
1081     (if (stringp encoding)
1082         (save-excursion
1083           (goto-char tagend) ; Make sure which line the tag is on.
1084           (mime-editor/define-encoding encoding)
1085           ))
1086     ))
1087
1088 \f
1089 ;; Commands work on a current message flagment.
1090
1091 (defun mime-editor/goto-tag ()
1092   "Search for the beginning of the tagged MIME message."
1093   (let ((current (point)) multipart)
1094     (if (looking-at mime-editor/tag-regexp)
1095         t
1096       ;; At first, go to the end.
1097       (cond ((re-search-forward mime-editor/beginning-tag-regexp nil t)
1098              (goto-char (1- (match-beginning 0))) ;For multiline tag
1099              )
1100             (t
1101              (goto-char (point-max))
1102              ))
1103       ;; Then search for the beginning. 
1104       (re-search-backward mime-editor/end-tag-regexp nil t)
1105       (or (looking-at mime-editor/beginning-tag-regexp)
1106           ;; Restore previous point.
1107           (progn
1108             (goto-char current)
1109             nil
1110             ))
1111       )))
1112
1113 (defun mime-editor/content-beginning ()
1114   "Return the point of the beginning of content."
1115   (save-excursion
1116     (let ((beg (save-excursion
1117                  (beginning-of-line) (point))))
1118       (if (mime-editor/goto-tag)
1119           (let ((top (point)))
1120             (goto-char (match-end 0))
1121             (if (and (= beg top)
1122                      (= (following-char) ?\^M))
1123                 (point)
1124               (forward-line 1)
1125               (point)))
1126         ;; Default text/plain tag.
1127         (goto-char (point-min))
1128         (re-search-forward
1129          (concat "\n" (regexp-quote mail-header-separator)
1130                  (if mime-ignore-preceding-spaces
1131                      "[ \t\n]*\n" "\n")) nil 'move)
1132         (point))
1133       )))
1134
1135 (defun mime-editor/content-end ()
1136   "Return the point of the end of content."
1137   (save-excursion
1138     (let ((beg (point)))
1139       (if (mime-editor/goto-tag)
1140           (let ((top (point)))
1141             (goto-char (match-end 0))
1142             (if (invisible-p (point))
1143                 (next-visible-point (point))
1144               ;; Move to the end of this text.
1145               (if (re-search-forward mime-editor/tag-regexp nil 'move)
1146                   ;; Don't forget a multiline tag.
1147                   (goto-char (match-beginning 0))
1148                 )
1149               (point)
1150               ))
1151         ;; Assume the message begins with text/plain.
1152         (goto-char (mime-editor/content-beginning))
1153         (if (re-search-forward mime-editor/tag-regexp nil 'move)
1154             ;; Don't forget a multiline tag.
1155             (goto-char (match-beginning 0)))
1156         (point))
1157       )))
1158
1159 (defun mime-editor/define-charset (charset)
1160   "Set charset of current tag to CHARSET."
1161   (save-excursion
1162     (if (mime-editor/goto-tag)
1163         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1164           (delete-region (match-beginning 0) (match-end 0))
1165           (insert
1166            (mime-create-tag
1167             (mime-editor/set-parameter
1168              (mime-editor/get-contype tag)
1169              "charset" (upcase (symbol-name charset)))
1170             (mime-editor/get-encoding tag)))
1171           ))))
1172
1173 (defun mime-editor/define-encoding (encoding)
1174   "Set encoding of current tag to ENCODING."
1175   (save-excursion
1176     (if (mime-editor/goto-tag)
1177         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1178           (delete-region (match-beginning 0) (match-end 0))
1179           (insert (mime-create-tag (mime-editor/get-contype tag) encoding)))
1180       )))
1181
1182 (defun mime-editor/choose-charset ()
1183   "Choose charset of a text following current point."
1184   (detect-mime-charset-region (point) (mime-editor/content-end))
1185   )
1186
1187 (defun mime-make-text-tag (&optional subtype)
1188   "Make a tag for a text after current point.
1189 Subtype of text type can be specified by an optional argument SUBTYPE.
1190 Otherwise, it is obtained from mime-content-types."
1191   (let* ((pritype "text")
1192          (subtype (or subtype
1193                       (car (car (cdr (assoc pritype mime-content-types)))))))
1194     ;; Charset should be defined later.
1195     (mime-make-tag pritype subtype)))
1196
1197 \f
1198 ;; Tag handling functions
1199
1200 (defun mime-make-tag (pritype subtype &optional parameters encoding)
1201   "Make a tag of MIME message of PRITYPE, SUBTYPE and optional PARAMETERS."
1202   (mime-create-tag (concat (or pritype "") "/" (or subtype "")
1203                            (or parameters ""))
1204                    encoding))
1205
1206 (defun mime-create-tag (contype &optional encoding)
1207   "Make a tag with CONTENT-TYPE and optional ENCODING."
1208   (format (if encoding mime-tag-format-with-encoding mime-tag-format)
1209           contype encoding))
1210
1211 (defun mime-editor/get-contype (tag)
1212   "Return Content-Type (including parameters) of TAG."
1213   (and (stringp tag)
1214        (or (string-match mime-editor/single-part-tag-regexp tag)
1215            (string-match mime-editor/multipart-beginning-regexp tag)
1216            (string-match mime-editor/multipart-end-regexp tag)
1217            )
1218        (substring tag (match-beginning 1) (match-end 1))
1219        ))
1220
1221 (defun mime-editor/get-encoding (tag)
1222   "Return encoding of TAG."
1223   (and (stringp tag)
1224        (string-match mime-editor/single-part-tag-regexp tag)
1225        (match-beginning 3)
1226        (not (= (match-beginning 3) (match-end 3)))
1227        (substring tag (match-beginning 3) (match-end 3))))
1228
1229 (defun mime-get-parameter (contype parameter)
1230   "For given CONTYPE return value for PARAMETER.
1231 Nil if no such parameter."
1232   (if (string-match
1233        (concat
1234         ";[ \t\n]*"
1235         (regexp-quote parameter)
1236         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\([ \t\n]*;\\|$\\)")
1237        contype)
1238       (substring contype (match-beginning 1) (match-end 1))
1239     nil                                 ;No such parameter
1240     ))
1241
1242 (defun mime-editor/set-parameter (contype parameter value)
1243   "For given CONTYPE set PARAMETER to VALUE."
1244   (let (ctype opt-fields)
1245     (if (string-match "\n[^ \t\n\r]+:" contype)
1246         (setq ctype (substring contype 0 (match-beginning 0))
1247               opt-fields (substring contype (match-beginning 0)))
1248       (setq ctype contype)
1249       )
1250     (if (string-match
1251          (concat
1252           ";[ \t\n]*\\("
1253           (regexp-quote parameter)
1254           "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\)[ \t\n]*\\(;\\|$\\)")
1255          ctype)
1256         ;; Change value
1257         (concat (substring ctype 0 (match-beginning 1))
1258                 parameter "=" value
1259                 (substring contype (match-end 1))
1260                 opt-fields)
1261       (concat ctype "; " parameter "=" value opt-fields)
1262       )))
1263
1264 (defun mime-strip-parameters (contype)
1265   "Return primary content-type and subtype without parameters for CONTYPE."
1266   (if (string-match "^[ \t]*\\([^; \t\n]*\\)" contype)
1267       (substring contype (match-beginning 1) (match-end 1)) nil))
1268
1269 (defun mime-test-content-type (contype type &optional subtype)
1270   "Test if CONTYPE is a TYPE and an optional SUBTYPE."
1271   (and (stringp contype)
1272        (stringp type)
1273        (string-match
1274         (concat "^[ \t]*" (downcase type) "/" (downcase (or subtype "")))
1275         (downcase contype))))
1276
1277 \f
1278 ;; Basic functions
1279
1280 (defun mime-find-file-type (file)
1281   "Guess Content-Type, subtype, and parameters from FILE."
1282   (let ((guess nil)
1283         (guesses mime-file-types))
1284     (while (and (not guess) guesses)
1285       (if (string-match (car (car guesses)) file)
1286           (setq guess (cdr (car guesses))))
1287       (setq guesses (cdr guesses)))
1288     guess
1289     ))
1290
1291 (defun mime-prompt-for-type (&optional default)
1292   "Ask for Content-type."
1293   (let ((type ""))
1294     ;; Repeat until primary content type is specified.
1295     (while (string-equal type "")
1296       (setq type
1297             (completing-read "What content type: "
1298                              mime-content-types
1299                              nil
1300                              'require-match ;Type must be specified.
1301                              default
1302                              ))
1303       (if (string-equal type "")
1304           (progn
1305             (message "Content type is required.")
1306             (beep)
1307             (sit-for 1)
1308             ))
1309       )
1310     type))
1311
1312 (defun mime-prompt-for-subtype (type &optional default)
1313   "Ask for subtype of media-type TYPE."
1314   (let ((subtypes (cdr (assoc type mime-content-types))))
1315     (or (and default
1316              (assoc default subtypes))
1317         (setq default (car (car subtypes)))
1318         ))
1319   (let* ((answer
1320           (completing-read
1321            (if default
1322                (concat
1323                 "What content subtype: (default " default ") ")
1324              "What content subtype: ")
1325            (cdr (assoc type mime-content-types))
1326            nil
1327            'require-match               ;Subtype must be specified.
1328            nil
1329            )))
1330     (if (string-equal answer "") default answer)))
1331
1332 (defun mime-prompt-for-parameters (pritype subtype &optional delimiter)
1333   "Ask for Content-type parameters of Content-Type PRITYPE and SUBTYPE.
1334 Optional DELIMITER specifies parameter delimiter (';' by default)."
1335   (let* ((delimiter (or delimiter "; "))
1336          (parameters
1337           (mapconcat
1338            (function identity)
1339            (delq nil
1340                  (mime-prompt-for-parameters-1
1341                   (cdr (assoc subtype
1342                               (cdr (assoc pritype mime-content-types))))))
1343            delimiter
1344            )))
1345     (if (and (stringp parameters)
1346              (not (string-equal parameters "")))
1347         (concat delimiter parameters)
1348       ""                                ;"" if no parameters
1349       )))
1350
1351 (defun mime-prompt-for-parameters-1 (optlist)
1352   (apply (function append)
1353          (mapcar (function mime-prompt-for-parameter) optlist)))
1354
1355 (defun mime-prompt-for-parameter (parameter)
1356   "Ask for PARAMETER.
1357 Parameter must be '(PROMPT CHOICE1 (CHOISE2 ...))."
1358   (let* ((prompt (car parameter))
1359          (choices (mapcar (function
1360                            (lambda (e)
1361                              (if (consp e) e (list e))))
1362                           (cdr parameter)))
1363          (default (car (car choices)))
1364          (answer nil))
1365     (if choices
1366         (progn
1367           (setq answer
1368                 (completing-read
1369                  (concat "What " prompt
1370                          ": (default "
1371                          (if (string-equal default "") "\"\"" default)
1372                          ") ")
1373                  choices nil nil ""))
1374           ;; If nothing is selected, use default.
1375           (if (string-equal answer "")
1376               (setq answer default)))
1377       (setq answer
1378             (read-string (concat "What " prompt ": "))))
1379     (cons (if (and answer
1380                    (not (string-equal answer "")))
1381               (concat prompt "="
1382                       ;; Note: control characters ignored!
1383                       (if (string-match mime-tspecials-regexp answer)
1384                           (concat "\"" answer "\"") answer)))
1385           (mime-prompt-for-parameters-1 (cdr (assoc answer (cdr parameter)))))
1386     ))
1387
1388 (defun mime-prompt-for-encoding (default)
1389   "Ask for Content-Transfer-Encoding. [tm-edit.el]"
1390   (let ((ret
1391          (completing-read
1392           (concat "What transfer encoding"
1393                   (if default
1394                       (concat " (default "
1395                               (if (string-equal default "")
1396                                   "\"\""
1397                                 default)
1398                               ")"
1399                               ))
1400                   ": ")
1401           mime-file-encoding-method-alist nil t nil)
1402          ))
1403     (if (string= ret "")
1404         default
1405       ret)))
1406
1407 \f
1408 ;;; @ Translate the tagged MIME messages into a MIME compliant message.
1409 ;;;
1410
1411 (defvar mime-editor/translate-buffer-hook
1412   '(mime-editor/pgp-enclose-buffer
1413     mime-editor/translate-header
1414     mime-editor/translate-body))
1415
1416 (defun mime-editor/translate-header ()
1417   "Encode the message header into network representation."
1418   (mime/encode-message-header 'code-conversion)
1419   (run-hooks 'mime-editor/translate-header-hook)
1420   )
1421
1422 (defun mime-editor/translate-buffer ()
1423   "Encode the tagged MIME message in current buffer in MIME compliant message."
1424   (interactive)
1425   (if (catch 'mime-editor/error
1426         (save-excursion
1427           (run-hooks 'mime-editor/translate-buffer-hook)
1428           ))
1429       (progn
1430         (undo)
1431         (error "Translation error!")
1432         )))
1433
1434 (defun mime-editor/find-inmost ()
1435   (goto-char (point-min))
1436   (if (re-search-forward mime-editor/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-editor/multipart-beginning-regexp nil t)
1454             (let (ret)
1455               (narrow-to-region (match-beginning 0)(point-max))
1456               (mime-editor/find-inmost)
1457               )
1458           (widen)
1459           (list type bb be eb)
1460           ))))
1461
1462 (defun mime-editor/process-multipart-1 (boundary)
1463   (let ((ret (mime-editor/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-editor/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-editor/beginning-tag-regexp)
1481                     (eobp)
1482                     (insert (concat (mime-make-text-tag) "\n"))
1483                     )))
1484           (cond ((string-equal type "quote")
1485                  (mime-editor/enquote-region bb eb)
1486                  )
1487                 ((string-equal type "signed")
1488                  (cond ((eq mime-editor/signing-type 'pgp-elkins)
1489                         (mime-editor/sign-pgp-elkins bb eb boundary)
1490                         )
1491                        ((eq mime-editor/signing-type 'pgp-kazu)
1492                         (mime-editor/sign-pgp-kazu bb eb boundary)
1493                         ))
1494                  )
1495                 ((string-equal type "encrypted")
1496                  (cond ((eq mime-editor/encrypting-type 'pgp-elkins)
1497                         (mime-editor/encrypt-pgp-elkins bb eb boundary)
1498                         )
1499                        ((eq mime-editor/encrypting-type 'pgp-kazu)
1500                         (mime-editor/encrypt-pgp-kazu bb eb boundary)
1501                         )))
1502                 (t
1503                  (setq boundary
1504                        (nth 2 (mime-editor/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-editor/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-editor/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-editor/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-editor/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-editor/sign-pgp-elkins (beg end boundary)
1536   (save-excursion
1537     (save-restriction
1538       (narrow-to-region beg end)
1539       (let* ((ret
1540               (mime-editor/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 mime-editor/pgp-sign-function
1553                      (point-min)(point-max) nil nil pgp-boundary)
1554             (throw 'mime-editor/error 'pgp-error)
1555             )
1556         ))))
1557
1558 (defvar mime-editor/encrypt-recipient-fields-list '("To" "cc"))
1559
1560 (defun mime-editor/make-encrypt-recipient-header ()
1561   (let* ((names mime-editor/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-editor/encrypt-pgp-elkins (beg end boundary)
1593   (save-excursion
1594     (save-restriction
1595       (let (from recipients header)
1596         (let ((ret (mime-editor/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-editor/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 mime-editor/pgp-encrypt-function
1617                        recipients (point-min) (point-max) from)
1618               (throw 'mime-editor/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-editor/sign-pgp-kazu (beg end boundary)
1637   (save-excursion
1638     (save-restriction
1639       (narrow-to-region beg end)
1640       (let* ((ret
1641               (mime-editor/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 mime-editor/traditional-pgp-sign-function
1654                       beg (point-max)))
1655             (throw 'mime-editor/error 'pgp-error)
1656             )
1657         (goto-char beg)
1658         (insert
1659          "--[[application/pgp; format=mime][7bit]]\n")
1660         ))
1661     ))
1662
1663 (defun mime-editor/encrypt-pgp-kazu (beg end boundary)
1664   (save-excursion
1665     (let (from recipients header)
1666       (let ((ret (mime-editor/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-editor/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 mime-editor/pgp-encrypt-function
1688                         recipients beg (point-max) nil 'maybe)
1689                )
1690               (throw 'mime-editor/error 'pgp-error)
1691               )
1692           (goto-char beg)
1693           (insert
1694            "--[[application/pgp; format=mime][7bit]]\n")
1695           ))
1696       )))
1697
1698 (defun mime-editor/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-editor/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-editor/translate-region
1730                      beg end
1731                      (format "%s-%d" boundary i)))
1732           ))
1733       (mime-editor/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-editor/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-editor/translate-single-part-tag (&optional prefix)
1758   (if (re-search-forward mime-editor/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-editor/get-contype tag))
1765         (setq encoding (mime-editor/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-editor/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-editor/normalize-body)
1792         ;; Counting the number of Content-Type.
1793         (goto-char (point-min))
1794         (while (re-search-forward mime-editor/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-editor/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-editor/get-contype tag))
1807             (setq encoding (mime-editor/get-encoding tag))
1808             ))
1809          (t
1810           ;; It's a multipart message.
1811           (goto-char (point-min))
1812           (and (mime-editor/translate-single-part-tag)
1813                (while (mime-editor/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-editor/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-editor/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-editor/single-part-tag-regexp nil t)
1839     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1840            (contype (mime-editor/get-contype tag))
1841            (charset (mime-get-parameter contype "charset"))
1842            (encoding (mime-editor/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-editor/content-end))
1848             )
1849         (if (= end (point-max))
1850             nil
1851           (goto-char end)
1852           (or (looking-at mime-editor/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-editor/choose-charset)))
1869         (mime-editor/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-editor/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-editor/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-editor/charset-default-encoding-alist)
1905                      ))
1906                    (beg (mime-editor/content-beginning))
1907                    )
1908               (encode-mime-charset-region beg (mime-editor/content-end)
1909                                           charset)
1910               (mime-encode-region beg (mime-editor/content-end) encoding)
1911               (mime-editor/define-encoding encoding)
1912               ))
1913         (goto-char (mime-editor/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-editor/content-beginning))
1921                (end (mime-editor/content-end))
1922                (body (buffer-substring beg end))
1923                )
1924           (mime-encode-region beg end encoding)
1925           (mime-editor/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-editor/voice-recorder-for-sun (encoding)
1947   "Record voice in a buffer using Sun audio device,
1948 and insert data encoded as ENCODING. [tm-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-editor/insert-message (&optional message)
1961   (interactive)
1962   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
1963     (if (and inserter (fboundp inserter))
1964         (progn
1965           (mime-editor/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-editor/insert-mail (&optional message)
1972   (interactive)
1973   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
1974     (if (and inserter (fboundp inserter))
1975         (progn
1976           (mime-editor/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-editor/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-editor/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-editor/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-editor/beginning-tag-regexp)
2019           (eobp)
2020           (insert (mime-make-text-tag) "\n")
2021           )
2022       )))
2023
2024 (defun mime-editor/enclose-quote-region (beg end)
2025   (interactive "*r")
2026   (mime-editor/enclose-region "quote" beg end)
2027   )
2028
2029 (defun mime-editor/enclose-mixed-region (beg end)
2030   (interactive "*r")
2031   (mime-editor/enclose-region "mixed" beg end)
2032   )
2033
2034 (defun mime-editor/enclose-parallel-region (beg end)
2035   (interactive "*r")
2036   (mime-editor/enclose-region "parallel" beg end)
2037   )
2038
2039 (defun mime-editor/enclose-digest-region (beg end)
2040   (interactive "*r")
2041   (mime-editor/enclose-region "digest" beg end)
2042   )
2043
2044 (defun mime-editor/enclose-alternative-region (beg end)
2045   (interactive "*r")
2046   (mime-editor/enclose-region "alternative" beg end)
2047   )
2048
2049 (defun mime-editor/enclose-signed-region (beg end)
2050   (interactive "*r")
2051   (if mime-editor/signing-type
2052       (mime-editor/enclose-region "signed" beg end)
2053     (message "Please specify signing type.")
2054     ))
2055
2056 (defun mime-editor/enclose-encrypted-region (beg end)
2057   (interactive "*r")
2058   (if mime-editor/signing-type
2059       (mime-editor/enclose-region "encrypted" beg end)
2060     (message "Please specify encrypting type.")
2061     ))
2062
2063 (defun mime-editor/insert-key (&optional arg)
2064   "Insert a pgp public key."
2065   (interactive "P")
2066   (mime-editor/insert-tag "application" "pgp-keys")
2067   (mime-editor/define-encoding "7bit")
2068   (funcall mime-editor/pgp-insert-public-key-function)
2069   )
2070
2071
2072 ;;; @ flag setting
2073 ;;;
2074
2075 (defun mime-editor/set-split (arg)
2076   (interactive
2077    (list
2078     (y-or-n-p "Do you want to enable split?")
2079     ))
2080   (setq mime-editor/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-editor/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-editor/transfer-level transfer-level)
2093     (if (< mime-editor/transfer-level 8)
2094         (setq mime-editor/transfer-level 8)
2095       (setq mime-editor/transfer-level 7)
2096       ))
2097   (setq mime-editor/charset-default-encoding-alist
2098         (mime-editor/make-charset-default-encoding-alist
2099          mime-editor/transfer-level))
2100   (message (format "Current transfer-level is %d bit"
2101                    mime-editor/transfer-level))
2102   (setq mime-editor/transfer-level-string
2103         (mime/encoding-name mime-editor/transfer-level 'not-omit))
2104   (force-mode-line-update)
2105   )
2106
2107 (defun mime-editor/set-transfer-level-7bit ()
2108   (interactive)
2109   (mime-editor/toggle-transfer-level 7)
2110   )
2111
2112 (defun mime-editor/set-transfer-level-8bit ()
2113   (interactive)
2114   (mime-editor/toggle-transfer-level 8)
2115   )
2116
2117
2118 ;;; @ pgp
2119 ;;;
2120
2121 (defun mime-editor/set-sign (arg)
2122   (interactive
2123    (list
2124     (y-or-n-p "Do you want to sign?")
2125     ))
2126   (if arg
2127       (if mime-editor/signing-type
2128           (progn
2129             (setq mime-editor/pgp-processing 'sign)
2130             (message "This message will be signed.")
2131             )
2132         (message "Please specify signing type.")
2133         )
2134     (if (eq mime-editor/pgp-processing 'sign)
2135         (setq mime-editor/pgp-processing nil)
2136       )
2137     (message "This message will not be signed.")
2138     ))
2139
2140 (defun mime-editor/set-encrypt (arg)
2141   (interactive
2142    (list
2143     (y-or-n-p "Do you want to encrypt?")
2144     ))
2145   (if arg
2146       (if mime-editor/encrypting-type
2147           (progn
2148             (setq mime-editor/pgp-processing 'encrypt)
2149             (message "This message will be encrypt.")
2150             )
2151         (message "Please specify encrypting type.")
2152         )
2153     (if (eq mime-editor/pgp-processing 'encrypt)
2154         (setq mime-editor/pgp-processing nil)
2155       )
2156     (message "This message will not be encrypt.")
2157     ))
2158
2159 (defvar mime-editor/pgp-processing nil)
2160 (make-variable-buffer-local 'mime-editor/pgp-processing)
2161
2162 (defun mime-editor/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-editor/pgp-processing 'sign)
2172                (mime-editor/enclose-signed-region beg end)
2173                )
2174               ((eq mime-editor/pgp-processing 'encrypt)
2175                (mime-editor/enclose-encrypted-region beg end)
2176                ))
2177       )))
2178
2179
2180 ;;; @ split
2181 ;;;
2182
2183 (defun mime-editor/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-editor/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-editor/split-and-send
2195   (&optional cmd lines mime-editor/message-max-length)
2196   (interactive)
2197   (or lines
2198       (setq lines
2199             (count-lines (point-min) (point-max)))
2200       )
2201   (or mime-editor/message-max-length
2202       (setq mime-editor/message-max-length
2203             (or (cdr (assq major-mode mime-editor/message-max-lines-alist))
2204                 mime-editor/message-default-max-lines))
2205       )
2206   (let* ((mime-editor/draft-file-name 
2207           (or (buffer-file-name)
2208               (make-temp-name
2209                (expand-file-name "tm-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-editor/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-editor/split-ignored-field-regexp separator))
2219           (subject (mail-fetch-field "subject"))
2220           (total (+ (/ lines mime-editor/message-max-length)
2221                     (if (> (mod lines mime-editor/message-max-length) 0)
2222                         1)))
2223           (command
2224            (or cmd
2225                (cdr
2226                 (assq major-mode
2227                       mime-editor/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-editor/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-editor/split-blind-field-regexp nil t)
2249             (delete-region (match-beginning 0)
2250                            (1+ (std11-field-end)))
2251             )))
2252       (while (< mime-editor/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-editor/message-max-length)
2260                         (point))
2261                       ))
2262           (delete-region (point-min)(point))
2263           )
2264         (mime-editor/insert-partial-header
2265          header subject id mime-editor/partial-number total separator)
2266         (insert data)
2267         (save-excursion
2268           (message (format "Sending %d/%d..."
2269                            mime-editor/partial-number total))
2270           (call-interactively command)
2271           (message (format "Sending %d/%d... done"
2272                            mime-editor/partial-number total))
2273           )
2274         (setq mime-editor/partial-number
2275               (1+ mime-editor/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-editor/insert-partial-header
2284        header subject id mime-editor/partial-number total separator)
2285       (insert data)
2286       (save-excursion
2287         (message (format "Sending %d/%d..."
2288                          mime-editor/partial-number total))
2289         (message (format "Sending %d/%d... done"
2290                          mime-editor/partial-number total))
2291         )
2292       )))
2293
2294 (defun mime-editor/maybe-split-and-send (&optional cmd)
2295   (interactive)
2296   (run-hooks 'mime-editor/before-send-hook)
2297   (let ((mime-editor/message-max-length
2298          (or (cdr (assq major-mode mime-editor/message-max-lines-alist))
2299              mime-editor/message-default-max-lines))
2300         (lines (count-lines (point-min) (point-max)))
2301         )
2302     (if (and (> lines mime-editor/message-max-length)
2303              mime-editor/split-message)
2304         (mime-editor/split-and-send cmd lines mime-editor/message-max-length)
2305       )))
2306
2307
2308 ;;; @ preview message
2309 ;;;
2310
2311 (defun mime-editor/preview-message ()
2312   "preview editing MIME message. [tm-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-editor/translate-hook)
2337     (mime-editor/translate-buffer)
2338     (goto-char (point-min))
2339     (if (re-search-forward
2340          (concat "^" (regexp-quote separator) "$"))
2341         (replace-match "")
2342       )
2343     (mime/viewer-mode)
2344     ))
2345
2346 (defun mime-editor/quitting-method ()
2347   (let ((temp mime::preview/article-buffer)
2348         buf)
2349     (mime-viewer/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-viewer/quitting-method-alist
2357            'mime/temporary-message-mode
2358            (function mime-editor/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-editor/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-editor/draft-preview ()
2375   (interactive)
2376   (let ((sep (cdr (assq major-mode mime-editor/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/viewer-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-viewer/kill-buffer)
2405     (pop-to-buffer mother)
2406     ))
2407
2408 (set-alist 'mime-viewer/quitting-method-alist
2409            'mh-letter-mode
2410            (function mime-viewer::quitting-method/draft-preview)
2411            )
2412
2413 (set-alist 'mime-viewer/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-equal type "multipart")
2439               (let* ((boundary (assoc-value "boundary" params))
2440                      (boundary-pat
2441                       (concat "\n--" (regexp-quote boundary) "[ \t]*\n"))
2442                      )
2443                 (re-search-forward boundary-pat nil t)
2444                 (let ((bb (match-beginning 0)) eb tag)
2445                   (setq tag (format "\n--<<%s>>-{\n" stype))
2446                   (goto-char bb)
2447                   (insert tag)
2448                   (setq bb (+ bb (length tag)))
2449                   (re-search-forward
2450                    (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2451                    nil t)
2452                   (setq eb (match-beginning 0))
2453                   (replace-match (format "--}-<<%s>>\n" stype))
2454                   (save-restriction
2455                     (narrow-to-region bb eb)
2456                     (goto-char (point-min))
2457                     (while (re-search-forward boundary-pat nil t)
2458                       (let ((beg (match-beginning 0))
2459                             end)
2460                         (delete-region beg (match-end 0))
2461                         (save-excursion
2462                           (if (re-search-forward boundary-pat nil t)
2463                               (setq end (match-beginning 0))
2464                             (setq end (point-max))
2465                             )
2466                           (save-restriction
2467                             (narrow-to-region beg end)
2468                             (mime-editor::edit-again code-conversion)
2469                             (goto-char (point-max))
2470                             ))))
2471                     ))
2472                 (goto-char (point-min))
2473                 (or (= (point-min) 1)
2474                     (delete-region (point-min)
2475                                    (if (search-forward "\n\n" nil t)
2476                                        (match-end 0)
2477                                      (point-min)
2478                                      )))
2479                 ))
2480              (t
2481               (let* (charset
2482                      (pstr
2483                       (let ((bytes (+ 14 (length ctype))))
2484                         (mapconcat (function
2485                                     (lambda (attr)
2486                                       (if (string-equal (car attr) "charset")
2487                                           (progn
2488                                             (setq charset (cdr attr))
2489                                             "")
2490                                         (let* ((str
2491                                                 (concat (car attr)
2492                                                         "=" (cdr attr))
2493                                                 )
2494                                                (bs (length str))
2495                                                )
2496                                           (setq bytes (+ bytes bs 2))
2497                                           (if (< bytes 76)
2498                                               (concat "; " str)
2499                                             (setq bytes (+ bs 1))
2500                                             (concat ";\n " str)
2501                                             )
2502                                           ))))
2503                                    params "")))
2504                      encoding
2505                      encoded)
2506                 (save-excursion
2507                   (if (re-search-forward
2508                        "Content-Transfer-Encoding:" nil t)
2509                       (let ((beg (match-beginning 0))
2510                             (hbeg (match-end 0))
2511                             (end (std11-field-end)))
2512                         (setq encoding
2513                               (eliminate-top-spaces
2514                                (std11-unfold-string
2515                                 (buffer-substring hbeg end))))
2516                         (if (or charset (string-equal type "text"))
2517                             (progn
2518                               (delete-region beg (1+ end))
2519                               (goto-char (point-min))
2520                               (if (search-forward "\n\n" nil t)
2521                                   (progn
2522                                     (mime-decode-region
2523                                      (match-end 0)(point-max) encoding)
2524                                     (setq encoded t
2525                                           encoding nil)
2526                                     )))))))
2527                 (if (or code-conversion encoded)
2528                     (decode-mime-charset-region
2529                      (point-min)(point-max)
2530                      (or charset default-mime-charset))
2531                   )
2532                 (let ((he
2533                        (if (re-search-forward "^$" nil t)
2534                            (match-end 0)
2535                          (point-min)
2536                          )))
2537                   (if (= (point-min) 1)
2538                       (progn
2539                         (goto-char he)
2540                         (insert
2541                          (concat "\n"
2542                                  (mime-create-tag
2543                                   (concat type "/" stype pstr) encoding)))
2544                         )
2545                     (delete-region (point-min) he)
2546                     (insert
2547                      (mime-create-tag
2548                       (concat type "/" stype pstr) encoding))
2549                     ))
2550                 ))))
2551         (if code-conversion
2552             (decode-mime-charset-region (point-min) (point-max)
2553                                         default-mime-charset)
2554           )
2555         ))))
2556
2557 (defun mime/edit-again (&optional code-conversion no-separator no-mode)
2558   (interactive)
2559   (mime-editor::edit-again code-conversion)
2560   (goto-char (point-min))
2561   (save-restriction
2562     (narrow-to-region
2563      (point-min)
2564      (if (re-search-forward
2565           (concat "^\\(" (regexp-quote mail-header-separator) "\\)?$")
2566           nil t)
2567          (match-end 0)
2568        (point-max)
2569        ))
2570     (goto-char (point-min))
2571     (while (re-search-forward
2572             "^\\(Content-.*\\|Mime-Version\\):" nil t)
2573       (delete-region (match-beginning 0) (1+ (std11-field-end)))
2574       ))
2575   (or no-separator
2576       (and (re-search-forward "^$")
2577            (replace-match mail-header-separator)
2578            ))
2579   (or no-mode
2580       (mime/editor-mode)
2581       ))
2582
2583
2584 ;;; @ end
2585 ;;;
2586
2587 (provide 'tm-edit)
2588
2589 (run-hooks 'tm-edit-load-hook)
2590
2591 ;;; tm-edit.el ends here