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