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