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