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