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