tm 7.64.
[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.63 $
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.63 1996/05/22 02:25:54 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" "Approved" "Path" "Replied" "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 start (point-max) encoding)
1084           ))
1085       (if hide-p
1086           (progn
1087             (mime-flag-region (point-min) (1- (point-max)) ?\^M)
1088             (goto-char (point-max)))
1089         ))
1090     ;; Define encoding even if it is 7bit.
1091     (if (stringp encoding)
1092         (save-excursion
1093           (goto-char tagend)            ;Make sure which line the tag is on.
1094           (mime-editor/define-encoding encoding)))
1095     ))
1096
1097 \f
1098 ;; Commands work on a current message flagment.
1099
1100 (defun mime-editor/goto-tag ()
1101   "Search for the beginning of the tagged MIME message."
1102   (let ((current (point)) multipart)
1103     (if (looking-at mime-editor/tag-regexp)
1104         t
1105       ;; At first, go to the end.
1106       (cond ((re-search-forward mime-editor/beginning-tag-regexp nil t)
1107              (goto-char (match-beginning 0)) ;For multiline tag
1108              (forward-line -1)
1109              (end-of-line)
1110              )
1111             (t
1112              (goto-char (point-max))
1113              ))
1114       ;; Then search for the beginning. 
1115       (re-search-backward mime-editor/end-tag-regexp nil t)
1116       (beginning-of-line)
1117       (or (looking-at mime-editor/beginning-tag-regexp)
1118           ;; Restore previous point.
1119           (progn
1120             (goto-char current)
1121             nil
1122             ))
1123       )))
1124
1125 (defun mime-editor/content-beginning ()
1126   "Return the point of the beginning of content."
1127   (save-excursion
1128     (let ((beg (save-excursion
1129                  (beginning-of-line) (point))))
1130       (if (mime-editor/goto-tag)
1131           (let ((top (point)))
1132             (goto-char (match-end 0))
1133             (if (and (= beg top)
1134                      (= (following-char) ?\^M))
1135                 (point)
1136               (forward-line 1)
1137               (point)))
1138         ;; Default text/plain tag.
1139         (goto-char (point-min))
1140         (re-search-forward
1141          (concat "\n" (regexp-quote mail-header-separator)
1142                  (if mime-ignore-preceding-spaces
1143                      "[ \t\n]*\n" "\n")) nil 'move)
1144         (point))
1145       )))
1146
1147 (defun mime-editor/content-end ()
1148   "Return the point of the end of content."
1149   (save-excursion
1150     (let ((beg (save-excursion
1151                  (beginning-of-line) (point))))
1152       (if (mime-editor/goto-tag)
1153           (let ((top (point)))
1154             (goto-char (match-end 0))
1155             (if (and (= beg top)        ;Must be on the same line.
1156                      (= (following-char) ?\^M))
1157                 (progn
1158                   (end-of-line)
1159                   (point))
1160               ;; Move to the end of this text.
1161               (if (re-search-forward mime-editor/tag-regexp nil 'move)
1162                   ;; Don't forget a multiline tag.
1163                   (goto-char (match-beginning 0)))
1164               (point)
1165               ))
1166         ;; Assume the message begins with text/plain.
1167         (goto-char (mime-editor/content-beginning))
1168         (if (re-search-forward mime-editor/tag-regexp nil 'move)
1169             ;; Don't forget a multiline tag.
1170             (goto-char (match-beginning 0)))
1171         (point))
1172       )))
1173
1174 (defun mime-editor/define-charset (charset)
1175   "Set charset of current tag to CHARSET."
1176   (save-excursion
1177     (if (mime-editor/goto-tag)
1178         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1179           (delete-region (match-beginning 0) (match-end 0))
1180           (insert
1181            (mime-create-tag (mime-set-parameter
1182                              (mime-editor/get-contype tag) "charset" charset)
1183                             (mime-editor/get-encoding tag))))
1184       )))
1185
1186 (defun mime-editor/define-encoding (encoding)
1187   "Set encoding of current tag to ENCODING."
1188   (save-excursion
1189     (if (mime-editor/goto-tag)
1190         (let ((tag (buffer-substring (match-beginning 0) (match-end 0))))
1191           (delete-region (match-beginning 0) (match-end 0))
1192           (insert (mime-create-tag (mime-editor/get-contype tag) encoding)))
1193       )))
1194
1195 (defun mime-editor/choose-charset ()
1196   "Choose charset of a text following current point."
1197   (mime/find-charset-region (point) (mime-editor/content-end))
1198   )
1199
1200 (defun mime-make-text-tag (&optional subtype)
1201   "Make a tag for a text after current point.
1202 Subtype of text type can be specified by an optional argument SUBTYPE.
1203 Otherwise, it is obtained from mime-content-types."
1204   (let* ((pritype "text")
1205          (subtype (or subtype
1206                       (car (car (cdr (assoc pritype mime-content-types)))))))
1207     ;; Charset should be defined later.
1208     (mime-make-tag pritype subtype)))
1209
1210 \f
1211 ;; Tag handling functions
1212
1213 (defun mime-make-tag (pritype subtype &optional parameters encoding)
1214   "Make a tag of MIME message of PRITYPE, SUBTYPE and optional PARAMETERS."
1215   (mime-create-tag (concat (or pritype "") "/" (or subtype "")
1216                            (or parameters ""))
1217                    encoding))
1218
1219 (defun mime-create-tag (contype &optional encoding)
1220   "Make a tag with CONTENT-TYPE and optional ENCODING."
1221   (format (if encoding mime-tag-format-with-encoding mime-tag-format)
1222           contype encoding))
1223
1224 (defun mime-editor/get-contype (tag)
1225   "Return Content-Type (including parameters) of TAG."
1226   (and (stringp tag)
1227        (or (string-match mime-editor/single-part-tag-regexp tag)
1228            (string-match mime-editor/multipart-beginning-regexp tag)
1229            (string-match mime-editor/multipart-end-regexp tag)
1230            )
1231        (substring tag (match-beginning 1) (match-end 1))
1232        ))
1233
1234 (defun mime-editor/get-encoding (tag)
1235   "Return encoding of TAG."
1236   (and (stringp tag)
1237        (string-match mime-editor/single-part-tag-regexp tag)
1238        (match-beginning 3)
1239        (not (= (match-beginning 3) (match-end 3)))
1240        (substring tag (match-beginning 3) (match-end 3))))
1241
1242 (defun mime-get-parameter (contype parameter)
1243   "For given CONTYPE return value for PARAMETER.
1244 Nil if no such parameter."
1245   (if (string-match
1246        (concat
1247         ";[ \t\n]*"
1248         (regexp-quote parameter)
1249         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\([ \t\n]*;\\|$\\)")
1250        contype)
1251       (substring contype (match-beginning 1) (match-end 1))
1252     nil                                 ;No such parameter
1253     ))
1254
1255 (defun mime-set-parameter (contype parameter value)
1256   "For given CONTYPE set PARAMETER to VALUE."
1257   (if (string-match
1258        (concat
1259         ";[ \t\n]*\\("
1260         (regexp-quote parameter)
1261         "[ \t\n]*=[ \t\n]*\\([^\" \t\n;]*\\|\"[^\"]*\"\\)\\)[ \t\n]*\\(;\\|$\\)")
1262        contype)
1263       ;; Change value
1264       (concat (substring contype 0 (match-beginning 1))
1265               parameter "=" value
1266               (substring contype (match-end 1)))
1267     (concat contype "; " parameter "=" value)))
1268
1269 (defun mime-strip-parameters (contype)
1270   "Return primary content-type and subtype without parameters for CONTYPE."
1271   (if (string-match "^[ \t]*\\([^; \t\n]*\\)" contype)
1272       (substring contype (match-beginning 1) (match-end 1)) nil))
1273
1274 (defun mime-test-content-type (contype type &optional subtype)
1275   "Test if CONTYPE is a TYPE and an optional SUBTYPE."
1276   (and (stringp contype)
1277        (stringp type)
1278        (string-match
1279         (concat "^[ \t]*" (downcase type) "/" (downcase (or subtype "")))
1280         (downcase contype))))
1281
1282 \f
1283 ;; Basic functions
1284
1285 (defun mime-find-file-type (file)
1286   "Guess Content-Type, subtype, and parameters from FILE."
1287   (let ((guess nil)
1288         (guesses mime-file-types))
1289     (while (and (not guess) guesses)
1290       (if (string-match (car (car guesses)) file)
1291           (setq guess (cdr (car guesses))))
1292       (setq guesses (cdr guesses)))
1293     guess
1294     ))
1295
1296 (defun mime-prompt-for-type ()
1297   "Ask for Content-type."
1298   (let ((type ""))
1299     ;; Repeat until primary content type is specified.
1300     (while (string-equal type "")
1301       (setq type
1302             (completing-read "What content type: "
1303                              mime-content-types
1304                              nil
1305                              'require-match ;Type must be specified.
1306                              nil
1307                              ))
1308       (if (string-equal type "")
1309           (progn
1310             (message "Content type is required.")
1311             (beep)
1312             (sit-for 1)
1313             ))
1314       )
1315     type
1316     ))
1317
1318 (defun mime-prompt-for-subtype (pritype)
1319   "Ask for Content-type subtype of Content-Type PRITYPE."
1320   (let* ((default (car (car (cdr (assoc pritype mime-content-types)))))
1321          (answer
1322           (completing-read
1323            (if default
1324                (concat
1325                 "What content subtype: (default " default ") ")
1326              "What content subtype: ")
1327            (cdr (assoc pritype mime-content-types))
1328            nil
1329            'require-match               ;Subtype must be specified.
1330            nil
1331            )))
1332     (if (string-equal answer "") default answer)))
1333
1334 (defun mime-prompt-for-parameters (pritype subtype &optional delimiter)
1335   "Ask for Content-type parameters of Content-Type PRITYPE and SUBTYPE.
1336 Optional DELIMITER specifies parameter delimiter (';' by default)."
1337   (let* ((delimiter (or delimiter "; "))
1338          (parameters
1339           (mapconcat
1340            (function identity)
1341            (delq nil
1342                  (mime-prompt-for-parameters-1
1343                   (cdr (assoc subtype
1344                               (cdr (assoc pritype mime-content-types))))))
1345            delimiter
1346            )))
1347     (if (and (stringp parameters)
1348              (not (string-equal parameters "")))
1349         (concat delimiter parameters)
1350       ""                                ;"" if no parameters
1351       )))
1352
1353 (defun mime-prompt-for-parameters-1 (optlist)
1354   (apply (function append)
1355          (mapcar (function mime-prompt-for-parameter) optlist)))
1356
1357 (defun mime-prompt-for-parameter (parameter)
1358   "Ask for PARAMETER.
1359 Parameter must be '(PROMPT CHOICE1 (CHOISE2 ...))."
1360   (let* ((prompt (car parameter))
1361          (choices (mapcar (function
1362                            (lambda (e)
1363                              (if (consp e) e (list e))))
1364                           (cdr parameter)))
1365          (default (car (car choices)))
1366          (answer nil))
1367     (if choices
1368         (progn
1369           (setq answer
1370                 (completing-read
1371                  (concat "What " prompt
1372                          ": (default "
1373                          (if (string-equal default "") "\"\"" default)
1374                          ") ")
1375                  choices nil nil ""))
1376           ;; If nothing is selected, use default.
1377           (if (string-equal answer "")
1378               (setq answer default)))
1379       (setq answer
1380             (read-string (concat "What " prompt ": "))))
1381     (cons (if (and answer
1382                    (not (string-equal answer "")))
1383               (concat prompt "="
1384                       ;; Note: control characters ignored!
1385                       (if (string-match mime-tspecials-regexp answer)
1386                           (concat "\"" answer "\"") answer)))
1387           (mime-prompt-for-parameters-1 (cdr (assoc answer (cdr parameter)))))
1388     ))
1389
1390 (defun mime-flag-region (from to flag)
1391   "Hides or shows lines from FROM to TO, according to FLAG.
1392 If FLAG is `\\n' (newline character) then text is shown,
1393 while if FLAG is `\\^M' (control-M) the text is hidden."
1394   (let ((buffer-read-only nil)          ;Okay even if write protected.
1395         (modp (buffer-modified-p)))
1396     (unwind-protect
1397         (subst-char-in-region from to
1398                               (if (= flag ?\n) ?\^M ?\n)
1399                               flag t)
1400       (set-buffer-modified-p modp))))
1401
1402 \f
1403 ;;; @ Translate the tagged MIME messages into a MIME compliant message.
1404 ;;;
1405
1406 (defvar mime-editor/translate-buffer-hook
1407   '(mime-editor/pgp-enclose-buffer
1408     mime/encode-message-header
1409     mime-editor/translate-body))
1410
1411 (defun mime-editor/translate-buffer ()
1412   "Encode the tagged MIME message in current buffer in MIME compliant message."
1413   (interactive)
1414   (if (catch 'mime-editor/error
1415         (save-excursion
1416           (run-hooks 'mime-editor/translate-buffer-hook)
1417           ))
1418       (progn
1419         (undo)
1420         (error "Translation error!")
1421         )))
1422
1423 (defun mime-editor/find-inmost ()
1424   (goto-char (point-min))
1425   (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1426       (let ((bb (match-beginning 0))
1427             (be (match-end 0))
1428             (type (buffer-substring (match-beginning 1)(match-end 1)))
1429             end-exp eb ee)
1430         (setq end-exp (format "^--}-<<%s>>\n" type))
1431         (widen)
1432         (if (re-search-forward end-exp nil t)
1433             (progn
1434               (setq eb (match-beginning 0))
1435               (setq ee (match-end 0))
1436               )
1437           (setq eb (point-max))
1438           (setq ee (point-max))
1439           )
1440         (narrow-to-region be eb)
1441         (goto-char be)
1442         (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1443             (let (ret)
1444               (narrow-to-region (match-beginning 0)(point-max))
1445               (mime-editor/find-inmost)
1446               )
1447           (widen)
1448           ;;(delete-region eb ee)
1449           (list type bb be eb)
1450           ))))
1451
1452 (defun mime-editor/process-multipart-1 (boundary)
1453   (let ((ret (mime-editor/find-inmost)))
1454     (if ret
1455         (let ((type (car ret))
1456               (bb (nth 1 ret))(be (nth 2 ret))
1457               (eb (nth 3 ret))
1458               )
1459           (narrow-to-region bb eb)
1460           (delete-region bb be)
1461           (setq bb (point-min))
1462           (setq eb (point-max))
1463           (widen)
1464           (goto-char eb)
1465           (if (looking-at mime-editor/multipart-end-regexp)
1466               (let ((beg (match-beginning 0))
1467                     (end (match-end 0))
1468                     )
1469                 (delete-region beg end)
1470                 (if (and (not (looking-at mime-editor/single-part-tag-regexp))
1471                          (not (eobp)))
1472                     (insert (concat (mime-make-text-tag) "\n"))
1473                   )))
1474           (cond ((string= type "signed")
1475                  (cond ((eq mime-editor/signing-type 'pgp-elkins)
1476                         (mime-editor/sign-pgp-elkins bb eb boundary)
1477                         )
1478                        ((eq mime-editor/signing-type 'pgp-kazu)
1479                         (mime-editor/sign-pgp-kazu bb eb boundary)
1480                         )
1481                        ))
1482                 ((string= type "encrypted")
1483                  (cond ((eq mime-editor/encrypting-type 'pgp-elkins)
1484                         (mime-editor/encrypt-pgp-elkins bb eb boundary)
1485                         )
1486                        ((eq mime-editor/encrypting-type 'pgp-kazu)
1487                         (mime-editor/encrypt-pgp-kazu bb eb boundary)
1488                         )))
1489                 (t
1490                  (setq boundary
1491                        (nth 2 (mime-editor/translate-region bb eb
1492                                                             boundary t)))
1493                  (goto-char bb)
1494                  (insert
1495                   (format "--[[multipart/%s;
1496  boundary=\"%s\"][7bit]]\n"
1497                           type boundary))
1498                  ))
1499           boundary))))
1500
1501
1502 (autoload 'mc-pgp-lookup-key "mc-pgp")
1503 (autoload 'mc-pgp-sign-region "mc-pgp")
1504 (autoload 'mc-pgp-encrypt-region "mc-pgp")
1505
1506 (defun tm:mc-pgp-generic-parser (result)
1507   (let ((ret (mc-pgp-generic-parser result)))
1508     (if (consp ret)
1509         (vector (car ret)(cdr ret))
1510       )))
1511
1512 (defun tm:mc-process-region
1513   (beg end passwd program args parser &optional buffer boundary)
1514   (let ((obuf (current-buffer))
1515         (process-connection-type nil)
1516         mybuf result rgn proc)
1517     (unwind-protect
1518         (progn
1519           (setq mybuf (or buffer (generate-new-buffer " *mailcrypt temp")))
1520           (set-buffer mybuf)
1521           (erase-buffer)
1522           (set-buffer obuf)
1523           (buffer-disable-undo mybuf)
1524           (setq proc
1525                 (apply 'start-process "*PGP*" mybuf program args))
1526           (if passwd
1527               (progn
1528                 (process-send-string proc (concat passwd "\n"))
1529                 (or mc-passwd-timeout (mc-deactivate-passwd t))))
1530           (process-send-region proc beg end)
1531           (process-send-eof proc)
1532           (while (eq 'run (process-status proc))
1533             (accept-process-output proc 5))
1534           (setq result (process-exit-status proc))
1535           ;; Hack to force a status_notify() in Emacs 19.29
1536           (delete-process proc)
1537           (set-buffer mybuf)
1538           (goto-char (point-max))
1539           (if (re-search-backward "\nProcess \\*PGP.*\n\\'" nil t)
1540               (delete-region (match-beginning 0) (match-end 0)))
1541           (goto-char (point-min))
1542           ;; CRNL -> NL
1543           (while (search-forward "\r\n" nil t)
1544             (replace-match "\n"))
1545           ;; Hurm.  FIXME; must get better result codes.
1546           (if (stringp result)
1547               (error "%s exited abnormally: '%s'" program result)
1548             (setq rgn (funcall parser result))
1549             ;; If the parser found something, migrate it
1550             (if (consp rgn)
1551                 (progn
1552                   (set-buffer obuf)
1553                   (if boundary
1554                       (save-restriction
1555                         (narrow-to-region beg end)
1556                         (goto-char beg)
1557                         (insert (format "--%s\n" boundary))
1558                         (goto-char (point-max))
1559                         (insert (format "\n--%s
1560 Content-Type: application/pgp-signature
1561 Content-Transfer-Encoding: 7bit
1562
1563 " boundary))
1564                         (insert-buffer-substring mybuf (car rgn) (cdr rgn))
1565                         (goto-char (point-max))
1566                         (insert (format "\n--%s--\n" boundary))
1567                         )
1568                     (delete-region beg end)
1569                     (goto-char beg)
1570                     (insert-buffer-substring mybuf (car rgn) (cdr rgn))
1571                     )
1572                   (set-buffer mybuf)
1573                   (delete-region (car rgn) (cdr rgn)))))
1574           ;; Return nil on failure and exit code on success
1575           (if rgn result))
1576       ;; Cleanup even on nonlocal exit
1577       (if (and proc (eq 'run (process-status proc)))
1578           (interrupt-process proc))
1579       (set-buffer obuf)
1580       (or buffer (null mybuf) (kill-buffer mybuf)))))
1581
1582 (defun tm:mc-pgp-sign-region (start end &optional id unclear boundary)
1583   (if (not (boundp 'mc-pgp-user-id))
1584       (load "mc-pgp")
1585     )
1586   (let ((process-environment process-environment)
1587         (buffer (get-buffer-create mc-buffer-name))
1588         passwd args key
1589         (parser (function mc-pgp-generic-parser))
1590         (pgp-path mc-pgp-path)
1591         )
1592     (setq key (mc-pgp-lookup-key (or id mc-pgp-user-id)))
1593     (setq passwd
1594           (mc-activate-passwd
1595            (cdr key)
1596            (format "PGP passphrase for %s (%s): " (car key) (cdr key))))
1597     (setenv "PGPPASSFD" "0")
1598     (setq args
1599           (cons
1600            (if boundary
1601                "-fbast"
1602              "-fast")
1603            (list "+verbose=1" "+language=en"
1604                  (format "+clearsig=%s" (if unclear "off" "on"))
1605                  "+batchmode" "-u" (cdr key))))
1606     (if mc-pgp-comment
1607         (setq args (cons (format "+comment=%s" mc-pgp-comment) args))
1608       )
1609     (message "Signing as %s ..." (car key))
1610     (if (tm:mc-process-region
1611          start end passwd pgp-path args parser buffer boundary)
1612         (progn
1613           (if boundary
1614               (progn
1615                 (goto-char (point-min))
1616                 (insert
1617                  (format "\
1618 --[[multipart/signed; protocol=\"application/pgp-signature\";
1619  boundary=\"%s\"; micalg=pgp-md5][7bit]]\n" boundary))
1620                 ))
1621           (message "Signing as %s ... Done." (car key))
1622           t)
1623       nil)))
1624
1625 (defun mime-editor/sign-pgp-elkins (beg end boundary)
1626   (save-excursion
1627     (save-restriction
1628       (narrow-to-region beg end)
1629       (let* ((ret
1630               (mime-editor/translate-region beg end boundary))
1631              (ctype    (car ret))
1632              (encoding (nth 1 ret))
1633              (parts    (nth 3 ret))
1634              (pgp-boundary (concat "pgp-sign-" boundary))
1635              )
1636         (goto-char beg)
1637         (insert (format "Content-Type: %s\n" ctype))
1638         (if encoding
1639             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1640           )
1641         (insert "\n")
1642         (or (tm:mc-pgp-sign-region (point-min)(point-max)
1643                                    nil nil pgp-boundary)
1644             (throw 'mime-editor/error 'pgp-error)
1645             )
1646         ))))
1647
1648 (defun mime-editor/encrypt-pgp-elkins (beg end boundary)
1649   (save-excursion
1650     (save-restriction
1651       (let ((from (rfc822/get-field-body "From"))
1652             (to (rfc822/get-field-body "To"))
1653             (cc (rfc822/get-field-body "cc"))
1654             recipients)
1655         (narrow-to-region beg end)
1656         (let* ((ret
1657                 (mime-editor/translate-region beg end boundary))
1658                (ctype    (car ret))
1659                (encoding (nth 1 ret))
1660                (parts    (nth 3 ret))
1661                (pgp-boundary (concat "pgp-" boundary))
1662                )
1663           (goto-char beg)
1664           (if (and (stringp from)
1665                    (not (string-equal from "")))
1666               (insert (format "From: %s\n" from))
1667             )
1668           (if (and (stringp to)
1669                    (not (string-equal to "")))
1670               (progn
1671                 (insert (format "To: %s\n" to))
1672                 (setq recipients to)
1673                 ))
1674           (if (and (stringp cc)
1675                    (not (string-equal cc "")))
1676               (progn
1677                 (insert (format "cc: %s\n" cc))
1678                 (if recipients
1679                     (setq recipients (concat recipients "," cc))
1680                   (setq recipients cc)
1681                   )))
1682           (insert (format "Content-Type: %s\n" ctype))
1683           (if encoding
1684               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1685             )
1686           (insert "\n")
1687           (if (null
1688                (let ((mc-pgp-always-sign 'never))
1689                  (mc-pgp-encrypt-region
1690                   (mc-split "\\([ \t\n]*,[ \t\n]*\\)+" recipients)
1691                   (point-min) (point-max) from nil)
1692                  ))
1693               (throw 'mime-editor/error 'pgp-error)
1694             )
1695           (goto-char beg)
1696           (insert (format "--[[multipart/encrypted;
1697  boundary=\"%s\";
1698  protocol=\"application/pgp-encrypted\"][7bit]]
1699 --%s
1700 Content-Type: application/pgp-encrypted
1701
1702 --%s
1703 Content-Type: application/octet-stream
1704 Content-Transfer-Encoding: 7bit
1705
1706 " pgp-boundary pgp-boundary pgp-boundary))
1707           (goto-char (point-max))
1708           (insert (format "\n--%s--\n" pgp-boundary))
1709           )))))
1710
1711 (defun mime-editor/sign-pgp-kazu (beg end boundary)
1712   (save-excursion
1713     (save-restriction
1714       (narrow-to-region beg end)
1715       (let* ((ret
1716               (mime-editor/translate-region beg end boundary))
1717              (ctype    (car ret))
1718              (encoding (nth 1 ret))
1719              (parts    (nth 3 ret))
1720              )
1721         (goto-char beg)
1722         (insert (format "Content-Type: %s\n" ctype))
1723         (if encoding
1724             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1725           )
1726         (insert "\n")
1727         (or (let ((program-coding-system-alist
1728                    (cons (cons (cons nil ".*pgp.*")
1729                                (cons *noconv* *noconv*))
1730                          program-coding-system-alist))
1731                   )
1732               (mc-pgp-sign-region beg (point-max))
1733               )
1734             (throw 'mime-editor/error 'pgp-error)
1735             )
1736         (goto-char beg)
1737         (insert
1738          "--[[application/pgp; format=mime][7bit]]\n")
1739         ))
1740     ))
1741
1742 (defun mime-editor/encrypt-pgp-kazu (beg end boundary)
1743   (save-excursion
1744     (let ((from (rfc822/get-field-body "From"))
1745           (to (rfc822/get-field-body "To"))
1746           (cc (rfc822/get-field-body "cc"))
1747           recipients)
1748       (save-restriction
1749         (narrow-to-region beg end)
1750         (let* ((ret
1751                 (mime-editor/translate-region beg end boundary))
1752                (ctype    (car ret))
1753                (encoding (nth 1 ret))
1754                (parts    (nth 3 ret))
1755                )
1756           (goto-char beg)
1757           (if (and (stringp from)
1758                    (not (string-equal from "")))
1759               (insert (format "From: %s\n" from))
1760             )
1761           (if (and (stringp to)
1762                    (not (string-equal to "")))
1763               (progn
1764                 (insert (format "To: %s\n" to))
1765                 (setq recipients to)
1766                 ))
1767           (if (and (stringp cc)
1768                    (not (string-equal cc "")))
1769               (progn
1770                 (insert (format "cc: %s\n" cc))
1771                 (if recipients
1772                     (setq recipients (concat recipients "," cc))
1773                   (setq recipients cc)
1774                   )))
1775           (insert (format "Content-Type: %s\n" ctype))
1776           (if encoding
1777               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1778             )
1779           (insert "\n")
1780           (or (let ((program-coding-system-alist
1781                      (cons (cons (cons nil ".*pgp.*")
1782                                  (cons *noconv* *noconv*))
1783                            program-coding-system-alist))
1784                     )
1785                 (mc-pgp-encrypt-region
1786                  (mc-split "\\([ \t\n]*,[ \t\n]*\\)+" recipients)
1787                  beg (point-max))
1788                 )
1789               (throw 'mime-editor/error 'pgp-error)
1790               )
1791           (goto-char beg)
1792           (insert
1793            "--[[application/pgp; format=mime][7bit]]\n")
1794           ))
1795       )))
1796
1797 (defun mime-editor/translate-body ()
1798   "Encode the tagged MIME body in current buffer in MIME compliant message."
1799   (interactive)
1800   (save-excursion
1801     (let ((boundary
1802            (concat mime-multipart-boundary "_"
1803                    (replace-space-with-underline (current-time-string))
1804                    ))
1805           (i 1)
1806           ret)
1807       (while (mime-editor/process-multipart-1
1808               (format "%s-%d" boundary i))
1809         (setq i (1+ i))
1810         )
1811       (save-restriction
1812         ;; We are interested in message body.
1813         (let* ((beg
1814                 (progn
1815                   (goto-char (point-min))
1816                   (re-search-forward
1817                    (concat "\n" (regexp-quote mail-header-separator)
1818                            (if mime-ignore-preceding-spaces
1819                                "[ \t\n]*\n" "\n")) nil 'move)
1820                   (point)))
1821                (end
1822                 (progn
1823                   (goto-char (point-max))
1824                   (and mime-ignore-trailing-spaces
1825                        (re-search-backward "[^ \t\n]\n" beg t)
1826                        (forward-char 1))
1827                   (point))))
1828           (setq ret (mime-editor/translate-region
1829                      beg end
1830                      (format "%s-%d" boundary i)))
1831           ))
1832       (let ((contype (car ret))         ;Content-Type
1833             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1834             )
1835         ;; Make primary MIME headers.
1836         (or (mail-position-on-field "Mime-Version")
1837             (insert mime-editor/mime-version-value))
1838         ;; Remove old Content-Type and other fields.
1839         (save-restriction
1840           (goto-char (point-min))
1841           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1842           (narrow-to-region (point-min) (point))
1843           (goto-char (point-min))
1844           (mime-delete-field "Content-Type")
1845           (mime-delete-field "Content-Transfer-Encoding"))
1846         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1847         (mail-position-on-field "Content-Type")
1848         (insert contype)
1849         (if encoding
1850             (progn
1851               (mail-position-on-field "Content-Transfer-Encoding")
1852               (insert encoding)))
1853         ))))
1854
1855 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1856   (if (null boundary)
1857       (setq boundary
1858             (concat mime-multipart-boundary "_"
1859                     (replace-space-with-underline (current-time-string))))
1860     )
1861   (save-excursion
1862     (save-restriction
1863       (narrow-to-region beg end)
1864       (let ((tag nil)                   ;MIME tag
1865             (contype nil)               ;Content-Type
1866             (encoding nil)              ;Content-Transfer-Encoding
1867             (nparts 0))                 ;Number of body parts
1868         ;; Normalize the body part by inserting appropriate message
1869         ;; tags for every message contents.
1870         (mime-editor/normalize-body)
1871         ;; Counting the number of Content-Type.
1872         (goto-char (point-min))
1873         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1874           (setq nparts (1+ nparts)))
1875         ;; Begin translation.
1876         (cond ((and (<= nparts 1)(not multipart))
1877                ;; It's a singular message.
1878                (goto-char (point-min))
1879                (while (re-search-forward
1880                        mime-editor/single-part-tag-regexp nil t)
1881                  (setq tag
1882                        (buffer-substring (match-beginning 0) (match-end 0)))
1883                  (delete-region (match-beginning 0) (1+ (match-end 0)))
1884                  (setq contype (mime-editor/get-contype tag))
1885                  (setq encoding (mime-editor/get-encoding tag))
1886                  ))
1887               (t
1888                ;; It's a multipart message.
1889                (goto-char (point-min))
1890                (while (re-search-forward
1891                        mime-editor/single-part-tag-regexp nil t)
1892                  (setq tag
1893                        (buffer-substring (match-beginning 0) (match-end 0)))
1894                  (delete-region (match-beginning 0) (match-end 0))
1895                  (setq contype (mime-editor/get-contype tag))
1896                  (setq encoding (mime-editor/get-encoding tag))
1897                  (insert "--" boundary "\n")
1898                  (insert "Content-Type: " contype "\n")
1899                  (if encoding
1900                      (insert "Content-Transfer-Encoding: " encoding "\n"))
1901                  )
1902                ;; Define Content-Type as "multipart/mixed".
1903                (setq contype
1904                      (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1905                ;; Content-Transfer-Encoding must be "7bit".
1906                ;; The following encoding can be `nil', but is
1907                ;; specified as is since there is no way that a user
1908                ;; specifies it.
1909                (setq encoding "7bit")
1910                ;; Insert the trailer.
1911                (goto-char (point-max))
1912                (if multipart
1913                    (insert "--" boundary "--\n")
1914                  (insert "\n--" boundary "--\n")
1915                  )))
1916         (list contype encoding boundary nparts)
1917         ))))
1918
1919 (defun mime-editor/normalize-body ()
1920   "Normalize the body part by inserting appropriate message tags."
1921   ;; Insert the first MIME tags if necessary.
1922   (goto-char (point-min))
1923   (if (not (looking-at mime-editor/single-part-tag-regexp))
1924       (insert (mime-make-text-tag) "\n"))
1925   ;; Check each tag, and add new tag or correct it if necessary.
1926   (goto-char (point-min))
1927   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1928     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1929            (contype (mime-editor/get-contype tag))
1930            (charset (mime-get-parameter contype "charset"))
1931            (encoding (mime-editor/get-encoding tag)))
1932       ;; Remove extra whitespaces after the tag.
1933       (if (looking-at "[ \t]+$")
1934           (delete-region (match-beginning 0) (match-end 0)))
1935       (cond
1936        ((= (following-char) ?\^M)
1937         ;; It must be image, audio or video.
1938         (let ((beg (point))
1939               (end (mime-editor/content-end)))
1940           ;; Insert explicit MIME tags after hidden messages.
1941           (forward-line 1)
1942           (if (and (not (eobp))
1943                    (not (looking-at mime-editor/single-part-tag-regexp)))
1944               (progn
1945                 (insert (mime-make-text-tag) "\n")
1946                 (forward-line -1)       ;Process it again as text.
1947                 ))
1948           ;; Show a hidden message.  The point is not altered
1949           ;; after the conversion.
1950           (mime-flag-region beg end ?\n)
1951           ))
1952        ((mime-test-content-type contype "message")
1953         ;; Content-type "message" should be sent as is.
1954         (forward-line 1)
1955         )
1956        ((mime-test-content-type contype "text")
1957         ;; Define charset for text if necessary.
1958         (setq charset (or charset (mime-editor/choose-charset)))
1959         (mime-editor/define-charset charset)
1960         (cond ((string-equal contype "text/x-rot13-47")
1961                (save-excursion
1962                  (forward-line)
1963                  (set-mark (point))
1964                  (goto-char (mime-editor/content-end))
1965                  (tm:caesar-region)
1966                  ))
1967               ((string-equal contype "text/enriched")
1968                (save-excursion
1969                  (let ((beg (progn
1970                               (forward-line)
1971                               (point)))
1972                        (end (mime-editor/content-end))
1973                        )
1974                    (enriched-encode beg end)
1975                    (goto-char beg)
1976                    (if (search-forward "\n\n")
1977                        (delete-region beg (match-end 0))
1978                      )
1979                    ))))
1980         ;; Point is now on current tag.
1981         ;; Define encoding and encode text if necessary.
1982         (or encoding    ;Encoding is not specified.
1983             (let* ((encoding
1984                     (cdr
1985                      (assoc charset
1986                             mime-editor/charset-default-encoding-alist)
1987                      ))
1988                    (beg (mime-editor/content-beginning))
1989                    )
1990               (mime-charset-encode-region beg (mime-editor/content-end)
1991                                           charset)
1992               (mime-encode-region beg (mime-editor/content-end) encoding)
1993               (mime-editor/define-encoding encoding)
1994               ))
1995         (forward-line 1)
1996         )
1997        ((null encoding)         ;Encoding is not specified.
1998         ;; Application, image, audio, video, and any other
1999         ;; unknown content-type without encoding should be
2000         ;; encoded.
2001         (let* ((encoding "base64")      ;Encode in BASE64 by default.
2002                (beg (mime-editor/content-beginning))
2003                (end (mime-editor/content-end))
2004                (body (buffer-substring beg end))
2005                )
2006           (mime-encode-region beg end encoding)
2007           (mime-editor/define-encoding encoding))
2008         (forward-line 1)
2009         )
2010        )
2011       )))
2012
2013 (defun mime-delete-field (field)
2014   "Delete header FIELD."
2015   (let ((regexp (format "^%s:[ \t]*" field)))
2016     (goto-char (point-min))
2017     (while (re-search-forward regexp nil t)
2018       (delete-region (match-beginning 0)
2019                      (progn (forward-line 1) (point)))
2020       )))
2021
2022 \f
2023 ;;;
2024 ;;; Platform dependent functions
2025 ;;;
2026
2027 ;; Sun implementations
2028
2029 (defun mime-voice-recorder-for-sun ()
2030   "Record voice in a buffer using Sun audio device, and return the buffer.
2031 If the environment variable AUDIOHOST is defined, its value is used as
2032 a recording host instead of local host."
2033   (let ((buffer (get-buffer-create " *MIME audio*"))
2034         (host (getenv "AUDIOHOST")))
2035     (message "Start the recording on %s.  Type C-g to finish the recording..."
2036              (or host (system-name)))
2037     (save-excursion
2038       (set-buffer buffer)
2039       (erase-buffer)
2040       (condition-case errorcode
2041           (let ((selective-display nil) ;Disable ^M to nl translation.
2042                 (mc-flag nil)           ;Mule
2043                 (kanji-flag nil))       ;NEmacs
2044             ;; If AUDIOHOST is defined, use the value as recording host.
2045             (cond ((not (null host))
2046                    ;; Disable automatic conversion of coding system if Mule.
2047                    (if (featurep 'mule)
2048                        (define-program-coding-system nil "rsh" *noconv*))
2049                    (call-process "rsh"
2050                                  nil
2051                                  buffer
2052                                  nil
2053                                  host
2054                                  "cat"
2055                                  "/dev/audio"
2056                                  ))
2057                   (t
2058                    ;; Disable automatic conversion of coding system if Mule.
2059                    (if (featurep 'mule)
2060                        (define-program-coding-system nil "cat" *noconv*))
2061                    (call-process "cat"
2062                                  "/dev/audio"
2063                                  buffer
2064                                  nil
2065                                  ))))
2066         (quit (message "Type C-g to finish recording... done.")
2067               buffer                    ;Return the buffer
2068               )))))
2069
2070 \f
2071 ;;; @ Other useful commands.
2072 ;;;
2073
2074 ;; Message forwarding commands as content-type "message/rfc822".
2075
2076 (defun mime-editor/insert-message (&optional message)
2077   (interactive)
2078   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
2079     (if (and inserter (fboundp inserter))
2080         (progn
2081           (mime-editor/insert-tag "message" "rfc822")
2082           (funcall inserter message)
2083           )
2084       (message "Sorry, I don't have message inserter for your MUA.")
2085       )))
2086
2087 (defun mime-editor/insert-mail (&optional message)
2088   (interactive)
2089   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
2090     (if (and inserter (fboundp inserter))
2091         (progn
2092           (mime-editor/insert-tag "message" "rfc822")
2093           (funcall inserter message)
2094           )
2095       (message "Sorry, I don't have mail inserter for your MUA.")
2096       )))
2097
2098 (defun mime-editor/inserted-message-filter ()
2099   (save-excursion
2100     (save-restriction
2101       (let ((header-start (point))
2102             (case-fold-search t)
2103             beg end)
2104         ;; for Emacs 18
2105         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2106         (if (re-search-forward "^$" (mark t))
2107             (narrow-to-region header-start (match-beginning 0))
2108           )
2109         (goto-char header-start)
2110         (while (and (re-search-forward
2111                      mime-editor/yank-ignored-field-regexp nil t)
2112                     (setq beg (match-beginning 0))
2113                     (setq end (1+ (rfc822/field-end)))
2114                     )
2115           (delete-region beg end)
2116           )
2117         ))))
2118
2119
2120 ;;; @ multipart enclosure
2121 ;;;
2122
2123 (defun mime-editor/enclose-region (type beg end)
2124   (save-excursion
2125     (goto-char beg)
2126     (let ((current (point))
2127           exist-prev-tag)
2128       (save-excursion
2129         (if (mime-editor/goto-tag)
2130             (or (eq current (match-beginning 0))
2131                 (setq exist-prev-tag t)
2132                 )))
2133       (save-restriction
2134         (narrow-to-region beg end)
2135         (goto-char beg)
2136         (if exist-prev-tag
2137             (insert "\n")
2138           )
2139         (insert (format "--<<%s>>-{\n" type))
2140         (goto-char (point-max))
2141         (insert (format "\n--}-<<%s>>\n" type))
2142         (goto-char (point-max))
2143         )
2144       (if (and (not (looking-at mime-editor/single-part-tag-regexp))
2145                (not (eobp)))
2146           (insert (mime-make-text-tag) "\n")
2147         )
2148       )))
2149
2150 (defun mime-editor/enclose-mixed-region (beg end)
2151   (interactive "*r")
2152   (mime-editor/enclose-region "mixed" beg end)
2153   )
2154
2155 (defun mime-editor/enclose-parallel-region (beg end)
2156   (interactive "*r")
2157   (mime-editor/enclose-region "parallel" beg end)
2158   )
2159
2160 (defun mime-editor/enclose-digest-region (beg end)
2161   (interactive "*r")
2162   (mime-editor/enclose-region "digest" beg end)
2163   )
2164
2165 (defun mime-editor/enclose-alternative-region (beg end)
2166   (interactive "*r")
2167   (mime-editor/enclose-region "alternative" beg end)
2168   )
2169
2170 (defun mime-editor/enclose-signed-region (beg end)
2171   (interactive "*r")
2172   (if mime-editor/signing-type
2173       (mime-editor/enclose-region "signed" beg end)
2174     (message "Please specify signing type.")
2175     ))
2176
2177 (defun mime-editor/enclose-encrypted-region (beg end)
2178   (interactive "*r")
2179   (if mime-editor/signing-type
2180       (mime-editor/enclose-region "encrypted" beg end)
2181     (message "Please specify encrypting type.")
2182     ))
2183
2184 (defun mime-editor/insert-key (&optional arg)
2185   "Insert a pgp public key."
2186   (interactive "P")
2187   (mime-editor/insert-tag "application" "pgp-keys")
2188   (mime-editor/define-encoding "7bit")
2189   (mc-insert-public-key)
2190   )
2191
2192
2193 ;;; @ flag setting
2194 ;;;
2195
2196 (defun mime-editor/set-split (arg)
2197   (interactive
2198    (list
2199     (y-or-n-p "Do you want to enable split?")
2200     ))
2201   (setq mime-editor/split-message arg)
2202   (if arg
2203       (message "This message is enabled to split.")
2204     (message "This message is not enabled to split.")
2205     ))
2206
2207 (defun mime-editor/toggle-transfer-level (&optional transfer-level)
2208   "Toggle transfer-level is 7bit or 8bit through.
2209
2210 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2211   (interactive)
2212   (if (numberp transfer-level)
2213       (setq mime-editor/transfer-level transfer-level)
2214     (if (< mime-editor/transfer-level 8)
2215         (setq mime-editor/transfer-level 8)
2216       (setq mime-editor/transfer-level 7)
2217       ))
2218   (setq mime-editor/charset-default-encoding-alist
2219         (mime/make-charset-default-encoding-alist
2220          mime-editor/transfer-level))
2221   (message (format "Current transfer-level is %d bit"
2222                    mime-editor/transfer-level))
2223   (setq mime-editor/transfer-level-string
2224         (mime/encoding-name mime-editor/transfer-level 'not-omit))
2225   (force-mode-line-update)
2226   )
2227
2228
2229 ;;; @ pgp
2230 ;;;
2231
2232 (defun mime-editor/set-sign (arg)
2233   (interactive
2234    (list
2235     (y-or-n-p "Do you want to sign?")
2236     ))
2237   (if arg
2238       (if mime-editor/signing-type
2239           (progn
2240             (setq mime-editor/pgp-processing 'sign)
2241             (message "This message will be signed.")
2242             )
2243         (message "Please specify signing type.")
2244         )
2245     (if (eq mime-editor/pgp-processing 'sign)
2246         (setq mime-editor/pgp-processing nil)
2247       )
2248     (message "This message will not be signed.")
2249     ))
2250
2251 (defun mime-editor/set-encrypt (arg)
2252   (interactive
2253    (list
2254     (y-or-n-p "Do you want to encrypt?")
2255     ))
2256   (if arg
2257       (if mime-editor/encrypting-type
2258           (progn
2259             (setq mime-editor/pgp-processing 'encrypt)
2260             (message "This message will be encrypt.")
2261             )
2262         (message "Please specify encrypting type.")
2263         )
2264     (if (eq mime-editor/pgp-processing 'encrypt)
2265         (setq mime-editor/pgp-processing nil)
2266       )
2267     (message "This message will not be encrypt.")
2268     ))
2269
2270 (defvar mime-editor/pgp-processing nil)
2271 (make-variable-buffer-local 'mime-editor/pgp-processing)
2272
2273 (defun mime-editor/pgp-enclose-buffer ()
2274   (let ((beg (save-excursion
2275                (goto-char (point-min))
2276                (if (search-forward (concat "\n" mail-header-separator "\n"))
2277                    (match-end 0)
2278                  )))
2279         (end (point-max))
2280         )
2281     (if beg
2282         (cond ((eq mime-editor/pgp-processing 'sign)
2283                (mime-editor/enclose-signed-region beg end)
2284                )
2285               ((eq mime-editor/pgp-processing 'encrypt)
2286                (mime-editor/enclose-encrypted-region beg end)
2287                ))
2288       )))
2289
2290
2291 ;;; @ split
2292 ;;;
2293
2294 (defun mime-editor/insert-partial-header
2295   (fields subject id number total separator)
2296   (insert fields)
2297   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2298   (insert (format "Mime-Version: 1.0 (split by tm-edit %s)\n"
2299                   mime-editor/version))
2300   (insert (format "\
2301 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2302                   id number total separator))
2303   )
2304
2305 (defun mime-editor/split-and-send
2306   (&optional cmd lines mime-editor/message-max-length)
2307   (interactive)
2308   (or lines
2309       (setq lines
2310             (count-lines (point-min) (point-max)))
2311       )
2312   (or mime-editor/message-max-length
2313       (setq mime-editor/message-max-length
2314             (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2315                 mime-editor/message-default-max-length))
2316       )
2317   (let* ((mime-editor/draft-file-name 
2318           (or (buffer-file-name)
2319               (make-temp-name
2320                (expand-file-name "tm-draft" mime/tmp-dir))))
2321          (separator mail-header-separator)
2322          (config
2323           (eval (cdr (assq major-mode mime-editor/window-config-alist))))
2324          (id (concat "\""
2325                      (replace-space-with-underline (current-time-string))
2326                      "@" (system-name) "\"")))
2327     (run-hooks 'mime-editor/before-split-hook)
2328     (let* ((header (rfc822/get-header-string-except
2329                     mime-editor/split-ignored-field-regexp separator))
2330            (subject (mail-fetch-field "subject"))
2331            (total (+ (/ lines mime-editor/message-max-length)
2332                      (if (> (mod lines mime-editor/message-max-length) 0)
2333                          1)))
2334            (the-buf (current-buffer))
2335            (buf (get-buffer "*tmp-send*"))
2336            (command
2337             (or cmd
2338                 (cdr
2339                  (assq major-mode
2340                        mime-editor/split-message-sender-alist))
2341                 (cdr
2342                  (assq major-mode
2343                        mime-editor/message-default-sender-alist))
2344                 ))
2345            data)
2346       (goto-char (point-min))
2347       (if (re-search-forward (concat "^" (regexp-quote separator) "$")
2348                              nil t)
2349           (replace-match "")
2350         )
2351       (if buf
2352           (progn
2353             (switch-to-buffer buf)
2354             (erase-buffer)
2355             (switch-to-buffer the-buf)
2356             )
2357         (setq buf (get-buffer-create "*tmp-send*"))
2358         )
2359       (switch-to-buffer buf)
2360       (make-local-variable 'mail-header-separator)
2361       (setq mail-header-separator separator)
2362       (switch-to-buffer the-buf)
2363       (goto-char (point-min))
2364       (re-search-forward "^$" nil t)
2365       (let ((mime-editor/partial-number 1))
2366         (setq data (buffer-substring
2367                     (point-min)
2368                     (progn
2369                       (goto-line mime-editor/message-max-length)
2370                       (point))
2371                     ))
2372         (delete-region (point-min)(point))
2373         (switch-to-buffer buf)
2374         (mime-editor/insert-partial-header
2375          header subject id mime-editor/partial-number total separator)
2376         (insert data)
2377         (save-excursion
2378           (save-restriction
2379             (goto-char (point-min))
2380             (search-forward (concat "\n" mail-header-separator "\n"))
2381             (narrow-to-region
2382              (match-end 0)
2383              (if (re-search-forward "^$" nil t)
2384                  (match-beginning 0)
2385                (point-max)
2386                ))
2387             (goto-char (point-min))
2388             (while (re-search-forward
2389                     mime-editor/split-blind-field-regexp nil t)
2390               (delete-region (match-beginning 0)
2391                              (let ((e (rfc822/field-end)))
2392                                (if (< e (point-max))
2393                                    (1+ e)
2394                                  e)))
2395               )
2396             ))
2397         (save-excursion
2398           (message (format "Sending %d/%d..."
2399                            mime-editor/partial-number total))
2400           (call-interactively command)
2401           (message (format "Sending %d/%d... done"
2402                            mime-editor/partial-number total))
2403           )
2404         (erase-buffer)
2405         (switch-to-buffer the-buf)
2406         (setq mime-editor/partial-number 2)
2407         (while (< mime-editor/partial-number total)
2408           (setq data (buffer-substring
2409                       (point-min)
2410                       (progn
2411                         (goto-line mime-editor/message-max-length)
2412                         (point))
2413                       ))
2414           (delete-region (point-min)(point))
2415           (switch-to-buffer buf)
2416           (mime-editor/insert-partial-header
2417            header subject id mime-editor/partial-number total separator)
2418           (insert data)
2419           (save-excursion
2420             (message (format "Sending %d/%d..."
2421                              mime-editor/partial-number total))
2422             (call-interactively command)
2423             (message (format "Sending %d/%d... done"
2424                              mime-editor/partial-number total))
2425             )
2426           (erase-buffer)
2427           (switch-to-buffer the-buf)
2428           (setq mime-editor/partial-number
2429                 (1+ mime-editor/partial-number))
2430           )
2431         (goto-char (point-min))
2432         (mime-editor/insert-partial-header
2433          header subject id mime-editor/partial-number total separator)
2434         (message (format "Sending %d/%d..."
2435                          mime-editor/partial-number total))
2436         ))))
2437
2438 (defun mime-editor/maybe-split-and-send (&optional cmd)
2439   (interactive)
2440   (run-hooks 'mime-editor/before-send-hook)
2441   (let ((mime-editor/message-max-length
2442          (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2443              mime-editor/message-default-max-length))
2444         (lines (count-lines (point-min) (point-max)))
2445         )
2446     (if (and (> lines mime-editor/message-max-length)
2447              mime-editor/split-message)
2448         (mime-editor/split-and-send cmd lines mime-editor/message-max-length)
2449       )))
2450
2451
2452 ;;; @ preview message
2453 ;;;
2454
2455 (defun mime-editor/preview-message ()
2456   "preview editing MIME message. [tm-edit.el]"
2457   (interactive)
2458   (let* ((str (buffer-string))
2459          (separator mail-header-separator)
2460          (the-buf (current-buffer))
2461          (buf-name (buffer-name))
2462          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2463          (buf (get-buffer temp-buf-name))
2464          )
2465     (if buf
2466         (progn
2467           (switch-to-buffer buf)
2468           (erase-buffer)
2469           )
2470       (setq buf (get-buffer-create temp-buf-name))
2471       (switch-to-buffer buf)
2472       )
2473     (insert str)
2474     (setq major-mode 'mime/temporary-message-mode)
2475     (make-local-variable 'mail-header-separator)
2476     (setq mail-header-separator separator)
2477     (make-local-variable 'mime/editing-buffer)
2478     (setq mime/editing-buffer the-buf)
2479     
2480     (run-hooks 'mime-editor/translate-hook)
2481     (mime-editor/translate-buffer)
2482     (goto-char (point-min))
2483     (if (re-search-forward
2484          (concat "^" (regexp-quote separator) "$"))
2485         (replace-match "")
2486       )
2487     (mime/viewer-mode)
2488     ))
2489
2490 (defun mime-editor/quitting-method ()
2491   (let ((temp mime::preview/article-buffer)
2492         buf)
2493     (mime-viewer/kill-buffer)
2494     (set-buffer temp)
2495     (setq buf mime/editing-buffer)
2496     (kill-buffer temp)
2497     (switch-to-buffer buf)
2498     ))
2499
2500 (set-alist 'mime-viewer/quitting-method-alist
2501            'mime/temporary-message-mode
2502            (function mime-editor/quitting-method)
2503            )
2504
2505
2506 ;;; @ draft preview
2507 ;;; 
2508 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2509 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2510
2511 (defvar mime-editor/draft-header-separator-alist
2512   '((news-reply-mode . mail-header-separator)
2513     (mh-letter-mode . mail-header-separator)
2514     ))
2515
2516 (defvar mime::article/draft-header-separator nil)
2517
2518 (defun mime-editor/draft-preview ()
2519   (interactive)
2520   (let ((sep (cdr (assq major-mode mime-editor/draft-header-separator-alist))))
2521     (or (stringp sep) (setq sep (eval sep)))
2522     (make-variable-buffer-local 'mime::article/draft-header-separator)
2523     (goto-char (point-min))
2524     (re-search-forward
2525      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2526     (setq mime::article/draft-header-separator
2527           (buffer-substring (match-beginning 0) (match-end 0)))
2528     (replace-match "")
2529     (mime/viewer-mode (current-buffer))
2530     (pop-to-buffer (current-buffer))
2531     ))
2532
2533 (defun mime-viewer::quitting-method/draft-preview ()
2534   (let ((mother mime::preview/mother-buffer))
2535     (save-excursion
2536       (switch-to-buffer mother)
2537       (goto-char (point-min))
2538       (if (and
2539            (re-search-forward
2540             (concat "^\\("
2541                     (regexp-quote mime::article/draft-header-separator)
2542                     "\\)?$") nil t)
2543            (bolp))
2544           (progn
2545             (insert mime::article/draft-header-separator)
2546             (set-buffer-modified-p (buffer-modified-p))
2547             )))
2548     (mime-viewer/kill-buffer)
2549     (pop-to-buffer mother)
2550     ))
2551
2552 (set-alist 'mime-viewer/quitting-method-alist
2553            'mh-letter-mode
2554            (function mime-viewer::quitting-method/draft-preview)
2555            )
2556
2557 (set-alist 'mime-viewer/quitting-method-alist
2558            'news-reply-mode
2559            (function mime-viewer::quitting-method/draft-preview)
2560            )
2561
2562
2563 ;;; @ edit again
2564 ;;;
2565
2566 (defun mime-editor::edit-again (code-conversion)
2567   (save-excursion
2568     (goto-char (point-min))
2569     (let ((ctl (mime/Content-Type)))
2570       (if ctl
2571           (let ((ctype (car ctl))
2572                 (params (cdr ctl))
2573                 type stype)
2574             (if (string-match "/" ctype)
2575                 (progn
2576                   (setq type (substring ctype 0 (match-beginning 0)))
2577                   (setq stype (substring ctype (match-end 0)))
2578                   )
2579               (setq type ctype)
2580               )
2581             (cond
2582              ((string-equal type "multipart")
2583               (let ((boundary (assoc-value "boundary" params)))
2584                 (re-search-forward (concat "\n--" boundary) nil t)
2585                 (let ((bb (match-beginning 0)) eb tag)
2586                   (setq tag (format "\n--<<%s>>-{" stype))
2587                   (goto-char bb)
2588                   (insert tag)
2589                   (setq bb (+ bb (length tag)))
2590                   (re-search-forward (concat "\n--" boundary "--") nil t)
2591                   (setq eb (match-beginning 0))
2592                   (replace-match (format "\n--}-<<%s>>" stype))
2593                   (save-restriction
2594                     (narrow-to-region bb eb)
2595                     (goto-char (point-min))
2596                     (while (re-search-forward
2597                             (concat "\n--" boundary "\n") nil t)
2598                       (let ((beg (match-beginning 0))
2599                             end)
2600                         (delete-region beg (match-end 0))
2601                         (save-excursion
2602                           (if (re-search-forward
2603                                (concat "\n--" boundary) nil t)
2604                               (setq end (match-beginning 0))
2605                             (setq end (point-max))
2606                             )
2607                           (save-restriction
2608                             (narrow-to-region beg end)
2609                             (mime-editor::edit-again code-conversion)
2610                             (goto-char (point-max))
2611                             ))))
2612                     ))
2613                 (goto-char (point-min))
2614                 (or (= (point-min) 1)
2615                     (delete-region (point-min)
2616                                    (if (re-search-forward "^$" nil t)
2617                                        (match-end 0)
2618                                      (point-min)
2619                                      )))
2620                 ))
2621              (t
2622               (let* (charset
2623                      (pstr
2624                       (mapconcat (function
2625                                   (lambda (attr)
2626                                     (if (string-equal (car attr)
2627                                                       "charset")
2628                                         (progn
2629                                           (setq charset (cdr attr))
2630                                           "")
2631                                       (concat ";" (car attr)
2632                                               "=" (cdr attr))
2633                                       )
2634                                     ))
2635                                  params ""))
2636                      encoding
2637                      encoded)
2638                 (save-excursion
2639                   (if (re-search-forward
2640                        "Content-Transfer-Encoding:" nil t)
2641                       (let ((beg (match-beginning 0))
2642                             (hbeg (match-end 0))
2643                             (end (rfc822/field-end)))
2644                         (setq encoding
2645                               (eliminate-top-spaces
2646                                (rfc822/unfolding-string
2647                                 (buffer-substring hbeg end))))
2648                         (if (or charset (string-equal type "text"))
2649                             (progn
2650                               (delete-region beg (1+ end))
2651                               (goto-char (point-min))
2652                               (if (search-forward "\n\n" nil t)
2653                                   (progn
2654                                     (mime-decode-region
2655                                      (match-end 0)(point-max) encoding)
2656                                     (setq encoded t
2657                                           encoding nil)
2658                                     )))))))
2659                 (if (or code-conversion encoded)
2660                     (if charset
2661                         (mime-charset-decode-region (point-min)(point-max)
2662                                                     charset)
2663                       (character-decode-region (point-min)(point-max)
2664                                                mime/default-coding-system)
2665                       ))
2666                 (let ((he
2667                        (if (re-search-forward "^$" nil t)
2668                            (match-end 0)
2669                          (point-min)
2670                          )))
2671                   (if (= (point-min) 1)
2672                       (progn
2673                         (goto-char he)
2674                         (insert
2675                          (concat
2676                           "\n"
2677                           (mime-create-tag
2678                            (concat type "/" stype pstr) encoding)
2679                           ))
2680                         )
2681                     (delete-region (point-min) he)
2682                     (insert
2683                      (concat "\n"
2684                              (mime-create-tag
2685                               (concat type "/" stype pstr) encoding)
2686                              ))
2687                     ))
2688                 ))))
2689         (if code-conversion
2690             (character-decode-region (point-min) (point-max)
2691                                      mime/default-coding-system)
2692           )
2693         ))))
2694
2695 (defun mime/edit-again (&optional code-conversion no-separator no-mode)
2696   (interactive)
2697   (mime-editor::edit-again code-conversion)
2698   (goto-char (point-min))
2699   (save-restriction
2700     (narrow-to-region (point-min)
2701                       (if (re-search-forward "^$" nil t)
2702                           (match-end 0)
2703                         (point-max)
2704                         ))
2705     (goto-char (point-min))
2706     (while (re-search-forward
2707             "^\\(Content-.*\\|Mime-Version\\):" nil t)
2708       (delete-region (match-beginning 0) (1+ (rfc822/field-end)))
2709       ))
2710   (or no-separator
2711       (and (re-search-forward "^$")
2712            (replace-match mail-header-separator)
2713            ))
2714   (or no-mode
2715       (mime/editor-mode)
2716       ))
2717
2718
2719 ;;; @ end
2720 ;;;
2721
2722 (provide 'tm-edit)
2723
2724 (run-hooks 'tm-edit-load-hook)
2725
2726 ;;; tm-edit.el ends here