This commit was generated by cvs2svn to compensate for changes in r509,
[elisp/tm.git] / tm-edit.el
1 ;;; tm-edit.el --- Simple MIME Composer for GNU Emacs
2
3 ;; Copyright (C) 1993,1994,1995,1996,1997 Free Software Foundation, Inc.
4
5 ;; Author: UMEDA Masanobu <umerin@mse.kyutech.ac.jp>
6 ;;         MORIOKA Tomohiko <morioka@jaist.ac.jp>
7 ;; Maintainer: MORIOKA Tomohiko <morioka@jaist.ac.jp>
8 ;; Created: 1994/08/21 renamed from mime.el
9 ;; Version: $Revision: 7.102 $
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].  Mule is required for reading the such
45 ;; 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.102 1997/01/30 11:31:36 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
701 \[make single part\]
702 \\[mime-editor/insert-text]     insert a text message.
703 \\[mime-editor/insert-file]     insert a (binary) file.
704 \\[mime-editor/insert-external] insert a reference to external body.
705 \\[mime-editor/insert-voice]    insert a voice message.
706 \\[mime-editor/insert-message]  insert a mail or news message.
707 \\[mime-editor/insert-mail]     insert a mail message.
708 \\[mime-editor/insert-signature]        insert a signature file at end.
709 \\[mime-editor/insert-key]      insert PGP public key.
710 \\[mime-editor/insert-tag]      insert a new MIME tag.
711
712 \[make enclosure (maybe multipart)\]
713 \\[mime-editor/enclose-alternative-region]      enclose as multipart/alternative.
714 \\[mime-editor/enclose-parallel-region] enclose as multipart/parallel.
715 \\[mime-editor/enclose-mixed-region]    enclose as multipart/mixed.
716 \\[mime-editor/enclose-digest-region]   enclose as multipart/digest.
717 \\[mime-editor/enclose-signed-region]   enclose as PGP signed.
718 \\[mime-editor/enclose-encrypted-region]        enclose as PGP encrypted.
719 \\[mime-editor/enclose-quote-region]    enclose as verbose mode (to avoid to expand tags)
720
721 \[other commands\]
722 \\[mime-editor/set-transfer-level-7bit] set transfer-level as 7.
723 \\[mime-editor/set-transfer-level-8bit] set transfer-level as 8.
724 \\[mime-editor/set-split]       set message splitting mode.
725 \\[mime-editor/set-sign]        set PGP-sign mode.
726 \\[mime-editor/set-encrypt]     set PGP-encryption mode.
727 \\[mime-editor/preview-message] preview editing MIME message.
728 \\[mime-editor/exit]    exit and translate into a MIME compliant message.
729 \\[mime-editor/help]    show this help.
730 \\[mime-editor/maybe-translate] exit and translate if in MIME mode, then split.
731
732 Additional commands are available in some major modes:
733 C-c C-c         exit, translate and run the original command.
734 C-c C-s         exit, translate and run the original command.
735
736 The following is a message example written in the tagged MIME format.
737 TABs at the beginning of the line are not a part of the message:
738
739         This is a conventional plain text.  It should be translated
740         into text/plain.
741         --[[text/plain]]
742         This is also a plain text.  But, it is explicitly specified as
743         is.
744         --[[text/plain; charset=ISO-8859-1]]
745         This is also a plain text.  But charset is specified as
746         iso-8859-1.
747
748         Â¡Hola!  Buenos días.  Â¿Cómo está usted?
749         --[[text/enriched]]
750         This is a <bold>enriched text</bold>.
751         --[[image/gif][base64]]...image encoded in base64 here...
752         --[[audio/basic][base64]]...audio encoded in base64 here...
753
754 User customizable variables (not documented all of them):
755  mime-prefix
756     Specifies a key prefix for MIME minor mode commands.
757
758  mime-ignore-preceding-spaces
759     Preceding white spaces in a message body are ignored if non-nil.
760
761  mime-ignore-trailing-spaces
762     Trailing white spaces in a message body are ignored if non-nil.
763
764  mime-auto-hide-body
765     Hide a non-textual body message encoded in base64 after insertion
766     if non-nil.
767
768  mime-editor/transfer-level
769     A number of network transfer level.  It should be bigger than 7.
770     If you are in 8bit-through environment, please set 8.
771
772  mime-editor/voice-recorder
773     Specifies a function to record a voice message and encode it.
774     The function `mime-editor/voice-recorder-for-sun' is for Sun
775     SparcStations.
776
777  mime/editor-mode-hook
778     Turning on MIME mode calls the value of mime/editor-mode-hook, if
779     it is non-nil.
780
781  mime-editor/translate-hook
782     The value of mime-editor/translate-hook is called just before translating
783     the tagged MIME format into a MIME compliant message if it is
784     non-nil.  If the hook call the function mime-editor/insert-signature,
785     the signature file will be inserted automatically.
786
787  mime-editor/exit-hook
788     Turning off MIME mode calls the value of mime-editor/exit-hook, if it is
789     non-nil."
790   (interactive)
791   (if mime/editor-mode-flag
792       (error "You are already editing a MIME message.")
793     (setq mime/editor-mode-flag t)
794     ;; Remember old key bindings.
795     (if running-xemacs
796         (use-local-map (or (current-local-map) (make-sparse-keymap)))
797       (make-local-variable 'mime/editor-mode-old-local-map)
798       (setq mime/editor-mode-old-local-map (current-local-map))
799       ;; Add MIME commands to current local map.
800       (use-local-map (copy-keymap (or (current-local-map)
801                                       (make-sparse-keymap))))
802       )
803     (if (not (lookup-key (current-local-map) mime-prefix))
804         (define-key (current-local-map) mime-prefix mime-editor/mime-map))
805
806     ;; Set transfer level into mode line
807     ;;
808     (setq mime-editor/transfer-level-string
809           (mime/encoding-name mime-editor/transfer-level 'not-omit))
810     (force-mode-line-update)
811     
812     ;; Define menu.  Menus for other emacs implementations are
813     ;; welcome.
814     (cond (running-xemacs
815            (mime-editor/define-menu-for-xemacs))
816           ((>= emacs-major-version 19)
817            (mime-editor/define-menu-for-emacs19)
818            ))
819     ;; end
820     
821     (enable-invisible)
822     
823     ;; I don't care about saving these.
824     (setq paragraph-start
825           (regexp-or mime-editor/single-part-tag-regexp
826                      paragraph-start))
827     (setq paragraph-separate
828           (regexp-or mime-editor/single-part-tag-regexp
829                      paragraph-separate))
830     (run-hooks 'mime/editor-mode-hook)
831     (message
832      (substitute-command-keys
833       "Type \\[mime-editor/exit] to exit MIME mode, and type \\[mime-editor/help] to get help."))
834     ))
835
836 ;;;###autoload
837 (defalias 'edit-mime 'mime/editor-mode)         ; for convenience
838 (defalias 'mime-mode 'mime/editor-mode)         ; for convenience
839
840 (defun mime-editor/exit (&optional nomime no-error)
841   "Translate the tagged MIME message into a MIME compliant message.
842 With no argument encode a message in the buffer into MIME, otherwise
843 just return to previous mode."
844   (interactive "P")
845   (if (not mime/editor-mode-flag)
846       (if (null no-error)
847           (error "You aren't editing a MIME message.")
848         )
849     (if (not nomime)
850         (progn
851           (run-hooks 'mime-editor/translate-hook)
852           (mime-editor/translate-buffer)))
853     ;; Restore previous state.
854     (setq mime/editor-mode-flag nil)
855     (cond (running-xemacs
856            (if (featurep 'menubar) 
857                (delete-menu-item (list mime-editor/menu-title))))
858           (t
859            (use-local-map mime/editor-mode-old-local-map)))
860     
861     (end-of-invisible)
862     (set-buffer-modified-p (buffer-modified-p))
863     (run-hooks 'mime-editor/exit-hook)
864     (message "Exit MIME editor mode.")
865     ))
866
867 (defun mime-editor/maybe-translate ()
868   (interactive)
869   (mime-editor/exit nil t)
870   (call-interactively 'mime-editor/maybe-split-and-send)
871   )
872
873 (defun mime-editor/help ()
874   "Show help message about MIME mode."
875   (interactive)
876   (with-output-to-temp-buffer "*Help*"
877     (princ "MIME editor mode:\n")
878     (princ (documentation 'mime/editor-mode))
879     (print-help-return-message)))
880
881 (defun mime-editor/insert-text ()
882   "Insert a text message.
883 Charset is automatically obtained from the `mime/lc-charset-alist'."
884   (interactive)
885   (let ((ret (mime-editor/insert-tag "text" nil nil)))
886   (if ret
887       (progn
888         (if (looking-at mime-editor/single-part-tag-regexp)
889             (progn
890               ;; Make a space between the following message.
891               (insert "\n")
892               (forward-char -1)
893               ))
894         (if (and (member (second ret) '("enriched" "richtext"))
895                  (fboundp 'enriched-mode)
896                  )
897             (enriched-mode t)
898           (if (boundp 'enriched-mode)
899               (enriched-mode nil)
900             ))))))
901
902 (defun mime-editor/insert-file (file &optional verbose)
903   "Insert a message from a file."
904   (interactive "fInsert file as MIME message: \nP")
905   (let*  ((guess (mime-find-file-type file))
906           (type (nth 0 guess))
907           (subtype (nth 1 guess))
908           (parameters (nth 2 guess))
909           (encoding (nth 3 guess))
910           (disposition-type (nth 4 guess))
911           (disposition-params (nth 5 guess))
912           )
913     (if verbose
914         (setq type    (mime-prompt-for-type type)
915               subtype (mime-prompt-for-subtype type subtype)
916               ))
917     (if (or (interactive-p) verbose)
918         (setq encoding (mime-prompt-for-encoding encoding))
919       )
920     (if (or (consp parameters) (stringp disposition-type))
921         (let ((rest parameters) cell attribute value)
922           (setq parameters "")
923           (while rest
924             (setq cell (car rest))
925             (setq attribute (car cell))
926             (setq value (cdr cell))
927             (if (eq value 'file)
928                 (setq value (std11-wrap-as-quoted-string
929                              (file-name-nondirectory file)))
930               )
931             (setq parameters (concat parameters "; " attribute "=" value))
932             (setq rest (cdr rest))
933             )
934           (if disposition-type
935               (progn
936                 (setq parameters
937                       (concat parameters "\n"
938                               "Content-Disposition: " disposition-type))
939                 (setq rest disposition-params)
940                 (while rest
941                   (setq cell (car rest))
942                   (setq attribute (car cell))
943                   (setq value (cdr cell))
944                   (if (eq value 'file)
945                       (setq value (std11-wrap-as-quoted-string
946                                    (file-name-nondirectory file)))
947                     )
948                   (setq parameters
949                         (concat parameters "; " attribute "=" value))
950                   (setq rest (cdr rest))
951                   )
952                 ))
953           ))
954     (mime-editor/insert-tag type subtype parameters)
955     (mime-editor/insert-binary-file file encoding)
956     ))
957
958 (defun mime-editor/insert-external ()
959   "Insert a reference to external body."
960   (interactive)
961   (mime-editor/insert-tag "message" "external-body" nil ";\n\t")
962   ;;(forward-char -1)
963   ;;(insert "Content-Description: " (read-string "Content-Description: ") "\n")
964   ;;(forward-line 1)
965   (let* ((pritype (mime-prompt-for-type))
966          (subtype (mime-prompt-for-subtype pritype))
967          (parameters (mime-prompt-for-parameters pritype subtype ";\n\t")))
968     (and pritype
969          subtype
970          (insert "Content-Type: "
971                  pritype "/" subtype (or parameters "") "\n")))
972   (if (and (not (eobp))
973            (not (looking-at mime-editor/single-part-tag-regexp)))
974       (insert (mime-make-text-tag) "\n")))
975
976 (defun mime-editor/insert-voice ()
977   "Insert a voice message."
978   (interactive)
979   (let ((encoding
980          (completing-read
981           "What transfer encoding: "
982           mime-file-encoding-method-alist nil t nil)))
983     (mime-editor/insert-tag "audio" "basic" nil)
984     (mime-editor/define-encoding encoding)
985     (save-restriction
986       (narrow-to-region (1- (point))(point))
987       (unwind-protect
988           (funcall mime-editor/voice-recorder encoding)
989         (progn
990           (insert "\n")
991           (invisible-region (point-min)(point-max))
992           (goto-char (point-max))
993           )))))
994
995 (defun mime-editor/insert-signature (&optional arg)
996   "Insert a signature file."
997   (interactive "P")
998   (let ((signature-insert-hook
999          (function
1000           (lambda ()
1001             (apply (function mime-editor/insert-tag)
1002                    (mime-find-file-type signature-file-name))
1003             )))
1004         )
1005     (insert-signature arg)
1006     ))
1007
1008 \f
1009 ;; Insert a new tag around a point.
1010
1011 (defun mime-editor/insert-tag (&optional pritype subtype parameters delimiter)
1012   "Insert new MIME tag and return a list of PRITYPE, SUBTYPE, and PARAMETERS.
1013 If nothing is inserted, return nil."
1014   (interactive)
1015   (let ((p (point)))
1016     (mime-editor/goto-tag)
1017     (if (and (re-search-forward mime-editor/tag-regexp nil t)
1018              (< (match-beginning 0) p)
1019              (< p (match-end 0))
1020              )
1021         (goto-char (match-beginning 0))
1022       (goto-char p)
1023       ))
1024   (let ((oldtag nil)
1025         (newtag nil)
1026         (current (point))
1027         )
1028     (setq pritype
1029           (or pritype
1030               (mime-prompt-for-type)))
1031     (setq subtype
1032           (or subtype
1033               (mime-prompt-for-subtype pritype)))
1034     (setq parameters
1035           (or parameters
1036               (mime-prompt-for-parameters pritype subtype delimiter)))
1037     ;; Make a new MIME tag.
1038     (setq newtag (mime-make-tag pritype subtype parameters))
1039     ;; Find an current MIME tag.
1040     (setq oldtag
1041           (save-excursion
1042             (if (mime-editor/goto-tag)
1043                 (buffer-substring (match-beginning 0) (match-end 0))
1044               ;; Assume content type is 'text/plan'.
1045               (mime-make-tag "text" "plain")
1046               )))
1047     ;; We are only interested in TEXT.
1048     (if (and oldtag
1049              (not (mime-test-content-type
1050                    (mime-editor/get-contype oldtag) "text")))
1051         (setq oldtag nil))
1052     ;; Make a new tag.
1053     (if (or (not oldtag)                ;Not text
1054             (or mime-ignore-same-text-tag
1055                 (not (string-equal oldtag newtag))))
1056         (progn
1057           ;; Mark the beginning of the tag for convenience.
1058           (push-mark (point) 'nomsg)
1059           (insert newtag "\n")
1060           (list pritype subtype parameters) ;New tag is created.
1061           )
1062       ;; Restore previous point.
1063       (goto-char current)
1064       nil                               ;Nothing is created.
1065       )
1066     ))
1067
1068 (defun mime-editor/insert-binary-file (file &optional encoding)
1069   "Insert binary FILE at point.
1070 Optional argument ENCODING specifies an encoding method such as base64."
1071   (let* ((tagend (1- (point)))          ;End of the tag
1072          (hide-p (and mime-auto-hide-body
1073                       (stringp encoding)
1074                       (not
1075                        (let ((en (downcase encoding)))
1076                          (or (string-equal en "7bit")
1077                              (string-equal en "8bit")
1078                              (string-equal en "binary")
1079                              )))))
1080          )
1081     (save-restriction
1082       (narrow-to-region tagend (point))
1083       (mime-insert-encoded-file file encoding)
1084       (if hide-p
1085           (progn
1086             (invisible-region (point-min) (point-max))
1087             (goto-char (point-max))
1088             )
1089         (goto-char (point-max))
1090         ))
1091     (or hide-p
1092         (looking-at mime-editor/tag-regexp)
1093         (= (point)(point-max))
1094         (mime-editor/insert-tag "text" "plain")
1095         )
1096     ;; Define encoding even if it is 7bit.
1097     (if (stringp encoding)
1098         (save-excursion
1099           (goto-char tagend) ; Make sure which line the tag is on.
1100           (mime-editor/define-encoding encoding)
1101           ))
1102     ))
1103
1104 \f
1105 ;; Commands work on a current message flagment.
1106
1107 (defun mime-editor/goto-tag ()
1108   "Search for the beginning of the tagged MIME message."
1109   (let ((current (point)) multipart)
1110     (if (looking-at mime-editor/tag-regexp)
1111         t
1112       ;; At first, go to the end.
1113       (cond ((re-search-forward mime-editor/beginning-tag-regexp nil t)
1114              (goto-char (1- (match-beginning 0))) ;For multiline tag
1115              )
1116             (t
1117              (goto-char (point-max))
1118              ))
1119       ;; Then search for the beginning. 
1120       (re-search-backward mime-editor/end-tag-regexp nil t)
1121       (or (looking-at mime-editor/beginning-tag-regexp)
1122           ;; Restore previous point.
1123           (progn
1124             (goto-char current)
1125             nil
1126             ))
1127       )))
1128
1129 (defun mime-editor/content-beginning ()
1130   "Return the point of the beginning of content."
1131   (save-excursion
1132     (let ((beg (save-excursion
1133                  (beginning-of-line) (point))))
1134       (if (mime-editor/goto-tag)
1135           (let ((top (point)))
1136             (goto-char (match-end 0))
1137             (if (and (= beg top)
1138                      (= (following-char) ?\^M))
1139                 (point)
1140               (forward-line 1)
1141               (point)))
1142         ;; Default text/plain tag.
1143         (goto-char (point-min))
1144         (re-search-forward
1145          (concat "\n" (regexp-quote mail-header-separator)
1146                  (if mime-ignore-preceding-spaces
1147                      "[ \t\n]*\n" "\n")) nil 'move)
1148         (point))
1149       )))
1150
1151 (defun mime-editor/content-end ()
1152   "Return the point of the end of content."
1153   (save-excursion
1154     (let ((beg (point)))
1155       (if (mime-editor/goto-tag)
1156           (let ((top (point)))
1157             (goto-char (match-end 0))
1158             (if (invisible-p (point))
1159                 (next-visible-point (point))
1160               ;; Move to the end of this text.
1161               (if (re-search-forward mime-editor/tag-regexp nil 'move)
1162                   ;; Don't forget a multiline tag.
1163                   (goto-char (match-beginning 0))
1164                 )
1165               (point)
1166               ))
1167         ;; Assume the message begins with text/plain.
1168         (goto-char (mime-editor/content-beginning))
1169         (if (re-search-forward mime-editor/tag-regexp nil 'move)
1170             ;; Don't forget a multiline tag.
1171             (goto-char (match-beginning 0)))
1172         (point))
1173       )))
1174
1175 (defun mime-editor/define-charset (charset)
1176   "Set charset of current tag to CHARSET."
1177   (save-excursion
1178     (if (mime-editor/goto-tag)
1179         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1180           (delete-region (match-beginning 0) (match-end 0))
1181           (insert
1182            (mime-create-tag
1183             (mime-editor/set-parameter
1184              (mime-editor/get-contype tag)
1185              "charset" (upcase (symbol-name charset)))
1186             (mime-editor/get-encoding tag)))
1187           ))))
1188
1189 (defun mime-editor/define-encoding (encoding)
1190   "Set encoding of current tag to ENCODING."
1191   (save-excursion
1192     (if (mime-editor/goto-tag)
1193         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1194           (delete-region (match-beginning 0) (match-end 0))
1195           (insert (mime-create-tag (mime-editor/get-contype tag) encoding)))
1196       )))
1197
1198 (defun mime-editor/choose-charset ()
1199   "Choose charset of a text following current point."
1200   (detect-mime-charset-region (point) (mime-editor/content-end))
1201   )
1202
1203 (defun mime-make-text-tag (&optional subtype)
1204   "Make a tag for a text after current point.
1205 Subtype of text type can be specified by an optional argument SUBTYPE.
1206 Otherwise, it is obtained from mime-content-types."
1207   (let* ((pritype "text")
1208          (subtype (or subtype
1209                       (car (car (cdr (assoc pritype mime-content-types)))))))
1210     ;; Charset should be defined later.
1211     (mime-make-tag pritype subtype)))
1212
1213 \f
1214 ;; Tag handling functions
1215
1216 (defun mime-make-tag (pritype subtype &optional parameters encoding)
1217   "Make a tag of MIME message of PRITYPE, SUBTYPE and optional PARAMETERS."
1218   (mime-create-tag (concat (or pritype "") "/" (or subtype "")
1219                            (or parameters ""))
1220                    encoding))
1221
1222 (defun mime-create-tag (contype &optional encoding)
1223   "Make a tag with CONTENT-TYPE and optional ENCODING."
1224   (format (if encoding mime-tag-format-with-encoding mime-tag-format)
1225           contype encoding))
1226
1227 (defun mime-editor/get-contype (tag)
1228   "Return Content-Type (including parameters) of TAG."
1229   (and (stringp tag)
1230        (or (string-match mime-editor/single-part-tag-regexp tag)
1231            (string-match mime-editor/multipart-beginning-regexp tag)
1232            (string-match mime-editor/multipart-end-regexp tag)
1233            )
1234        (substring tag (match-beginning 1) (match-end 1))
1235        ))
1236
1237 (defun mime-editor/get-encoding (tag)
1238   "Return encoding of TAG."
1239   (and (stringp tag)
1240        (string-match mime-editor/single-part-tag-regexp tag)
1241        (match-beginning 3)
1242        (not (= (match-beginning 3) (match-end 3)))
1243        (substring tag (match-beginning 3) (match-end 3))))
1244
1245 (defun mime-get-parameter (contype parameter)
1246   "For given CONTYPE return value for PARAMETER.
1247 Nil if no such parameter."
1248   (if (string-match
1249        (concat
1250         ";[ \t\n]*"
1251         (regexp-quote parameter)
1252         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\([ \t\n]*;\\|$\\)")
1253        contype)
1254       (substring contype (match-beginning 1) (match-end 1))
1255     nil                                 ;No such parameter
1256     ))
1257
1258 (defun mime-editor/set-parameter (contype parameter value)
1259   "For given CONTYPE set PARAMETER to VALUE."
1260   (let (ctype opt-fields)
1261     (if (string-match "\n[^ \t\n\r]+:" contype)
1262         (setq ctype (substring contype 0 (match-beginning 0))
1263               opt-fields (substring contype (match-beginning 0)))
1264       (setq ctype contype)
1265       )
1266     (if (string-match
1267          (concat
1268           ";[ \t\n]*\\("
1269           (regexp-quote parameter)
1270           "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\)[ \t\n]*\\(;\\|$\\)")
1271          ctype)
1272         ;; Change value
1273         (concat (substring ctype 0 (match-beginning 1))
1274                 parameter "=" value
1275                 (substring contype (match-end 1))
1276                 opt-fields)
1277       (concat ctype "; " parameter "=" value opt-fields)
1278       )))
1279
1280 (defun mime-strip-parameters (contype)
1281   "Return primary content-type and subtype without parameters for CONTYPE."
1282   (if (string-match "^[ \t]*\\([^; \t\n]*\\)" contype)
1283       (substring contype (match-beginning 1) (match-end 1)) nil))
1284
1285 (defun mime-test-content-type (contype type &optional subtype)
1286   "Test if CONTYPE is a TYPE and an optional SUBTYPE."
1287   (and (stringp contype)
1288        (stringp type)
1289        (string-match
1290         (concat "^[ \t]*" (downcase type) "/" (downcase (or subtype "")))
1291         (downcase contype))))
1292
1293 \f
1294 ;; Basic functions
1295
1296 (defun mime-find-file-type (file)
1297   "Guess Content-Type, subtype, and parameters from FILE."
1298   (let ((guess nil)
1299         (guesses mime-file-types))
1300     (while (and (not guess) guesses)
1301       (if (string-match (car (car guesses)) file)
1302           (setq guess (cdr (car guesses))))
1303       (setq guesses (cdr guesses)))
1304     guess
1305     ))
1306
1307 (defun mime-prompt-for-type (&optional default)
1308   "Ask for Content-type."
1309   (let ((type ""))
1310     ;; Repeat until primary content type is specified.
1311     (while (string-equal type "")
1312       (setq type
1313             (completing-read "What content type: "
1314                              mime-content-types
1315                              nil
1316                              'require-match ;Type must be specified.
1317                              default
1318                              ))
1319       (if (string-equal type "")
1320           (progn
1321             (message "Content type is required.")
1322             (beep)
1323             (sit-for 1)
1324             ))
1325       )
1326     type))
1327
1328 (defun mime-prompt-for-subtype (type &optional default)
1329   "Ask for subtype of media-type TYPE."
1330   (let ((subtypes (cdr (assoc type mime-content-types))))
1331     (or (and default
1332              (assoc default subtypes))
1333         (setq default (car (car subtypes)))
1334         ))
1335   (let* ((answer
1336           (completing-read
1337            (if default
1338                (concat
1339                 "What content subtype: (default " default ") ")
1340              "What content subtype: ")
1341            (cdr (assoc type mime-content-types))
1342            nil
1343            'require-match               ;Subtype must be specified.
1344            nil
1345            )))
1346     (if (string-equal answer "") default answer)))
1347
1348 (defun mime-prompt-for-parameters (pritype subtype &optional delimiter)
1349   "Ask for Content-type parameters of Content-Type PRITYPE and SUBTYPE.
1350 Optional DELIMITER specifies parameter delimiter (';' by default)."
1351   (let* ((delimiter (or delimiter "; "))
1352          (parameters
1353           (mapconcat
1354            (function identity)
1355            (delq nil
1356                  (mime-prompt-for-parameters-1
1357                   (cdr (assoc subtype
1358                               (cdr (assoc pritype mime-content-types))))))
1359            delimiter
1360            )))
1361     (if (and (stringp parameters)
1362              (not (string-equal parameters "")))
1363         (concat delimiter parameters)
1364       ""                                ;"" if no parameters
1365       )))
1366
1367 (defun mime-prompt-for-parameters-1 (optlist)
1368   (apply (function append)
1369          (mapcar (function mime-prompt-for-parameter) optlist)))
1370
1371 (defun mime-prompt-for-parameter (parameter)
1372   "Ask for PARAMETER.
1373 Parameter must be '(PROMPT CHOICE1 (CHOISE2 ...))."
1374   (let* ((prompt (car parameter))
1375          (choices (mapcar (function
1376                            (lambda (e)
1377                              (if (consp e) e (list e))))
1378                           (cdr parameter)))
1379          (default (car (car choices)))
1380          (answer nil))
1381     (if choices
1382         (progn
1383           (setq answer
1384                 (completing-read
1385                  (concat "What " prompt
1386                          ": (default "
1387                          (if (string-equal default "") "\"\"" default)
1388                          ") ")
1389                  choices nil nil ""))
1390           ;; If nothing is selected, use default.
1391           (if (string-equal answer "")
1392               (setq answer default)))
1393       (setq answer
1394             (read-string (concat "What " prompt ": "))))
1395     (cons (if (and answer
1396                    (not (string-equal answer "")))
1397               (concat prompt "="
1398                       ;; Note: control characters ignored!
1399                       (if (string-match mime-tspecials-regexp answer)
1400                           (concat "\"" answer "\"") answer)))
1401           (mime-prompt-for-parameters-1 (cdr (assoc answer (cdr parameter)))))
1402     ))
1403
1404 (defun mime-prompt-for-encoding (default)
1405   "Ask for Content-Transfer-Encoding. [tm-edit.el]"
1406   (let (encoding)
1407     (while (string=
1408             (setq encoding
1409                   (completing-read
1410                    "What transfer encoding: "
1411                    mime-file-encoding-method-alist nil t default)
1412                   )
1413             ""))
1414     encoding))
1415
1416 \f
1417 ;;; @ Translate the tagged MIME messages into a MIME compliant message.
1418 ;;;
1419
1420 (defvar mime-editor/translate-buffer-hook
1421   '(mime-editor/pgp-enclose-buffer
1422     mime-editor/translate-header
1423     mime-editor/translate-body))
1424
1425 (defun mime-editor/translate-header ()
1426   "Encode the message header into network representation."
1427   (mime/encode-message-header 'code-conversion)
1428   (run-hooks 'mime-editor/translate-header-hook)
1429   )
1430
1431 (defun mime-editor/translate-buffer ()
1432   "Encode the tagged MIME message in current buffer in MIME compliant message."
1433   (interactive)
1434   (if (catch 'mime-editor/error
1435         (save-excursion
1436           (run-hooks 'mime-editor/translate-buffer-hook)
1437           ))
1438       (progn
1439         (undo)
1440         (error "Translation error!")
1441         )))
1442
1443 (defun mime-editor/find-inmost ()
1444   (goto-char (point-min))
1445   (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1446       (let ((bb (match-beginning 0))
1447             (be (match-end 0))
1448             (type (buffer-substring (match-beginning 1)(match-end 1)))
1449             end-exp eb ee)
1450         (setq end-exp (format "--}-<<%s>>\n" type))
1451         (widen)
1452         (if (re-search-forward end-exp nil t)
1453             (progn
1454               (setq eb (match-beginning 0))
1455               (setq ee (match-end 0))
1456               )
1457           (setq eb (point-max))
1458           (setq ee (point-max))
1459           )
1460         (narrow-to-region be eb)
1461         (goto-char be)
1462         (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1463             (let (ret)
1464               (narrow-to-region (match-beginning 0)(point-max))
1465               (mime-editor/find-inmost)
1466               )
1467           (widen)
1468           (list type bb be eb)
1469           ))))
1470
1471 (defun mime-editor/process-multipart-1 (boundary)
1472   (let ((ret (mime-editor/find-inmost)))
1473     (if ret
1474         (let ((type (car ret))
1475               (bb (nth 1 ret))(be (nth 2 ret))
1476               (eb (nth 3 ret))
1477               )
1478           (narrow-to-region bb eb)
1479           (delete-region bb be)
1480           (setq bb (point-min))
1481           (setq eb (point-max))
1482           (widen)
1483           (goto-char eb)
1484           (if (looking-at mime-editor/multipart-end-regexp)
1485               (let ((beg (match-beginning 0))
1486                     (end (match-end 0))
1487                     )
1488                 (delete-region beg end)
1489                 (or (looking-at mime-editor/beginning-tag-regexp)
1490                     (eobp)
1491                     (insert (concat (mime-make-text-tag) "\n"))
1492                     )))
1493           (cond ((string-equal type "quote")
1494                  (mime-editor/enquote-region bb eb)
1495                  )
1496                 ((string-equal type "signed")
1497                  (cond ((eq mime-editor/signing-type 'pgp-elkins)
1498                         (mime-editor/sign-pgp-elkins bb eb boundary)
1499                         )
1500                        ((eq mime-editor/signing-type 'pgp-kazu)
1501                         (mime-editor/sign-pgp-kazu bb eb boundary)
1502                         ))
1503                  )
1504                 ((string-equal type "encrypted")
1505                  (cond ((eq mime-editor/encrypting-type 'pgp-elkins)
1506                         (mime-editor/encrypt-pgp-elkins bb eb boundary)
1507                         )
1508                        ((eq mime-editor/encrypting-type 'pgp-kazu)
1509                         (mime-editor/encrypt-pgp-kazu bb eb boundary)
1510                         )))
1511                 (t
1512                  (setq boundary
1513                        (nth 2 (mime-editor/translate-region bb eb
1514                                                             boundary t)))
1515                  (goto-char bb)
1516                  (insert
1517                   (format "--[[multipart/%s;
1518  boundary=\"%s\"][7bit]]\n"
1519                           type boundary))
1520                  ))
1521           boundary))))
1522
1523 (defun mime-editor/enquote-region (beg end)
1524   (save-excursion
1525     (save-restriction
1526       (narrow-to-region beg end)
1527       (goto-char beg)
1528       (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1529         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1530           (replace-match (concat "- " (substring tag 1)))
1531           )))))
1532
1533 (defun mime-editor/dequote-region (beg end)
1534   (save-excursion
1535     (save-restriction
1536       (narrow-to-region beg end)
1537       (goto-char beg)
1538       (while (re-search-forward
1539               mime-editor/quoted-single-part-tag-regexp nil t)
1540         (let ((tag (buffer-substring (match-beginning 0)(match-end 0))))
1541           (replace-match (concat "-" (substring tag 2)))
1542           )))))
1543
1544 (defun mime-editor/sign-pgp-elkins (beg end boundary)
1545   (save-excursion
1546     (save-restriction
1547       (narrow-to-region beg end)
1548       (let* ((ret
1549               (mime-editor/translate-region beg end boundary))
1550              (ctype    (car ret))
1551              (encoding (nth 1 ret))
1552              (parts    (nth 3 ret))
1553              (pgp-boundary (concat "pgp-sign-" boundary))
1554              )
1555         (goto-char beg)
1556         (insert (format "Content-Type: %s\n" ctype))
1557         (if encoding
1558             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1559           )
1560         (insert "\n")
1561         (or (funcall mime-editor/pgp-sign-function
1562                      (point-min)(point-max) nil nil pgp-boundary)
1563             (throw 'mime-editor/error 'pgp-error)
1564             )
1565         ))))
1566
1567 (defvar mime-editor/encrypt-recipient-fields-list '("To" "cc"))
1568
1569 (defun mime-editor/make-encrypt-recipient-header ()
1570   (let* ((names mime-editor/encrypt-recipient-fields-list)
1571          (values
1572           (std11-field-bodies (cons "From" names)
1573                               nil mail-header-separator))
1574          (from (prog1
1575                    (car values)
1576                  (setq values (cdr values))))
1577          (header (and (stringp from)
1578                       (if (string-equal from "")
1579                           ""
1580                         (format "From: %s\n" from)
1581                         )))
1582          recipients)
1583     (while (and names values)
1584       (let ((name (car names))
1585             (value (car values))
1586             )
1587         (and (stringp value)
1588              (or (string-equal value "")
1589                  (progn
1590                    (setq header (concat header name ": " value "\n")
1591                          recipients (if recipients
1592                                         (concat recipients " ," value)
1593                                       value))
1594                    ))))
1595       (setq names (cdr names)
1596             values (cdr values))
1597       )
1598     (vector from recipients header)
1599     ))
1600
1601 (defun mime-editor/encrypt-pgp-elkins (beg end boundary)
1602   (save-excursion
1603     (save-restriction
1604       (let (from recipients header)
1605         (let ((ret (mime-editor/make-encrypt-recipient-header)))
1606           (setq from (aref ret 0)
1607                 recipients (aref ret 1)
1608                 header (aref ret 2))
1609           )
1610         (narrow-to-region beg end)
1611         (let* ((ret
1612                 (mime-editor/translate-region beg end boundary))
1613                (ctype    (car ret))
1614                (encoding (nth 1 ret))
1615                (parts    (nth 3 ret))
1616                (pgp-boundary (concat "pgp-" boundary))
1617                )
1618           (goto-char beg)
1619           (insert header)
1620           (insert (format "Content-Type: %s\n" ctype))
1621           (if encoding
1622               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1623             )
1624           (insert "\n")
1625           (or (funcall mime-editor/pgp-encrypt-function
1626                        recipients (point-min) (point-max) from)
1627               (throw 'mime-editor/error 'pgp-error)
1628               )
1629           (goto-char beg)
1630           (insert (format "--[[multipart/encrypted;
1631  boundary=\"%s\";
1632  protocol=\"application/pgp-encrypted\"][7bit]]
1633 --%s
1634 Content-Type: application/pgp-encrypted
1635
1636 --%s
1637 Content-Type: application/octet-stream
1638 Content-Transfer-Encoding: 7bit
1639
1640 " pgp-boundary pgp-boundary pgp-boundary))
1641           (goto-char (point-max))
1642           (insert (format "\n--%s--\n" pgp-boundary))
1643           )))))
1644
1645 (defun mime-editor/sign-pgp-kazu (beg end boundary)
1646   (save-excursion
1647     (save-restriction
1648       (narrow-to-region beg end)
1649       (let* ((ret
1650               (mime-editor/translate-region beg end boundary))
1651              (ctype    (car ret))
1652              (encoding (nth 1 ret))
1653              (parts    (nth 3 ret))
1654              )
1655         (goto-char beg)
1656         (insert (format "Content-Type: %s\n" ctype))
1657         (if encoding
1658             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1659           )
1660         (insert "\n")
1661         (or (as-binary-process
1662              (funcall mime-editor/traditional-pgp-sign-function
1663                       beg (point-max)))
1664             (throw 'mime-editor/error 'pgp-error)
1665             )
1666         (goto-char beg)
1667         (insert
1668          "--[[application/pgp; format=mime][7bit]]\n")
1669         ))
1670     ))
1671
1672 (defun mime-editor/encrypt-pgp-kazu (beg end boundary)
1673   (save-excursion
1674     (let (from recipients header)
1675       (let ((ret (mime-editor/make-encrypt-recipient-header)))
1676         (setq from (aref ret 0)
1677               recipients (aref ret 1)
1678               header (aref ret 2))
1679         )
1680       (save-restriction
1681         (narrow-to-region beg end)
1682         (let* ((ret
1683                 (mime-editor/translate-region beg end boundary))
1684                (ctype    (car ret))
1685                (encoding (nth 1 ret))
1686                (parts    (nth 3 ret))
1687                )
1688           (goto-char beg)
1689           (insert header)
1690           (insert (format "Content-Type: %s\n" ctype))
1691           (if encoding
1692               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1693             )
1694           (insert "\n")
1695           (or (as-binary-process
1696                (funcall mime-editor/pgp-encrypt-function
1697                         recipients beg (point-max) nil 'maybe)
1698                )
1699               (throw 'mime-editor/error 'pgp-error)
1700               )
1701           (goto-char beg)
1702           (insert
1703            "--[[application/pgp; format=mime][7bit]]\n")
1704           ))
1705       )))
1706
1707 (defun mime-editor/translate-body ()
1708   "Encode the tagged MIME body in current buffer in MIME compliant message."
1709   (interactive)
1710   (save-excursion
1711     (let ((boundary
1712            (concat mime-multipart-boundary "_"
1713                    (replace-space-with-underline (current-time-string))
1714                    ))
1715           (i 1)
1716           ret)
1717       (while (mime-editor/process-multipart-1
1718               (format "%s-%d" boundary i))
1719         (setq i (1+ i))
1720         )
1721       (save-restriction
1722         ;; We are interested in message body.
1723         (let* ((beg
1724                 (progn
1725                   (goto-char (point-min))
1726                   (re-search-forward
1727                    (concat "\n" (regexp-quote mail-header-separator)
1728                            (if mime-ignore-preceding-spaces
1729                                "[ \t\n]*\n" "\n")) nil 'move)
1730                   (point)))
1731                (end
1732                 (progn
1733                   (goto-char (point-max))
1734                   (and mime-ignore-trailing-spaces
1735                        (re-search-backward "[^ \t\n]\n" beg t)
1736                        (forward-char 1))
1737                   (point))))
1738           (setq ret (mime-editor/translate-region
1739                      beg end
1740                      (format "%s-%d" boundary i)))
1741           ))
1742       (mime-editor/dequote-region (point-min)(point-max))
1743       (let ((contype (car ret))         ;Content-Type
1744             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1745             )
1746         ;; Make primary MIME headers.
1747         (or (mail-position-on-field "Mime-Version")
1748             (insert mime-editor/mime-version-value))
1749         ;; Remove old Content-Type and other fields.
1750         (save-restriction
1751           (goto-char (point-min))
1752           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1753           (narrow-to-region (point-min) (point))
1754           (goto-char (point-min))
1755           (mime-delete-field "Content-Type")
1756           (mime-delete-field "Content-Transfer-Encoding"))
1757         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1758         (mail-position-on-field "Content-Type")
1759         (insert contype)
1760         (if encoding
1761             (progn
1762               (mail-position-on-field "Content-Transfer-Encoding")
1763               (insert encoding)))
1764         ))))
1765
1766 (defun mime-editor/translate-single-part-tag (&optional prefix)
1767   (if (re-search-forward mime-editor/single-part-tag-regexp nil t)
1768       (let* ((beg (match-beginning 0))
1769              (end (match-end 0))
1770              (tag (buffer-substring beg end))
1771              )
1772         (delete-region beg end)
1773         (setq contype (mime-editor/get-contype tag))
1774         (setq encoding (mime-editor/get-encoding tag))
1775         (insert (concat prefix "--" boundary "\n"))
1776         (save-restriction
1777           (narrow-to-region (point)(point))
1778           (insert "Content-Type: " contype "\n")
1779           (if encoding
1780               (insert "Content-Transfer-Encoding: " encoding "\n"))
1781           (mime/encode-message-header)
1782           )
1783         t)))
1784
1785 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1786   (if (null boundary)
1787       (setq boundary
1788             (concat mime-multipart-boundary "_"
1789                     (replace-space-with-underline (current-time-string))))
1790     )
1791   (save-excursion
1792     (save-restriction
1793       (narrow-to-region beg end)
1794       (let ((tag nil)                   ;MIME tag
1795             (contype nil)               ;Content-Type
1796             (encoding nil)              ;Content-Transfer-Encoding
1797             (nparts 0))                 ;Number of body parts
1798         ;; Normalize the body part by inserting appropriate message
1799         ;; tags for every message contents.
1800         (mime-editor/normalize-body)
1801         ;; Counting the number of Content-Type.
1802         (goto-char (point-min))
1803         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1804           (setq nparts (1+ nparts)))
1805         ;; Begin translation.
1806         (cond
1807          ((and (<= nparts 1)(not multipart))
1808           ;; It's a singular message.
1809           (goto-char (point-min))
1810           (while (re-search-forward
1811                   mime-editor/single-part-tag-regexp nil t)
1812             (setq tag
1813                   (buffer-substring (match-beginning 0) (match-end 0)))
1814             (delete-region (match-beginning 0) (1+ (match-end 0)))
1815             (setq contype (mime-editor/get-contype tag))
1816             (setq encoding (mime-editor/get-encoding tag))
1817             ))
1818          (t
1819           ;; It's a multipart message.
1820           (goto-char (point-min))
1821           (and (mime-editor/translate-single-part-tag)
1822                (while (mime-editor/translate-single-part-tag "\n"))
1823                )
1824           ;; Define Content-Type as "multipart/mixed".
1825           (setq contype
1826                 (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1827           ;; Content-Transfer-Encoding must be "7bit".
1828           ;; The following encoding can be `nil', but is
1829           ;; specified as is since there is no way that a user
1830           ;; specifies it.
1831           (setq encoding "7bit")
1832           ;; Insert the trailer.
1833           (goto-char (point-max))
1834           (insert "\n--" boundary "--\n")
1835           ))
1836         (list contype encoding boundary nparts)
1837         ))))
1838
1839 (defun mime-editor/normalize-body ()
1840   "Normalize the body part by inserting appropriate message tags."
1841   ;; Insert the first MIME tags if necessary.
1842   (goto-char (point-min))
1843   (if (not (looking-at mime-editor/single-part-tag-regexp))
1844       (insert (mime-make-text-tag) "\n"))
1845   ;; Check each tag, and add new tag or correct it if necessary.
1846   (goto-char (point-min))
1847   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1848     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1849            (contype (mime-editor/get-contype tag))
1850            (charset (mime-get-parameter contype "charset"))
1851            (encoding (mime-editor/get-encoding tag)))
1852       ;; Remove extra whitespaces after the tag.
1853       (if (looking-at "[ \t]+$")
1854           (delete-region (match-beginning 0) (match-end 0)))
1855       (let ((beg (point))
1856             (end (mime-editor/content-end))
1857             )
1858         (if (= end (point-max))
1859             nil
1860           (goto-char end)
1861           (or (looking-at mime-editor/beginning-tag-regexp)
1862               (eobp)
1863               (insert (mime-make-text-tag) "\n")
1864               ))
1865         (visible-region beg end)
1866         (goto-char beg)
1867         )
1868       (cond
1869        ((mime-test-content-type contype "message")
1870         ;; Content-type "message" should be sent as is.
1871         (forward-line 1)
1872         )
1873        ((mime-test-content-type contype "text")
1874         ;; Define charset for text if necessary.
1875         (setq charset (if charset
1876                           (intern (downcase charset))
1877                         (mime-editor/choose-charset)))
1878         (mime-editor/define-charset charset)
1879         (cond ((string-equal contype "text/x-rot13-47")
1880                (save-excursion
1881                  (forward-line)
1882                  (set-mark (point))
1883                  (goto-char (mime-editor/content-end))
1884                  (tm:caesar-region)
1885                  ))
1886               ((string-equal contype "text/enriched")
1887                (save-excursion
1888                  (let ((beg (progn
1889                               (forward-line)
1890                               (point)))
1891                        (end (mime-editor/content-end))
1892                        )
1893                    ;; Patch for hard newlines
1894                    ;; (save-excursion
1895                    ;;   (goto-char beg)
1896                    ;;   (while (search-forward "\n" end t)
1897                    ;;     (put-text-property (match-beginning 0)
1898                    ;;                        (point)
1899                    ;;                        'hard t)))
1900                    ;; End patch for hard newlines
1901                    (enriched-encode beg end)
1902                    (goto-char beg)
1903                    (if (search-forward "\n\n")
1904                        (delete-region beg (match-end 0))
1905                      )
1906                    ))))
1907         ;; Point is now on current tag.
1908         ;; Define encoding and encode text if necessary.
1909         (or encoding    ;Encoding is not specified.
1910             (let* ((encoding
1911                     (cdr
1912                      (assq charset
1913                            mime-editor/charset-default-encoding-alist)
1914                      ))
1915                    (beg (mime-editor/content-beginning))
1916                    )
1917               (encode-mime-charset-region beg (mime-editor/content-end)
1918                                           charset)
1919               (mime-encode-region beg (mime-editor/content-end) encoding)
1920               (mime-editor/define-encoding encoding)
1921               ))
1922         (goto-char (mime-editor/content-end))
1923         )
1924        ((null encoding)         ;Encoding is not specified.
1925         ;; Application, image, audio, video, and any other
1926         ;; unknown content-type without encoding should be
1927         ;; encoded.
1928         (let* ((encoding "base64")      ;Encode in BASE64 by default.
1929                (beg (mime-editor/content-beginning))
1930                (end (mime-editor/content-end))
1931                (body (buffer-substring beg end))
1932                )
1933           (mime-encode-region beg end encoding)
1934           (mime-editor/define-encoding encoding))
1935         (forward-line 1)
1936         ))
1937       )))
1938
1939 (defun mime-delete-field (field)
1940   "Delete header FIELD."
1941   (let ((regexp (format "^%s:[ \t]*" field)))
1942     (goto-char (point-min))
1943     (while (re-search-forward regexp nil t)
1944       (delete-region (match-beginning 0)
1945                      (progn (forward-line 1) (point)))
1946       )))
1947
1948 \f
1949 ;;;
1950 ;;; Platform dependent functions
1951 ;;;
1952
1953 ;; Sun implementations
1954
1955 (defun mime-editor/voice-recorder-for-sun (encoding)
1956   "Record voice in a buffer using Sun audio device,
1957 and insert data encoded as ENCODING. [tm-edit.el]"
1958   (message "Start the recording on %s.  Type C-g to finish the recording..."
1959            (system-name))
1960   (mime-insert-encoded-file "/dev/audio" encoding)
1961   )
1962
1963 \f
1964 ;;; @ Other useful commands.
1965 ;;;
1966
1967 ;; Message forwarding commands as content-type "message/rfc822".
1968
1969 (defun mime-editor/insert-message (&optional message)
1970   (interactive)
1971   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
1972     (if (and inserter (fboundp inserter))
1973         (progn
1974           (mime-editor/insert-tag "message" "rfc822")
1975           (funcall inserter message)
1976           )
1977       (message "Sorry, I don't have message inserter for your MUA.")
1978       )))
1979
1980 (defun mime-editor/insert-mail (&optional message)
1981   (interactive)
1982   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
1983     (if (and inserter (fboundp inserter))
1984         (progn
1985           (mime-editor/insert-tag "message" "rfc822")
1986           (funcall inserter message)
1987           )
1988       (message "Sorry, I don't have mail inserter for your MUA.")
1989       )))
1990
1991 (defun mime-editor/inserted-message-filter ()
1992   (save-excursion
1993     (save-restriction
1994       (let ((header-start (point))
1995             (case-fold-search t)
1996             beg end)
1997         ;; for Emacs 18
1998         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
1999         (if (re-search-forward "^$" (mark t))
2000             (narrow-to-region header-start (match-beginning 0))
2001           )
2002         (goto-char header-start)
2003         (while (and (re-search-forward
2004                      mime-editor/yank-ignored-field-regexp nil t)
2005                     (setq beg (match-beginning 0))
2006                     (setq end (1+ (std11-field-end)))
2007                     )
2008           (delete-region beg end)
2009           )
2010         ))))
2011
2012
2013 ;;; @ multipart enclosure
2014 ;;;
2015
2016 (defun mime-editor/enclose-region (type beg end)
2017   (save-excursion
2018     (goto-char beg)
2019     (let ((current (point)))
2020       (save-restriction
2021         (narrow-to-region beg end)
2022         (insert (format "--<<%s>>-{\n" type))
2023         (goto-char (point-max))
2024         (insert (format "--}-<<%s>>\n" type))
2025         (goto-char (point-max))
2026         )
2027       (or (looking-at mime-editor/beginning-tag-regexp)
2028           (eobp)
2029           (insert (mime-make-text-tag) "\n")
2030           )
2031       )))
2032
2033 (defun mime-editor/enclose-quote-region (beg end)
2034   (interactive "*r")
2035   (mime-editor/enclose-region "quote" beg end)
2036   )
2037
2038 (defun mime-editor/enclose-mixed-region (beg end)
2039   (interactive "*r")
2040   (mime-editor/enclose-region "mixed" beg end)
2041   )
2042
2043 (defun mime-editor/enclose-parallel-region (beg end)
2044   (interactive "*r")
2045   (mime-editor/enclose-region "parallel" beg end)
2046   )
2047
2048 (defun mime-editor/enclose-digest-region (beg end)
2049   (interactive "*r")
2050   (mime-editor/enclose-region "digest" beg end)
2051   )
2052
2053 (defun mime-editor/enclose-alternative-region (beg end)
2054   (interactive "*r")
2055   (mime-editor/enclose-region "alternative" beg end)
2056   )
2057
2058 (defun mime-editor/enclose-signed-region (beg end)
2059   (interactive "*r")
2060   (if mime-editor/signing-type
2061       (mime-editor/enclose-region "signed" beg end)
2062     (message "Please specify signing type.")
2063     ))
2064
2065 (defun mime-editor/enclose-encrypted-region (beg end)
2066   (interactive "*r")
2067   (if mime-editor/signing-type
2068       (mime-editor/enclose-region "encrypted" beg end)
2069     (message "Please specify encrypting type.")
2070     ))
2071
2072 (defun mime-editor/insert-key (&optional arg)
2073   "Insert a pgp public key."
2074   (interactive "P")
2075   (mime-editor/insert-tag "application" "pgp-keys")
2076   (mime-editor/define-encoding "7bit")
2077   (funcall mime-editor/pgp-insert-public-key-function)
2078   )
2079
2080
2081 ;;; @ flag setting
2082 ;;;
2083
2084 (defun mime-editor/set-split (arg)
2085   (interactive
2086    (list
2087     (y-or-n-p "Do you want to enable split?")
2088     ))
2089   (setq mime-editor/split-message arg)
2090   (if arg
2091       (message "This message is enabled to split.")
2092     (message "This message is not enabled to split.")
2093     ))
2094
2095 (defun mime-editor/toggle-transfer-level (&optional transfer-level)
2096   "Toggle transfer-level is 7bit or 8bit through.
2097
2098 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2099   (interactive)
2100   (if (numberp transfer-level)
2101       (setq mime-editor/transfer-level transfer-level)
2102     (if (< mime-editor/transfer-level 8)
2103         (setq mime-editor/transfer-level 8)
2104       (setq mime-editor/transfer-level 7)
2105       ))
2106   (setq mime-editor/charset-default-encoding-alist
2107         (mime-editor/make-charset-default-encoding-alist
2108          mime-editor/transfer-level))
2109   (message (format "Current transfer-level is %d bit"
2110                    mime-editor/transfer-level))
2111   (setq mime-editor/transfer-level-string
2112         (mime/encoding-name mime-editor/transfer-level 'not-omit))
2113   (force-mode-line-update)
2114   )
2115
2116 (defun mime-editor/set-transfer-level-7bit ()
2117   (interactive)
2118   (mime-editor/toggle-transfer-level 7)
2119   )
2120
2121 (defun mime-editor/set-transfer-level-8bit ()
2122   (interactive)
2123   (mime-editor/toggle-transfer-level 8)
2124   )
2125
2126
2127 ;;; @ pgp
2128 ;;;
2129
2130 (defun mime-editor/set-sign (arg)
2131   (interactive
2132    (list
2133     (y-or-n-p "Do you want to sign?")
2134     ))
2135   (if arg
2136       (if mime-editor/signing-type
2137           (progn
2138             (setq mime-editor/pgp-processing 'sign)
2139             (message "This message will be signed.")
2140             )
2141         (message "Please specify signing type.")
2142         )
2143     (if (eq mime-editor/pgp-processing 'sign)
2144         (setq mime-editor/pgp-processing nil)
2145       )
2146     (message "This message will not be signed.")
2147     ))
2148
2149 (defun mime-editor/set-encrypt (arg)
2150   (interactive
2151    (list
2152     (y-or-n-p "Do you want to encrypt?")
2153     ))
2154   (if arg
2155       (if mime-editor/encrypting-type
2156           (progn
2157             (setq mime-editor/pgp-processing 'encrypt)
2158             (message "This message will be encrypt.")
2159             )
2160         (message "Please specify encrypting type.")
2161         )
2162     (if (eq mime-editor/pgp-processing 'encrypt)
2163         (setq mime-editor/pgp-processing nil)
2164       )
2165     (message "This message will not be encrypt.")
2166     ))
2167
2168 (defvar mime-editor/pgp-processing nil)
2169 (make-variable-buffer-local 'mime-editor/pgp-processing)
2170
2171 (defun mime-editor/pgp-enclose-buffer ()
2172   (let ((beg (save-excursion
2173                (goto-char (point-min))
2174                (if (search-forward (concat "\n" mail-header-separator "\n"))
2175                    (match-end 0)
2176                  )))
2177         (end (point-max))
2178         )
2179     (if beg
2180         (cond ((eq mime-editor/pgp-processing 'sign)
2181                (mime-editor/enclose-signed-region beg end)
2182                )
2183               ((eq mime-editor/pgp-processing 'encrypt)
2184                (mime-editor/enclose-encrypted-region beg end)
2185                ))
2186       )))
2187
2188
2189 ;;; @ split
2190 ;;;
2191
2192 (defun mime-editor/insert-partial-header
2193   (fields subject id number total separator)
2194   (insert fields)
2195   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2196   (insert (format "Mime-Version: 1.0 (split by %s)\n"
2197                   mime-editor/version-name))
2198   (insert (format "\
2199 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2200                   id number total separator))
2201   )
2202
2203 (defun mime-editor/split-and-send
2204   (&optional cmd lines mime-editor/message-max-length)
2205   (interactive)
2206   (or lines
2207       (setq lines
2208             (count-lines (point-min) (point-max)))
2209       )
2210   (or mime-editor/message-max-length
2211       (setq mime-editor/message-max-length
2212             (or (cdr (assq major-mode mime-editor/message-max-lines-alist))
2213                 mime-editor/message-default-max-lines))
2214       )
2215   (let* ((mime-editor/draft-file-name 
2216           (or (buffer-file-name)
2217               (make-temp-name
2218                (expand-file-name "tm-draft" mime/tmp-dir))))
2219          (separator mail-header-separator)
2220          (id (concat "\""
2221                      (replace-space-with-underline (current-time-string))
2222                      "@" (system-name) "\"")))
2223     (run-hooks 'mime-editor/before-split-hook)
2224     (let ((the-buf (current-buffer))
2225           (copy-buf (get-buffer-create " *Original Message*"))
2226           (header (std11-header-string-except
2227                    mime-editor/split-ignored-field-regexp separator))
2228           (subject (mail-fetch-field "subject"))
2229           (total (+ (/ lines mime-editor/message-max-length)
2230                     (if (> (mod lines mime-editor/message-max-length) 0)
2231                         1)))
2232           (command
2233            (or cmd
2234                (cdr
2235                 (assq major-mode
2236                       mime-editor/split-message-sender-alist))
2237                (function
2238                 (lambda ()
2239                   (interactive)
2240                   (error "Split sender is not specified for `%s'." major-mode)
2241                   ))
2242                ))
2243           (mime-editor/partial-number 1)
2244           data)
2245       (save-excursion
2246         (set-buffer copy-buf)
2247         (erase-buffer)
2248         (insert-buffer the-buf)
2249         (save-restriction
2250           (if (re-search-forward
2251                (concat "^" (regexp-quote separator) "$") nil t)
2252               (let ((he (match-beginning 0)))
2253                 (replace-match "")
2254                 (narrow-to-region (point-min) he)
2255                 ))
2256           (goto-char (point-min))
2257           (while (re-search-forward mime-editor/split-blind-field-regexp nil t)
2258             (delete-region (match-beginning 0)
2259                            (1+ (std11-field-end)))
2260             )))
2261       (while (< mime-editor/partial-number total)
2262         (erase-buffer)
2263         (save-excursion
2264           (set-buffer copy-buf)
2265           (setq data (buffer-substring
2266                       (point-min)
2267                       (progn
2268                         (goto-line mime-editor/message-max-length)
2269                         (point))
2270                       ))
2271           (delete-region (point-min)(point))
2272           )
2273         (mime-editor/insert-partial-header
2274          header subject id mime-editor/partial-number total separator)
2275         (insert data)
2276         (save-excursion
2277           (message (format "Sending %d/%d..."
2278                            mime-editor/partial-number total))
2279           (call-interactively command)
2280           (message (format "Sending %d/%d... done"
2281                            mime-editor/partial-number total))
2282           )
2283         (setq mime-editor/partial-number
2284               (1+ mime-editor/partial-number))
2285         )
2286       (erase-buffer)
2287       (save-excursion
2288         (set-buffer copy-buf)
2289         (setq data (buffer-string))
2290         (erase-buffer)
2291         )
2292       (mime-editor/insert-partial-header
2293        header subject id mime-editor/partial-number total separator)
2294       (insert data)
2295       (save-excursion
2296         (message (format "Sending %d/%d..."
2297                          mime-editor/partial-number total))
2298         (message (format "Sending %d/%d... done"
2299                          mime-editor/partial-number total))
2300         )
2301       )))
2302
2303 (defun mime-editor/maybe-split-and-send (&optional cmd)
2304   (interactive)
2305   (run-hooks 'mime-editor/before-send-hook)
2306   (let ((mime-editor/message-max-length
2307          (or (cdr (assq major-mode mime-editor/message-max-lines-alist))
2308              mime-editor/message-default-max-lines))
2309         (lines (count-lines (point-min) (point-max)))
2310         )
2311     (if (and (> lines mime-editor/message-max-length)
2312              mime-editor/split-message)
2313         (mime-editor/split-and-send cmd lines mime-editor/message-max-length)
2314       )))
2315
2316
2317 ;;; @ preview message
2318 ;;;
2319
2320 (defun mime-editor/preview-message ()
2321   "preview editing MIME message. [tm-edit.el]"
2322   (interactive)
2323   (let* ((str (buffer-string))
2324          (separator mail-header-separator)
2325          (the-buf (current-buffer))
2326          (buf-name (buffer-name))
2327          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2328          (buf (get-buffer temp-buf-name))
2329          )
2330     (if buf
2331         (progn
2332           (switch-to-buffer buf)
2333           (erase-buffer)
2334           )
2335       (setq buf (get-buffer-create temp-buf-name))
2336       (switch-to-buffer buf)
2337       )
2338     (insert str)
2339     (setq major-mode 'mime/temporary-message-mode)
2340     (make-local-variable 'mail-header-separator)
2341     (setq mail-header-separator separator)
2342     (make-local-variable 'mime/editing-buffer)
2343     (setq mime/editing-buffer the-buf)
2344     
2345     (run-hooks 'mime-editor/translate-hook)
2346     (mime-editor/translate-buffer)
2347     (goto-char (point-min))
2348     (if (re-search-forward
2349          (concat "^" (regexp-quote separator) "$"))
2350         (replace-match "")
2351       )
2352     (mime/viewer-mode)
2353     ))
2354
2355 (defun mime-editor/quitting-method ()
2356   (let ((temp mime::preview/article-buffer)
2357         buf)
2358     (mime-viewer/kill-buffer)
2359     (set-buffer temp)
2360     (setq buf mime/editing-buffer)
2361     (kill-buffer temp)
2362     (switch-to-buffer buf)
2363     ))
2364
2365 (set-alist 'mime-viewer/quitting-method-alist
2366            'mime/temporary-message-mode
2367            (function mime-editor/quitting-method)
2368            )
2369
2370
2371 ;;; @ draft preview
2372 ;;; 
2373 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2374 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2375
2376 (defvar mime-editor/draft-header-separator-alist
2377   '((news-reply-mode . mail-header-separator)
2378     (mh-letter-mode . mail-header-separator)
2379     ))
2380
2381 (defvar mime::article/draft-header-separator nil)
2382
2383 (defun mime-editor/draft-preview ()
2384   (interactive)
2385   (let ((sep (cdr (assq major-mode mime-editor/draft-header-separator-alist))))
2386     (or (stringp sep) (setq sep (eval sep)))
2387     (make-variable-buffer-local 'mime::article/draft-header-separator)
2388     (goto-char (point-min))
2389     (re-search-forward
2390      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2391     (setq mime::article/draft-header-separator
2392           (buffer-substring (match-beginning 0) (match-end 0)))
2393     (replace-match "")
2394     (mime/viewer-mode (current-buffer))
2395     (pop-to-buffer (current-buffer))
2396     ))
2397
2398 (defun mime-viewer::quitting-method/draft-preview ()
2399   (let ((mother mime::preview/mother-buffer))
2400     (save-excursion
2401       (switch-to-buffer mother)
2402       (goto-char (point-min))
2403       (if (and
2404            (re-search-forward
2405             (concat "^\\("
2406                     (regexp-quote mime::article/draft-header-separator)
2407                     "\\)?$") nil t)
2408            (bolp))
2409           (progn
2410             (insert mime::article/draft-header-separator)
2411             (set-buffer-modified-p (buffer-modified-p))
2412             )))
2413     (mime-viewer/kill-buffer)
2414     (pop-to-buffer mother)
2415     ))
2416
2417 (set-alist 'mime-viewer/quitting-method-alist
2418            'mh-letter-mode
2419            (function mime-viewer::quitting-method/draft-preview)
2420            )
2421
2422 (set-alist 'mime-viewer/quitting-method-alist
2423            'news-reply-mode
2424            (function mime-viewer::quitting-method/draft-preview)
2425            )
2426
2427
2428 ;;; @ edit again
2429 ;;;
2430
2431 (defun mime-editor::edit-again (code-conversion)
2432   (save-excursion
2433     (goto-char (point-min))
2434     (let ((ctl (mime/Content-Type)))
2435       (if ctl
2436           (let ((ctype (car ctl))
2437                 (params (cdr ctl))
2438                 type stype)
2439             (if (string-match "/" ctype)
2440                 (progn
2441                   (setq type (substring ctype 0 (match-beginning 0)))
2442                   (setq stype (substring ctype (match-end 0)))
2443                   )
2444               (setq type ctype)
2445               )
2446             (cond
2447              ((string-equal type "multipart")
2448               (let* ((boundary (assoc-value "boundary" params))
2449                      (boundary-pat
2450                       (concat "\n--" (regexp-quote boundary) "[ \t]*\n"))
2451                      )
2452                 (re-search-forward boundary-pat nil t)
2453                 (let ((bb (match-beginning 0)) eb tag)
2454                   (setq tag (format "\n--<<%s>>-{\n" stype))
2455                   (goto-char bb)
2456                   (insert tag)
2457                   (setq bb (+ bb (length tag)))
2458                   (re-search-forward
2459                    (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2460                    nil t)
2461                   (setq eb (match-beginning 0))
2462                   (replace-match (format "--}-<<%s>>\n" stype))
2463                   (save-restriction
2464                     (narrow-to-region bb eb)
2465                     (goto-char (point-min))
2466                     (while (re-search-forward boundary-pat nil t)
2467                       (let ((beg (match-beginning 0))
2468                             end)
2469                         (delete-region beg (match-end 0))
2470                         (save-excursion
2471                           (if (re-search-forward boundary-pat nil t)
2472                               (setq end (match-beginning 0))
2473                             (setq end (point-max))
2474                             )
2475                           (save-restriction
2476                             (narrow-to-region beg end)
2477                             (mime-editor::edit-again code-conversion)
2478                             (goto-char (point-max))
2479                             ))))
2480                     ))
2481                 (goto-char (point-min))
2482                 (or (= (point-min) 1)
2483                     (delete-region (point-min)
2484                                    (if (search-forward "\n\n" nil t)
2485                                        (match-end 0)
2486                                      (point-min)
2487                                      )))
2488                 ))
2489              (t
2490               (let* (charset
2491                      (pstr
2492                       (let ((bytes (+ 14 (length ctype))))
2493                         (mapconcat (function
2494                                     (lambda (attr)
2495                                       (if (string-equal (car attr) "charset")
2496                                           (progn
2497                                             (setq charset (cdr attr))
2498                                             "")
2499                                         (let* ((str
2500                                                 (concat (car attr)
2501                                                         "=" (cdr attr))
2502                                                 )
2503                                                (bs (length str))
2504                                                )
2505                                           (setq bytes (+ bytes bs 2))
2506                                           (if (< bytes 76)
2507                                               (concat "; " str)
2508                                             (setq bytes (+ bs 1))
2509                                             (concat ";\n " str)
2510                                             )
2511                                           ))))
2512                                    params "")))
2513                      encoding
2514                      encoded)
2515                 (save-excursion
2516                   (if (re-search-forward
2517                        "Content-Transfer-Encoding:" nil t)
2518                       (let ((beg (match-beginning 0))
2519                             (hbeg (match-end 0))
2520                             (end (std11-field-end)))
2521                         (setq encoding
2522                               (eliminate-top-spaces
2523                                (std11-unfold-string
2524                                 (buffer-substring hbeg end))))
2525                         (if (or charset (string-equal type "text"))
2526                             (progn
2527                               (delete-region beg (1+ end))
2528                               (goto-char (point-min))
2529                               (if (search-forward "\n\n" nil t)
2530                                   (progn
2531                                     (mime-decode-region
2532                                      (match-end 0)(point-max) encoding)
2533                                     (setq encoded t
2534                                           encoding nil)
2535                                     )))))))
2536                 (if (or code-conversion encoded)
2537                     (decode-mime-charset-region
2538                      (point-min)(point-max)
2539                      (or charset default-mime-charset))
2540                   )
2541                 (let ((he
2542                        (if (re-search-forward "^$" nil t)
2543                            (match-end 0)
2544                          (point-min)
2545                          )))
2546                   (if (= (point-min) 1)
2547                       (progn
2548                         (goto-char he)
2549                         (insert
2550                          (concat "\n"
2551                                  (mime-create-tag
2552                                   (concat type "/" stype pstr) encoding)))
2553                         )
2554                     (delete-region (point-min) he)
2555                     (insert
2556                      (mime-create-tag
2557                       (concat type "/" stype pstr) encoding))
2558                     ))
2559                 ))))
2560         (if code-conversion
2561             (decode-mime-charset-region (point-min) (point-max)
2562                                         default-mime-charset)
2563           )
2564         ))))
2565
2566 (defun mime/edit-again (&optional code-conversion no-separator no-mode)
2567   (interactive)
2568   (mime-editor::edit-again code-conversion)
2569   (goto-char (point-min))
2570   (save-restriction
2571     (narrow-to-region
2572      (point-min)
2573      (if (re-search-forward
2574           (concat "^\\(" (regexp-quote mail-header-separator) "\\)?$")
2575           nil t)
2576          (match-end 0)
2577        (point-max)
2578        ))
2579     (goto-char (point-min))
2580     (while (re-search-forward
2581             "^\\(Content-.*\\|Mime-Version\\):" nil t)
2582       (delete-region (match-beginning 0) (1+ (std11-field-end)))
2583       ))
2584   (or no-separator
2585       (and (re-search-forward "^$")
2586            (replace-match mail-header-separator)
2587            ))
2588   (or no-mode
2589       (mime/editor-mode)
2590       ))
2591
2592
2593 ;;; @ end
2594 ;;;
2595
2596 (provide 'tm-edit)
2597
2598 (run-hooks 'tm-edit-load-hook)
2599
2600 ;;; tm-edit.el ends here