tm 7.99.
[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.99 $
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.99 1996/12/24 12:08:50 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      "base64"
296      "attachment"       (("filename" . file))
297      )
298     ("\\.tgz$"
299      "application" "octet-stream" (("type" . "tar+gzip"))
300      "base64"
301      "attachment"       (("filename" . file))
302      )
303     ("\\.tar\\.Z$"
304      "application" "octet-stream" (("type" . "tar+compress"))
305      "base64"
306      "attachment"       (("filename" . file))
307      )
308     ("\\.taz$"
309      "application" "octet-stream" (("type" . "tar+compress"))
310      "base64"
311      "attachment"       (("filename" . file))
312      )
313     ("\\.gz$"
314      "application" "octet-stream" (("type" . "gzip"))
315      "base64"
316      "attachment"       (("filename" . file))
317      )
318     ("\\.Z$"
319      "application" "octet-stream" (("type" . "compress"))
320      "base64"
321      "attachment"       (("filename" . file))
322      )
323     ("\\.lzh$"
324      "application" "octet-stream" (("type" . "lha"))
325      "base64"
326      "attachment"       (("filename" . file))
327      )
328     ("\\.zip$"
329      "application" "zip" nil
330      "base64"
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 (or (interactive-p) verbose)
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 (encoding)
1391     (while (string=
1392             (setq encoding
1393                   (completing-read
1394                    "What transfer encoding: "
1395                    mime-file-encoding-method-alist nil t default)
1396                   )
1397             ""))
1398     encoding))
1399
1400 \f
1401 ;;; @ Translate the tagged MIME messages into a MIME compliant message.
1402 ;;;
1403
1404 (defvar mime-editor/translate-buffer-hook
1405   '(mime-editor/pgp-enclose-buffer
1406     mime-editor/translate-header
1407     mime-editor/translate-body))
1408
1409 (defun mime-editor/translate-header ()
1410   "Encode the message header into network representation."
1411   (mime/encode-message-header 'code-conversion)
1412   (run-hooks 'mime-editor/translate-header-hook)
1413   )
1414
1415 (defun mime-editor/translate-buffer ()
1416   "Encode the tagged MIME message in current buffer in MIME compliant message."
1417   (interactive)
1418   (if (catch 'mime-editor/error
1419         (save-excursion
1420           (run-hooks 'mime-editor/translate-buffer-hook)
1421           ))
1422       (progn
1423         (undo)
1424         (error "Translation error!")
1425         )))
1426
1427 (defun mime-editor/find-inmost ()
1428   (goto-char (point-min))
1429   (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1430       (let ((bb (match-beginning 0))
1431             (be (match-end 0))
1432             (type (buffer-substring (match-beginning 1)(match-end 1)))
1433             end-exp eb ee)
1434         (setq end-exp (format "--}-<<%s>>\n" type))
1435         (widen)
1436         (if (re-search-forward end-exp nil t)
1437             (progn
1438               (setq eb (match-beginning 0))
1439               (setq ee (match-end 0))
1440               )
1441           (setq eb (point-max))
1442           (setq ee (point-max))
1443           )
1444         (narrow-to-region be eb)
1445         (goto-char be)
1446         (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1447             (let (ret)
1448               (narrow-to-region (match-beginning 0)(point-max))
1449               (mime-editor/find-inmost)
1450               )
1451           (widen)
1452           (list type bb be eb)
1453           ))))
1454
1455 (defun mime-editor/process-multipart-1 (boundary)
1456   (let ((ret (mime-editor/find-inmost)))
1457     (if ret
1458         (let ((type (car ret))
1459               (bb (nth 1 ret))(be (nth 2 ret))
1460               (eb (nth 3 ret))
1461               )
1462           (narrow-to-region bb eb)
1463           (delete-region bb be)
1464           (setq bb (point-min))
1465           (setq eb (point-max))
1466           (widen)
1467           (goto-char eb)
1468           (if (looking-at mime-editor/multipart-end-regexp)
1469               (let ((beg (match-beginning 0))
1470                     (end (match-end 0))
1471                     )
1472                 (delete-region beg end)
1473                 (or (looking-at mime-editor/beginning-tag-regexp)
1474                     (eobp)
1475                     (insert (concat (mime-make-text-tag) "\n"))
1476                     )))
1477           (cond ((string-equal type "quote")
1478                  (mime-editor/enquote-region bb eb)
1479                  )
1480                 ((string-equal type "signed")
1481                  (cond ((eq mime-editor/signing-type 'pgp-elkins)
1482                         (mime-editor/sign-pgp-elkins bb eb boundary)
1483                         )
1484                        ((eq mime-editor/signing-type 'pgp-kazu)
1485                         (mime-editor/sign-pgp-kazu bb eb boundary)
1486                         ))
1487                  )
1488                 ((string-equal type "encrypted")
1489                  (cond ((eq mime-editor/encrypting-type 'pgp-elkins)
1490                         (mime-editor/encrypt-pgp-elkins bb eb boundary)
1491                         )
1492                        ((eq mime-editor/encrypting-type 'pgp-kazu)
1493                         (mime-editor/encrypt-pgp-kazu bb eb boundary)
1494                         )))
1495                 (t
1496                  (setq boundary
1497                        (nth 2 (mime-editor/translate-region bb eb
1498                                                             boundary t)))
1499                  (goto-char bb)
1500                  (insert
1501                   (format "--[[multipart/%s;
1502  boundary=\"%s\"][7bit]]\n"
1503                           type boundary))
1504                  ))
1505           boundary))))
1506
1507 (defun mime-editor/enquote-region (beg end)
1508   (save-excursion
1509     (save-restriction
1510       (narrow-to-region beg end)
1511       (goto-char beg)
1512       (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1513         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1514           (replace-match (concat "- " (substring tag 1)))
1515           )))))
1516
1517 (defun mime-editor/dequote-region (beg end)
1518   (save-excursion
1519     (save-restriction
1520       (narrow-to-region beg end)
1521       (goto-char beg)
1522       (while (re-search-forward
1523               mime-editor/quoted-single-part-tag-regexp nil t)
1524         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1525           (replace-match (concat "-" (substring tag 2)))
1526           )))))
1527
1528 (defun mime-editor/sign-pgp-elkins (beg end boundary)
1529   (save-excursion
1530     (save-restriction
1531       (narrow-to-region beg end)
1532       (let* ((ret
1533               (mime-editor/translate-region beg end boundary))
1534              (ctype    (car ret))
1535              (encoding (nth 1 ret))
1536              (parts    (nth 3 ret))
1537              (pgp-boundary (concat "pgp-sign-" boundary))
1538              )
1539         (goto-char beg)
1540         (insert (format "Content-Type: %s\n" ctype))
1541         (if encoding
1542             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1543           )
1544         (insert "\n")
1545         (or (funcall mime-editor/pgp-sign-function
1546                      (point-min)(point-max) nil nil pgp-boundary)
1547             (throw 'mime-editor/error 'pgp-error)
1548             )
1549         ))))
1550
1551 (defvar mime-editor/encrypt-recipient-fields-list '("To" "cc"))
1552
1553 (defun mime-editor/make-encrypt-recipient-header ()
1554   (let* ((names mime-editor/encrypt-recipient-fields-list)
1555          (values
1556           (std11-field-bodies (cons "From" names)
1557                               nil mail-header-separator))
1558          (from (prog1
1559                    (car values)
1560                  (setq values (cdr values))))
1561          (header (and (stringp from)
1562                       (if (string-equal from "")
1563                           ""
1564                         (format "From: %s\n" from)
1565                         )))
1566          recipients)
1567     (while (and names values)
1568       (let ((name (car names))
1569             (value (car values))
1570             )
1571         (and (stringp value)
1572              (or (string-equal value "")
1573                  (progn
1574                    (setq header (concat header name ": " value "\n")
1575                          recipients (if recipients
1576                                         (concat recipients " ," value)
1577                                       value))
1578                    ))))
1579       (setq names (cdr names)
1580             values (cdr values))
1581       )
1582     (vector from recipients header)
1583     ))
1584
1585 (defun mime-editor/encrypt-pgp-elkins (beg end boundary)
1586   (save-excursion
1587     (save-restriction
1588       (let (from recipients header)
1589         (let ((ret (mime-editor/make-encrypt-recipient-header)))
1590           (setq from (aref ret 0)
1591                 recipients (aref ret 1)
1592                 header (aref ret 2))
1593           )
1594         (narrow-to-region beg end)
1595         (let* ((ret
1596                 (mime-editor/translate-region beg end boundary))
1597                (ctype    (car ret))
1598                (encoding (nth 1 ret))
1599                (parts    (nth 3 ret))
1600                (pgp-boundary (concat "pgp-" boundary))
1601                )
1602           (goto-char beg)
1603           (insert header)
1604           (insert (format "Content-Type: %s\n" ctype))
1605           (if encoding
1606               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1607             )
1608           (insert "\n")
1609           (or (funcall mime-editor/pgp-encrypt-function
1610                        recipients (point-min) (point-max) from)
1611               (throw 'mime-editor/error 'pgp-error)
1612               )
1613           (goto-char beg)
1614           (insert (format "--[[multipart/encrypted;
1615  boundary=\"%s\";
1616  protocol=\"application/pgp-encrypted\"][7bit]]
1617 --%s
1618 Content-Type: application/pgp-encrypted
1619
1620 --%s
1621 Content-Type: application/octet-stream
1622 Content-Transfer-Encoding: 7bit
1623
1624 " pgp-boundary pgp-boundary pgp-boundary))
1625           (goto-char (point-max))
1626           (insert (format "\n--%s--\n" pgp-boundary))
1627           )))))
1628
1629 (defun mime-editor/sign-pgp-kazu (beg end boundary)
1630   (save-excursion
1631     (save-restriction
1632       (narrow-to-region beg end)
1633       (let* ((ret
1634               (mime-editor/translate-region beg end boundary))
1635              (ctype    (car ret))
1636              (encoding (nth 1 ret))
1637              (parts    (nth 3 ret))
1638              )
1639         (goto-char beg)
1640         (insert (format "Content-Type: %s\n" ctype))
1641         (if encoding
1642             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1643           )
1644         (insert "\n")
1645         (or (as-binary-process
1646              (funcall mime-editor/traditional-pgp-sign-function
1647                       beg (point-max)))
1648             (throw 'mime-editor/error 'pgp-error)
1649             )
1650         (goto-char beg)
1651         (insert
1652          "--[[application/pgp; format=mime][7bit]]\n")
1653         ))
1654     ))
1655
1656 (defun mime-editor/encrypt-pgp-kazu (beg end boundary)
1657   (save-excursion
1658     (let (from recipients header)
1659       (let ((ret (mime-editor/make-encrypt-recipient-header)))
1660         (setq from (aref ret 0)
1661               recipients (aref ret 1)
1662               header (aref ret 2))
1663         )
1664       (save-restriction
1665         (narrow-to-region beg end)
1666         (let* ((ret
1667                 (mime-editor/translate-region beg end boundary))
1668                (ctype    (car ret))
1669                (encoding (nth 1 ret))
1670                (parts    (nth 3 ret))
1671                )
1672           (goto-char beg)
1673           (insert header)
1674           (insert (format "Content-Type: %s\n" ctype))
1675           (if encoding
1676               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1677             )
1678           (insert "\n")
1679           (or (as-binary-process
1680                (funcall mime-editor/pgp-encrypt-function
1681                         recipients beg (point-max) nil 'maybe)
1682                )
1683               (throw 'mime-editor/error 'pgp-error)
1684               )
1685           (goto-char beg)
1686           (insert
1687            "--[[application/pgp; format=mime][7bit]]\n")
1688           ))
1689       )))
1690
1691 (defun mime-editor/translate-body ()
1692   "Encode the tagged MIME body in current buffer in MIME compliant message."
1693   (interactive)
1694   (save-excursion
1695     (let ((boundary
1696            (concat mime-multipart-boundary "_"
1697                    (replace-space-with-underline (current-time-string))
1698                    ))
1699           (i 1)
1700           ret)
1701       (while (mime-editor/process-multipart-1
1702               (format "%s-%d" boundary i))
1703         (setq i (1+ i))
1704         )
1705       (save-restriction
1706         ;; We are interested in message body.
1707         (let* ((beg
1708                 (progn
1709                   (goto-char (point-min))
1710                   (re-search-forward
1711                    (concat "\n" (regexp-quote mail-header-separator)
1712                            (if mime-ignore-preceding-spaces
1713                                "[ \t\n]*\n" "\n")) nil 'move)
1714                   (point)))
1715                (end
1716                 (progn
1717                   (goto-char (point-max))
1718                   (and mime-ignore-trailing-spaces
1719                        (re-search-backward "[^ \t\n]\n" beg t)
1720                        (forward-char 1))
1721                   (point))))
1722           (setq ret (mime-editor/translate-region
1723                      beg end
1724                      (format "%s-%d" boundary i)))
1725           ))
1726       (mime-editor/dequote-region (point-min)(point-max))
1727       (let ((contype (car ret))         ;Content-Type
1728             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1729             )
1730         ;; Make primary MIME headers.
1731         (or (mail-position-on-field "Mime-Version")
1732             (insert mime-editor/mime-version-value))
1733         ;; Remove old Content-Type and other fields.
1734         (save-restriction
1735           (goto-char (point-min))
1736           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1737           (narrow-to-region (point-min) (point))
1738           (goto-char (point-min))
1739           (mime-delete-field "Content-Type")
1740           (mime-delete-field "Content-Transfer-Encoding"))
1741         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1742         (mail-position-on-field "Content-Type")
1743         (insert contype)
1744         (if encoding
1745             (progn
1746               (mail-position-on-field "Content-Transfer-Encoding")
1747               (insert encoding)))
1748         ))))
1749
1750 (defun mime-editor/translate-single-part-tag (&optional prefix)
1751   (if (re-search-forward mime-editor/single-part-tag-regexp nil t)
1752       (let* ((beg (match-beginning 0))
1753              (end (match-end 0))
1754              (tag (buffer-substring beg end))
1755              )
1756         (delete-region beg end)
1757         (setq contype (mime-editor/get-contype tag))
1758         (setq encoding (mime-editor/get-encoding tag))
1759         (insert (concat prefix "--" boundary "\n"))
1760         (save-restriction
1761           (narrow-to-region (point)(point))
1762           (insert "Content-Type: " contype "\n")
1763           (if encoding
1764               (insert "Content-Transfer-Encoding: " encoding "\n"))
1765           (mime/encode-message-header)
1766           )
1767         t)))
1768
1769 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1770   (if (null boundary)
1771       (setq boundary
1772             (concat mime-multipart-boundary "_"
1773                     (replace-space-with-underline (current-time-string))))
1774     )
1775   (save-excursion
1776     (save-restriction
1777       (narrow-to-region beg end)
1778       (let ((tag nil)                   ;MIME tag
1779             (contype nil)               ;Content-Type
1780             (encoding nil)              ;Content-Transfer-Encoding
1781             (nparts 0))                 ;Number of body parts
1782         ;; Normalize the body part by inserting appropriate message
1783         ;; tags for every message contents.
1784         (mime-editor/normalize-body)
1785         ;; Counting the number of Content-Type.
1786         (goto-char (point-min))
1787         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1788           (setq nparts (1+ nparts)))
1789         ;; Begin translation.
1790         (cond
1791          ((and (<= nparts 1)(not multipart))
1792           ;; It's a singular message.
1793           (goto-char (point-min))
1794           (while (re-search-forward
1795                   mime-editor/single-part-tag-regexp nil t)
1796             (setq tag
1797                   (buffer-substring (match-beginning 0) (match-end 0)))
1798             (delete-region (match-beginning 0) (1+ (match-end 0)))
1799             (setq contype (mime-editor/get-contype tag))
1800             (setq encoding (mime-editor/get-encoding tag))
1801             ))
1802          (t
1803           ;; It's a multipart message.
1804           (goto-char (point-min))
1805           (and (mime-editor/translate-single-part-tag)
1806                (while (mime-editor/translate-single-part-tag "\n"))
1807                )
1808           ;; Define Content-Type as "multipart/mixed".
1809           (setq contype
1810                 (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1811           ;; Content-Transfer-Encoding must be "7bit".
1812           ;; The following encoding can be `nil', but is
1813           ;; specified as is since there is no way that a user
1814           ;; specifies it.
1815           (setq encoding "7bit")
1816           ;; Insert the trailer.
1817           (goto-char (point-max))
1818           (insert "\n--" boundary "--\n")
1819           ))
1820         (list contype encoding boundary nparts)
1821         ))))
1822
1823 (defun mime-editor/normalize-body ()
1824   "Normalize the body part by inserting appropriate message tags."
1825   ;; Insert the first MIME tags if necessary.
1826   (goto-char (point-min))
1827   (if (not (looking-at mime-editor/single-part-tag-regexp))
1828       (insert (mime-make-text-tag) "\n"))
1829   ;; Check each tag, and add new tag or correct it if necessary.
1830   (goto-char (point-min))
1831   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1832     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1833            (contype (mime-editor/get-contype tag))
1834            (charset (mime-get-parameter contype "charset"))
1835            (encoding (mime-editor/get-encoding tag)))
1836       ;; Remove extra whitespaces after the tag.
1837       (if (looking-at "[ \t]+$")
1838           (delete-region (match-beginning 0) (match-end 0)))
1839       (let ((beg (point))
1840             (end (mime-editor/content-end))
1841             )
1842         (if (= end (point-max))
1843             nil
1844           (goto-char end)
1845           (or (looking-at mime-editor/beginning-tag-regexp)
1846               (eobp)
1847               (insert (mime-make-text-tag) "\n")
1848               ))
1849         (visible-region beg end)
1850         (goto-char beg)
1851         )
1852       (cond
1853        ((mime-test-content-type contype "message")
1854         ;; Content-type "message" should be sent as is.
1855         (forward-line 1)
1856         )
1857        ((mime-test-content-type contype "text")
1858         ;; Define charset for text if necessary.
1859         (setq charset (if charset
1860                           (intern (downcase charset))
1861                         (mime-editor/choose-charset)))
1862         (mime-editor/define-charset charset)
1863         (cond ((string-equal contype "text/x-rot13-47")
1864                (save-excursion
1865                  (forward-line)
1866                  (set-mark (point))
1867                  (goto-char (mime-editor/content-end))
1868                  (tm:caesar-region)
1869                  ))
1870               ((string-equal contype "text/enriched")
1871                (save-excursion
1872                  (let ((beg (progn
1873                               (forward-line)
1874                               (point)))
1875                        (end (mime-editor/content-end))
1876                        )
1877                    ;; Patch for hard newlines
1878                    ;; (save-excursion
1879                    ;;   (goto-char beg)
1880                    ;;   (while (search-forward "\n" end t)
1881                    ;;     (put-text-property (match-beginning 0)
1882                    ;;                        (point)
1883                    ;;                        'hard t)))
1884                    ;; End patch for hard newlines
1885                    (enriched-encode beg end)
1886                    (goto-char beg)
1887                    (if (search-forward "\n\n")
1888                        (delete-region beg (match-end 0))
1889                      )
1890                    ))))
1891         ;; Point is now on current tag.
1892         ;; Define encoding and encode text if necessary.
1893         (or encoding    ;Encoding is not specified.
1894             (let* ((encoding
1895                     (cdr
1896                      (assq charset
1897                            mime-editor/charset-default-encoding-alist)
1898                      ))
1899                    (beg (mime-editor/content-beginning))
1900                    )
1901               (encode-mime-charset-region beg (mime-editor/content-end)
1902                                           charset)
1903               (mime-encode-region beg (mime-editor/content-end) encoding)
1904               (mime-editor/define-encoding encoding)
1905               ))
1906         (goto-char (mime-editor/content-end))
1907         )
1908        ((null encoding)         ;Encoding is not specified.
1909         ;; Application, image, audio, video, and any other
1910         ;; unknown content-type without encoding should be
1911         ;; encoded.
1912         (let* ((encoding "base64")      ;Encode in BASE64 by default.
1913                (beg (mime-editor/content-beginning))
1914                (end (mime-editor/content-end))
1915                (body (buffer-substring beg end))
1916                )
1917           (mime-encode-region beg end encoding)
1918           (mime-editor/define-encoding encoding))
1919         (forward-line 1)
1920         ))
1921       )))
1922
1923 (defun mime-delete-field (field)
1924   "Delete header FIELD."
1925   (let ((regexp (format "^%s:[ \t]*" field)))
1926     (goto-char (point-min))
1927     (while (re-search-forward regexp nil t)
1928       (delete-region (match-beginning 0)
1929                      (progn (forward-line 1) (point)))
1930       )))
1931
1932 \f
1933 ;;;
1934 ;;; Platform dependent functions
1935 ;;;
1936
1937 ;; Sun implementations
1938
1939 (defun mime-editor/voice-recorder-for-sun (encoding)
1940   "Record voice in a buffer using Sun audio device,
1941 and insert data encoded as ENCODING. [tm-edit.el]"
1942   (message "Start the recording on %s.  Type C-g to finish the recording..."
1943            (system-name))
1944   (mime-insert-encoded-file "/dev/audio" encoding)
1945   )
1946
1947 \f
1948 ;;; @ Other useful commands.
1949 ;;;
1950
1951 ;; Message forwarding commands as content-type "message/rfc822".
1952
1953 (defun mime-editor/insert-message (&optional message)
1954   (interactive)
1955   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
1956     (if (and inserter (fboundp inserter))
1957         (progn
1958           (mime-editor/insert-tag "message" "rfc822")
1959           (funcall inserter message)
1960           )
1961       (message "Sorry, I don't have message inserter for your MUA.")
1962       )))
1963
1964 (defun mime-editor/insert-mail (&optional message)
1965   (interactive)
1966   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
1967     (if (and inserter (fboundp inserter))
1968         (progn
1969           (mime-editor/insert-tag "message" "rfc822")
1970           (funcall inserter message)
1971           )
1972       (message "Sorry, I don't have mail inserter for your MUA.")
1973       )))
1974
1975 (defun mime-editor/inserted-message-filter ()
1976   (save-excursion
1977     (save-restriction
1978       (let ((header-start (point))
1979             (case-fold-search t)
1980             beg end)
1981         ;; for Emacs 18
1982         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
1983         (if (re-search-forward "^$" (mark t))
1984             (narrow-to-region header-start (match-beginning 0))
1985           )
1986         (goto-char header-start)
1987         (while (and (re-search-forward
1988                      mime-editor/yank-ignored-field-regexp nil t)
1989                     (setq beg (match-beginning 0))
1990                     (setq end (1+ (std11-field-end)))
1991                     )
1992           (delete-region beg end)
1993           )
1994         ))))
1995
1996
1997 ;;; @ multipart enclosure
1998 ;;;
1999
2000 (defun mime-editor/enclose-region (type beg end)
2001   (save-excursion
2002     (goto-char beg)
2003     (let ((current (point)))
2004       (save-restriction
2005         (narrow-to-region beg end)
2006         (insert (format "--<<%s>>-{\n" type))
2007         (goto-char (point-max))
2008         (insert (format "--}-<<%s>>\n" type))
2009         (goto-char (point-max))
2010         )
2011       (or (looking-at mime-editor/beginning-tag-regexp)
2012           (eobp)
2013           (insert (mime-make-text-tag) "\n")
2014           )
2015       )))
2016
2017 (defun mime-editor/enclose-quote-region (beg end)
2018   (interactive "*r")
2019   (mime-editor/enclose-region "quote" beg end)
2020   )
2021
2022 (defun mime-editor/enclose-mixed-region (beg end)
2023   (interactive "*r")
2024   (mime-editor/enclose-region "mixed" beg end)
2025   )
2026
2027 (defun mime-editor/enclose-parallel-region (beg end)
2028   (interactive "*r")
2029   (mime-editor/enclose-region "parallel" beg end)
2030   )
2031
2032 (defun mime-editor/enclose-digest-region (beg end)
2033   (interactive "*r")
2034   (mime-editor/enclose-region "digest" beg end)
2035   )
2036
2037 (defun mime-editor/enclose-alternative-region (beg end)
2038   (interactive "*r")
2039   (mime-editor/enclose-region "alternative" beg end)
2040   )
2041
2042 (defun mime-editor/enclose-signed-region (beg end)
2043   (interactive "*r")
2044   (if mime-editor/signing-type
2045       (mime-editor/enclose-region "signed" beg end)
2046     (message "Please specify signing type.")
2047     ))
2048
2049 (defun mime-editor/enclose-encrypted-region (beg end)
2050   (interactive "*r")
2051   (if mime-editor/signing-type
2052       (mime-editor/enclose-region "encrypted" beg end)
2053     (message "Please specify encrypting type.")
2054     ))
2055
2056 (defun mime-editor/insert-key (&optional arg)
2057   "Insert a pgp public key."
2058   (interactive "P")
2059   (mime-editor/insert-tag "application" "pgp-keys")
2060   (mime-editor/define-encoding "7bit")
2061   (funcall mime-editor/pgp-insert-public-key-function)
2062   )
2063
2064
2065 ;;; @ flag setting
2066 ;;;
2067
2068 (defun mime-editor/set-split (arg)
2069   (interactive
2070    (list
2071     (y-or-n-p "Do you want to enable split?")
2072     ))
2073   (setq mime-editor/split-message arg)
2074   (if arg
2075       (message "This message is enabled to split.")
2076     (message "This message is not enabled to split.")
2077     ))
2078
2079 (defun mime-editor/toggle-transfer-level (&optional transfer-level)
2080   "Toggle transfer-level is 7bit or 8bit through.
2081
2082 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2083   (interactive)
2084   (if (numberp transfer-level)
2085       (setq mime-editor/transfer-level transfer-level)
2086     (if (< mime-editor/transfer-level 8)
2087         (setq mime-editor/transfer-level 8)
2088       (setq mime-editor/transfer-level 7)
2089       ))
2090   (setq mime-editor/charset-default-encoding-alist
2091         (mime-editor/make-charset-default-encoding-alist
2092          mime-editor/transfer-level))
2093   (message (format "Current transfer-level is %d bit"
2094                    mime-editor/transfer-level))
2095   (setq mime-editor/transfer-level-string
2096         (mime/encoding-name mime-editor/transfer-level 'not-omit))
2097   (force-mode-line-update)
2098   )
2099
2100 (defun mime-editor/set-transfer-level-7bit ()
2101   (interactive)
2102   (mime-editor/toggle-transfer-level 7)
2103   )
2104
2105 (defun mime-editor/set-transfer-level-8bit ()
2106   (interactive)
2107   (mime-editor/toggle-transfer-level 8)
2108   )
2109
2110
2111 ;;; @ pgp
2112 ;;;
2113
2114 (defun mime-editor/set-sign (arg)
2115   (interactive
2116    (list
2117     (y-or-n-p "Do you want to sign?")
2118     ))
2119   (if arg
2120       (if mime-editor/signing-type
2121           (progn
2122             (setq mime-editor/pgp-processing 'sign)
2123             (message "This message will be signed.")
2124             )
2125         (message "Please specify signing type.")
2126         )
2127     (if (eq mime-editor/pgp-processing 'sign)
2128         (setq mime-editor/pgp-processing nil)
2129       )
2130     (message "This message will not be signed.")
2131     ))
2132
2133 (defun mime-editor/set-encrypt (arg)
2134   (interactive
2135    (list
2136     (y-or-n-p "Do you want to encrypt?")
2137     ))
2138   (if arg
2139       (if mime-editor/encrypting-type
2140           (progn
2141             (setq mime-editor/pgp-processing 'encrypt)
2142             (message "This message will be encrypt.")
2143             )
2144         (message "Please specify encrypting type.")
2145         )
2146     (if (eq mime-editor/pgp-processing 'encrypt)
2147         (setq mime-editor/pgp-processing nil)
2148       )
2149     (message "This message will not be encrypt.")
2150     ))
2151
2152 (defvar mime-editor/pgp-processing nil)
2153 (make-variable-buffer-local 'mime-editor/pgp-processing)
2154
2155 (defun mime-editor/pgp-enclose-buffer ()
2156   (let ((beg (save-excursion
2157                (goto-char (point-min))
2158                (if (search-forward (concat "\n" mail-header-separator "\n"))
2159                    (match-end 0)
2160                  )))
2161         (end (point-max))
2162         )
2163     (if beg
2164         (cond ((eq mime-editor/pgp-processing 'sign)
2165                (mime-editor/enclose-signed-region beg end)
2166                )
2167               ((eq mime-editor/pgp-processing 'encrypt)
2168                (mime-editor/enclose-encrypted-region beg end)
2169                ))
2170       )))
2171
2172
2173 ;;; @ split
2174 ;;;
2175
2176 (defun mime-editor/insert-partial-header
2177   (fields subject id number total separator)
2178   (insert fields)
2179   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2180   (insert (format "Mime-Version: 1.0 (split by %s)\n"
2181                   mime-editor/version-name))
2182   (insert (format "\
2183 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2184                   id number total separator))
2185   )
2186
2187 (defun mime-editor/split-and-send
2188   (&optional cmd lines mime-editor/message-max-length)
2189   (interactive)
2190   (or lines
2191       (setq lines
2192             (count-lines (point-min) (point-max)))
2193       )
2194   (or mime-editor/message-max-length
2195       (setq mime-editor/message-max-length
2196             (or (cdr (assq major-mode mime-editor/message-max-lines-alist))
2197                 mime-editor/message-default-max-lines))
2198       )
2199   (let* ((mime-editor/draft-file-name 
2200           (or (buffer-file-name)
2201               (make-temp-name
2202                (expand-file-name "tm-draft" mime/tmp-dir))))
2203          (separator mail-header-separator)
2204          (id (concat "\""
2205                      (replace-space-with-underline (current-time-string))
2206                      "@" (system-name) "\"")))
2207     (run-hooks 'mime-editor/before-split-hook)
2208     (let ((the-buf (current-buffer))
2209           (copy-buf (get-buffer-create " *Original Message*"))
2210           (header (std11-header-string-except
2211                    mime-editor/split-ignored-field-regexp separator))
2212           (subject (mail-fetch-field "subject"))
2213           (total (+ (/ lines mime-editor/message-max-length)
2214                     (if (> (mod lines mime-editor/message-max-length) 0)
2215                         1)))
2216           (command
2217            (or cmd
2218                (cdr
2219                 (assq major-mode
2220                       mime-editor/split-message-sender-alist))
2221                (function
2222                 (lambda ()
2223                   (interactive)
2224                   (error "Split sender is not specified for `%s'." major-mode)
2225                   ))
2226                ))
2227           (mime-editor/partial-number 1)
2228           data)
2229       (save-excursion
2230         (set-buffer copy-buf)
2231         (erase-buffer)
2232         (insert-buffer the-buf)
2233         (save-restriction
2234           (if (re-search-forward
2235                (concat "^" (regexp-quote separator) "$") nil t)
2236               (let ((he (match-beginning 0)))
2237                 (replace-match "")
2238                 (narrow-to-region (point-min) he)
2239                 ))
2240           (goto-char (point-min))
2241           (while (re-search-forward mime-editor/split-blind-field-regexp nil t)
2242             (delete-region (match-beginning 0)
2243                            (1+ (std11-field-end)))
2244             )))
2245       (while (< mime-editor/partial-number total)
2246         (erase-buffer)
2247         (save-excursion
2248           (set-buffer copy-buf)
2249           (setq data (buffer-substring
2250                       (point-min)
2251                       (progn
2252                         (goto-line mime-editor/message-max-length)
2253                         (point))
2254                       ))
2255           (delete-region (point-min)(point))
2256           )
2257         (mime-editor/insert-partial-header
2258          header subject id mime-editor/partial-number total separator)
2259         (insert data)
2260         (save-excursion
2261           (message (format "Sending %d/%d..."
2262                            mime-editor/partial-number total))
2263           (call-interactively command)
2264           (message (format "Sending %d/%d... done"
2265                            mime-editor/partial-number total))
2266           )
2267         (setq mime-editor/partial-number
2268               (1+ mime-editor/partial-number))
2269         )
2270       (erase-buffer)
2271       (save-excursion
2272         (set-buffer copy-buf)
2273         (setq data (buffer-string))
2274         (erase-buffer)
2275         )
2276       (mime-editor/insert-partial-header
2277        header subject id mime-editor/partial-number total separator)
2278       (insert data)
2279       (save-excursion
2280         (message (format "Sending %d/%d..."
2281                          mime-editor/partial-number total))
2282         (message (format "Sending %d/%d... done"
2283                          mime-editor/partial-number total))
2284         )
2285       )))
2286
2287 (defun mime-editor/maybe-split-and-send (&optional cmd)
2288   (interactive)
2289   (run-hooks 'mime-editor/before-send-hook)
2290   (let ((mime-editor/message-max-length
2291          (or (cdr (assq major-mode mime-editor/message-max-lines-alist))
2292              mime-editor/message-default-max-lines))
2293         (lines (count-lines (point-min) (point-max)))
2294         )
2295     (if (and (> lines mime-editor/message-max-length)
2296              mime-editor/split-message)
2297         (mime-editor/split-and-send cmd lines mime-editor/message-max-length)
2298       )))
2299
2300
2301 ;;; @ preview message
2302 ;;;
2303
2304 (defun mime-editor/preview-message ()
2305   "preview editing MIME message. [tm-edit.el]"
2306   (interactive)
2307   (let* ((str (buffer-string))
2308          (separator mail-header-separator)
2309          (the-buf (current-buffer))
2310          (buf-name (buffer-name))
2311          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2312          (buf (get-buffer temp-buf-name))
2313          )
2314     (if buf
2315         (progn
2316           (switch-to-buffer buf)
2317           (erase-buffer)
2318           )
2319       (setq buf (get-buffer-create temp-buf-name))
2320       (switch-to-buffer buf)
2321       )
2322     (insert str)
2323     (setq major-mode 'mime/temporary-message-mode)
2324     (make-local-variable 'mail-header-separator)
2325     (setq mail-header-separator separator)
2326     (make-local-variable 'mime/editing-buffer)
2327     (setq mime/editing-buffer the-buf)
2328     
2329     (run-hooks 'mime-editor/translate-hook)
2330     (mime-editor/translate-buffer)
2331     (goto-char (point-min))
2332     (if (re-search-forward
2333          (concat "^" (regexp-quote separator) "$"))
2334         (replace-match "")
2335       )
2336     (mime/viewer-mode)
2337     ))
2338
2339 (defun mime-editor/quitting-method ()
2340   (let ((temp mime::preview/article-buffer)
2341         buf)
2342     (mime-viewer/kill-buffer)
2343     (set-buffer temp)
2344     (setq buf mime/editing-buffer)
2345     (kill-buffer temp)
2346     (switch-to-buffer buf)
2347     ))
2348
2349 (set-alist 'mime-viewer/quitting-method-alist
2350            'mime/temporary-message-mode
2351            (function mime-editor/quitting-method)
2352            )
2353
2354
2355 ;;; @ draft preview
2356 ;;; 
2357 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2358 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2359
2360 (defvar mime-editor/draft-header-separator-alist
2361   '((news-reply-mode . mail-header-separator)
2362     (mh-letter-mode . mail-header-separator)
2363     ))
2364
2365 (defvar mime::article/draft-header-separator nil)
2366
2367 (defun mime-editor/draft-preview ()
2368   (interactive)
2369   (let ((sep (cdr (assq major-mode mime-editor/draft-header-separator-alist))))
2370     (or (stringp sep) (setq sep (eval sep)))
2371     (make-variable-buffer-local 'mime::article/draft-header-separator)
2372     (goto-char (point-min))
2373     (re-search-forward
2374      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2375     (setq mime::article/draft-header-separator
2376           (buffer-substring (match-beginning 0) (match-end 0)))
2377     (replace-match "")
2378     (mime/viewer-mode (current-buffer))
2379     (pop-to-buffer (current-buffer))
2380     ))
2381
2382 (defun mime-viewer::quitting-method/draft-preview ()
2383   (let ((mother mime::preview/mother-buffer))
2384     (save-excursion
2385       (switch-to-buffer mother)
2386       (goto-char (point-min))
2387       (if (and
2388            (re-search-forward
2389             (concat "^\\("
2390                     (regexp-quote mime::article/draft-header-separator)
2391                     "\\)?$") nil t)
2392            (bolp))
2393           (progn
2394             (insert mime::article/draft-header-separator)
2395             (set-buffer-modified-p (buffer-modified-p))
2396             )))
2397     (mime-viewer/kill-buffer)
2398     (pop-to-buffer mother)
2399     ))
2400
2401 (set-alist 'mime-viewer/quitting-method-alist
2402            'mh-letter-mode
2403            (function mime-viewer::quitting-method/draft-preview)
2404            )
2405
2406 (set-alist 'mime-viewer/quitting-method-alist
2407            'news-reply-mode
2408            (function mime-viewer::quitting-method/draft-preview)
2409            )
2410
2411
2412 ;;; @ edit again
2413 ;;;
2414
2415 (defun mime-editor::edit-again (code-conversion)
2416   (save-excursion
2417     (goto-char (point-min))
2418     (let ((ctl (mime/Content-Type)))
2419       (if ctl
2420           (let ((ctype (car ctl))
2421                 (params (cdr ctl))
2422                 type stype)
2423             (if (string-match "/" ctype)
2424                 (progn
2425                   (setq type (substring ctype 0 (match-beginning 0)))
2426                   (setq stype (substring ctype (match-end 0)))
2427                   )
2428               (setq type ctype)
2429               )
2430             (cond
2431              ((string-equal type "multipart")
2432               (let* ((boundary (assoc-value "boundary" params))
2433                      (boundary-pat
2434                       (concat "\n--" (regexp-quote boundary) "[ \t]*\n"))
2435                      )
2436                 (re-search-forward boundary-pat nil t)
2437                 (let ((bb (match-beginning 0)) eb tag)
2438                   (setq tag (format "\n--<<%s>>-{\n" stype))
2439                   (goto-char bb)
2440                   (insert tag)
2441                   (setq bb (+ bb (length tag)))
2442                   (re-search-forward
2443                    (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2444                    nil t)
2445                   (setq eb (match-beginning 0))
2446                   (replace-match (format "--}-<<%s>>\n" stype))
2447                   (save-restriction
2448                     (narrow-to-region bb eb)
2449                     (goto-char (point-min))
2450                     (while (re-search-forward boundary-pat nil t)
2451                       (let ((beg (match-beginning 0))
2452                             end)
2453                         (delete-region beg (match-end 0))
2454                         (save-excursion
2455                           (if (re-search-forward boundary-pat nil t)
2456                               (setq end (match-beginning 0))
2457                             (setq end (point-max))
2458                             )
2459                           (save-restriction
2460                             (narrow-to-region beg end)
2461                             (mime-editor::edit-again code-conversion)
2462                             (goto-char (point-max))
2463                             ))))
2464                     ))
2465                 (goto-char (point-min))
2466                 (or (= (point-min) 1)
2467                     (delete-region (point-min)
2468                                    (if (search-forward "\n\n" nil t)
2469                                        (match-end 0)
2470                                      (point-min)
2471                                      )))
2472                 ))
2473              (t
2474               (let* (charset
2475                      (pstr
2476                       (let ((bytes (+ 14 (length ctype))))
2477                         (mapconcat (function
2478                                     (lambda (attr)
2479                                       (if (string-equal (car attr) "charset")
2480                                           (progn
2481                                             (setq charset (cdr attr))
2482                                             "")
2483                                         (let* ((str
2484                                                 (concat (car attr)
2485                                                         "=" (cdr attr))
2486                                                 )
2487                                                (bs (length str))
2488                                                )
2489                                           (setq bytes (+ bytes bs 2))
2490                                           (if (< bytes 76)
2491                                               (concat "; " str)
2492                                             (setq bytes (+ bs 1))
2493                                             (concat ";\n " str)
2494                                             )
2495                                           ))))
2496                                    params "")))
2497                      encoding
2498                      encoded)
2499                 (save-excursion
2500                   (if (re-search-forward
2501                        "Content-Transfer-Encoding:" nil t)
2502                       (let ((beg (match-beginning 0))
2503                             (hbeg (match-end 0))
2504                             (end (std11-field-end)))
2505                         (setq encoding
2506                               (eliminate-top-spaces
2507                                (std11-unfold-string
2508                                 (buffer-substring hbeg end))))
2509                         (if (or charset (string-equal type "text"))
2510                             (progn
2511                               (delete-region beg (1+ end))
2512                               (goto-char (point-min))
2513                               (if (search-forward "\n\n" nil t)
2514                                   (progn
2515                                     (mime-decode-region
2516                                      (match-end 0)(point-max) encoding)
2517                                     (setq encoded t
2518                                           encoding nil)
2519                                     )))))))
2520                 (if (or code-conversion encoded)
2521                     (decode-mime-charset-region
2522                      (point-min)(point-max)
2523                      (or charset default-mime-charset))
2524                   )
2525                 (let ((he
2526                        (if (re-search-forward "^$" nil t)
2527                            (match-end 0)
2528                          (point-min)
2529                          )))
2530                   (if (= (point-min) 1)
2531                       (progn
2532                         (goto-char he)
2533                         (insert
2534                          (concat "\n"
2535                                  (mime-create-tag
2536                                   (concat type "/" stype pstr) encoding)))
2537                         )
2538                     (delete-region (point-min) he)
2539                     (insert
2540                      (mime-create-tag
2541                       (concat type "/" stype pstr) encoding))
2542                     ))
2543                 ))))
2544         (if code-conversion
2545             (decode-mime-charset-region (point-min) (point-max)
2546                                         default-mime-charset)
2547           )
2548         ))))
2549
2550 (defun mime/edit-again (&optional code-conversion no-separator no-mode)
2551   (interactive)
2552   (mime-editor::edit-again code-conversion)
2553   (goto-char (point-min))
2554   (save-restriction
2555     (narrow-to-region
2556      (point-min)
2557      (if (re-search-forward
2558           (concat "^\\(" (regexp-quote mail-header-separator) "\\)?$")
2559           nil t)
2560          (match-end 0)
2561        (point-max)
2562        ))
2563     (goto-char (point-min))
2564     (while (re-search-forward
2565             "^\\(Content-.*\\|Mime-Version\\):" nil t)
2566       (delete-region (match-beginning 0) (1+ (std11-field-end)))
2567       ))
2568   (or no-separator
2569       (and (re-search-forward "^$")
2570            (replace-match mail-header-separator)
2571            ))
2572   (or no-mode
2573       (mime/editor-mode)
2574       ))
2575
2576
2577 ;;; @ end
2578 ;;;
2579
2580 (provide 'tm-edit)
2581
2582 (run-hooks 'tm-edit-load-hook)
2583
2584 ;;; tm-edit.el ends here