This commit was generated by cvs2svn to compensate for changes in r425,
[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.75 $
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.75 1996/07/31 02:51:16 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 (defun mime-editor/encrypt-pgp-elkins (beg end boundary)
1666   (save-excursion
1667     (save-restriction
1668       (let ((from (rfc822/get-field-body "From" mail-header-separator))
1669             (to (rfc822/get-field-body "To" mail-header-separator))
1670             (cc (rfc822/get-field-body "cc" mail-header-separator))
1671             recipients)
1672         (narrow-to-region beg end)
1673         (let* ((ret
1674                 (mime-editor/translate-region beg end boundary))
1675                (ctype    (car ret))
1676                (encoding (nth 1 ret))
1677                (parts    (nth 3 ret))
1678                (pgp-boundary (concat "pgp-" boundary))
1679                )
1680           (goto-char beg)
1681           (if (and (stringp from)
1682                    (not (string-equal from "")))
1683               (insert (format "From: %s\n" from))
1684             )
1685           (if (and (stringp to)
1686                    (not (string-equal to "")))
1687               (progn
1688                 (insert (format "To: %s\n" to))
1689                 (setq recipients to)
1690                 ))
1691           (if (and (stringp cc)
1692                    (not (string-equal cc "")))
1693               (progn
1694                 (insert (format "cc: %s\n" cc))
1695                 (if recipients
1696                     (setq recipients (concat recipients "," cc))
1697                   (setq recipients cc)
1698                   )))
1699           (insert (format "Content-Type: %s\n" ctype))
1700           (if encoding
1701               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1702             )
1703           (insert "\n")
1704           (if (null
1705                (let ((mc-pgp-always-sign 'never))
1706                  (mc-pgp-encrypt-region
1707                   (mc-split "\\([ \t\n]*,[ \t\n]*\\)+" recipients)
1708                   (point-min) (point-max) from nil)
1709                  ))
1710               (throw 'mime-editor/error 'pgp-error)
1711             )
1712           (goto-char beg)
1713           (insert (format "--[[multipart/encrypted;
1714  boundary=\"%s\";
1715  protocol=\"application/pgp-encrypted\"][7bit]]
1716 --%s
1717 Content-Type: application/pgp-encrypted
1718
1719 --%s
1720 Content-Type: application/octet-stream
1721 Content-Transfer-Encoding: 7bit
1722
1723 " pgp-boundary pgp-boundary pgp-boundary))
1724           (goto-char (point-max))
1725           (insert (format "\n--%s--\n" pgp-boundary))
1726           )))))
1727
1728 (defun mime-editor/sign-pgp-kazu (beg end boundary)
1729   (save-excursion
1730     (save-restriction
1731       (narrow-to-region beg end)
1732       (let* ((ret
1733               (mime-editor/translate-region beg end boundary))
1734              (ctype    (car ret))
1735              (encoding (nth 1 ret))
1736              (parts    (nth 3 ret))
1737              )
1738         (goto-char beg)
1739         (insert (format "Content-Type: %s\n" ctype))
1740         (if encoding
1741             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1742           )
1743         (insert "\n")
1744         (or (as-binary-process (mc-pgp-sign-region beg (point-max)))
1745             (throw 'mime-editor/error 'pgp-error)
1746             )
1747         (goto-char beg)
1748         (insert
1749          "--[[application/pgp; format=mime][7bit]]\n")
1750         ))
1751     ))
1752
1753 (defun mime-editor/encrypt-pgp-kazu (beg end boundary)
1754   (save-excursion
1755     (let ((from (rfc822/get-field-body "From"))
1756           (to (rfc822/get-field-body "To"))
1757           (cc (rfc822/get-field-body "cc"))
1758           recipients)
1759       (save-restriction
1760         (narrow-to-region beg end)
1761         (let* ((ret
1762                 (mime-editor/translate-region beg end boundary))
1763                (ctype    (car ret))
1764                (encoding (nth 1 ret))
1765                (parts    (nth 3 ret))
1766                )
1767           (goto-char beg)
1768           (if (and (stringp from)
1769                    (not (string-equal from "")))
1770               (insert (format "From: %s\n" from))
1771             )
1772           (if (and (stringp to)
1773                    (not (string-equal to "")))
1774               (progn
1775                 (insert (format "To: %s\n" to))
1776                 (setq recipients to)
1777                 ))
1778           (if (and (stringp cc)
1779                    (not (string-equal cc "")))
1780               (progn
1781                 (insert (format "cc: %s\n" cc))
1782                 (if recipients
1783                     (setq recipients (concat recipients "," cc))
1784                   (setq recipients cc)
1785                   )))
1786           (insert (format "Content-Type: %s\n" ctype))
1787           (if encoding
1788               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1789             )
1790           (insert "\n")
1791           (or (as-binary-process
1792                (mc-pgp-encrypt-region
1793                 (mc-split "\\([ \t\n]*,[ \t\n]*\\)+" recipients)
1794                 beg (point-max))
1795                )
1796               (throw 'mime-editor/error 'pgp-error)
1797               )
1798           (goto-char beg)
1799           (insert
1800            "--[[application/pgp; format=mime][7bit]]\n")
1801           ))
1802       )))
1803
1804 (defun mime-editor/translate-body ()
1805   "Encode the tagged MIME body in current buffer in MIME compliant message."
1806   (interactive)
1807   (save-excursion
1808     (let ((boundary
1809            (concat mime-multipart-boundary "_"
1810                    (replace-space-with-underline (current-time-string))
1811                    ))
1812           (i 1)
1813           ret)
1814       (while (mime-editor/process-multipart-1
1815               (format "%s-%d" boundary i))
1816         (setq i (1+ i))
1817         )
1818       (save-restriction
1819         ;; We are interested in message body.
1820         (let* ((beg
1821                 (progn
1822                   (goto-char (point-min))
1823                   (re-search-forward
1824                    (concat "\n" (regexp-quote mail-header-separator)
1825                            (if mime-ignore-preceding-spaces
1826                                "[ \t\n]*\n" "\n")) nil 'move)
1827                   (point)))
1828                (end
1829                 (progn
1830                   (goto-char (point-max))
1831                   (and mime-ignore-trailing-spaces
1832                        (re-search-backward "[^ \t\n]\n" beg t)
1833                        (forward-char 1))
1834                   (point))))
1835           (setq ret (mime-editor/translate-region
1836                      beg end
1837                      (format "%s-%d" boundary i)))
1838           ))
1839       (mime-editor/dequote-region (point-min)(point-max))
1840       (let ((contype (car ret))         ;Content-Type
1841             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1842             )
1843         ;; Make primary MIME headers.
1844         (or (mail-position-on-field "Mime-Version")
1845             (insert mime-editor/mime-version-value))
1846         ;; Remove old Content-Type and other fields.
1847         (save-restriction
1848           (goto-char (point-min))
1849           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1850           (narrow-to-region (point-min) (point))
1851           (goto-char (point-min))
1852           (mime-delete-field "Content-Type")
1853           (mime-delete-field "Content-Transfer-Encoding"))
1854         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1855         (mail-position-on-field "Content-Type")
1856         (insert contype)
1857         (if encoding
1858             (progn
1859               (mail-position-on-field "Content-Transfer-Encoding")
1860               (insert encoding)))
1861         ))))
1862
1863 (defun mime-editor/translate-single-part-tag (&optional prefix)
1864   (if (re-search-forward mime-editor/single-part-tag-regexp nil t)
1865       (let* ((beg (match-beginning 0))
1866              (end (match-end 0))
1867              (tag (buffer-substring beg end))
1868              )
1869         (delete-region beg end)
1870         (setq contype (mime-editor/get-contype tag))
1871         (setq encoding (mime-editor/get-encoding tag))
1872         (insert (concat prefix "--" boundary "\n"))
1873         (save-restriction
1874           (narrow-to-region (point)(point))
1875           (insert "Content-Type: " contype "\n")
1876           (if encoding
1877               (insert "Content-Transfer-Encoding: " encoding "\n"))
1878           (mime/encode-message-header)
1879           )
1880         t)))
1881
1882 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1883   (if (null boundary)
1884       (setq boundary
1885             (concat mime-multipart-boundary "_"
1886                     (replace-space-with-underline (current-time-string))))
1887     )
1888   (save-excursion
1889     (save-restriction
1890       (narrow-to-region beg end)
1891       (let ((tag nil)                   ;MIME tag
1892             (contype nil)               ;Content-Type
1893             (encoding nil)              ;Content-Transfer-Encoding
1894             (nparts 0))                 ;Number of body parts
1895         ;; Normalize the body part by inserting appropriate message
1896         ;; tags for every message contents.
1897         (mime-editor/normalize-body)
1898         ;; Counting the number of Content-Type.
1899         (goto-char (point-min))
1900         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1901           (setq nparts (1+ nparts)))
1902         ;; Begin translation.
1903         (cond
1904          ((and (<= nparts 1)(not multipart))
1905           ;; It's a singular message.
1906           (goto-char (point-min))
1907           (while (re-search-forward
1908                   mime-editor/single-part-tag-regexp nil t)
1909             (setq tag
1910                   (buffer-substring (match-beginning 0) (match-end 0)))
1911             (delete-region (match-beginning 0) (1+ (match-end 0)))
1912             (setq contype (mime-editor/get-contype tag))
1913             (setq encoding (mime-editor/get-encoding tag))
1914             ))
1915          (t
1916           ;; It's a multipart message.
1917           (goto-char (point-min))
1918           (and (mime-editor/translate-single-part-tag)
1919                (while (mime-editor/translate-single-part-tag "\n"))
1920                )
1921           ;; Define Content-Type as "multipart/mixed".
1922           (setq contype
1923                 (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1924           ;; Content-Transfer-Encoding must be "7bit".
1925           ;; The following encoding can be `nil', but is
1926           ;; specified as is since there is no way that a user
1927           ;; specifies it.
1928           (setq encoding "7bit")
1929           ;; Insert the trailer.
1930           (goto-char (point-max))
1931           (insert "\n--" boundary "--\n")
1932           ))
1933         (list contype encoding boundary nparts)
1934         ))))
1935
1936 (defun mime-editor/normalize-body ()
1937   "Normalize the body part by inserting appropriate message tags."
1938   ;; Insert the first MIME tags if necessary.
1939   (goto-char (point-min))
1940   (if (not (looking-at mime-editor/single-part-tag-regexp))
1941       (insert (mime-make-text-tag) "\n"))
1942   ;; Check each tag, and add new tag or correct it if necessary.
1943   (goto-char (point-min))
1944   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1945     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1946            (contype (mime-editor/get-contype tag))
1947            (charset (mime-get-parameter contype "charset"))
1948            (encoding (mime-editor/get-encoding tag)))
1949       ;; Remove extra whitespaces after the tag.
1950       (if (looking-at "[ \t]+$")
1951           (delete-region (match-beginning 0) (match-end 0)))
1952       (let ((beg (point))
1953             (end (mime-editor/content-end))
1954             )
1955         (goto-char end)
1956         (or (looking-at mime-editor/beginning-tag-regexp)
1957             (eobp)
1958             (insert (mime-make-text-tag) "\n")
1959             )
1960         (visible-region beg end)
1961         (goto-char beg)
1962         )
1963       (cond
1964        ((mime-test-content-type contype "message")
1965         ;; Content-type "message" should be sent as is.
1966         (forward-line 1)
1967         )
1968        ((mime-test-content-type contype "text")
1969         ;; Define charset for text if necessary.
1970         (setq charset (if charset
1971                           (intern (downcase charset))
1972                         (mime-editor/choose-charset)))
1973         (mime-editor/define-charset charset)
1974         (cond ((string-equal contype "text/x-rot13-47")
1975                (save-excursion
1976                  (forward-line)
1977                  (set-mark (point))
1978                  (goto-char (mime-editor/content-end))
1979                  (tm:caesar-region)
1980                  ))
1981               ((string-equal contype "text/enriched")
1982                (save-excursion
1983                  (let ((beg (progn
1984                               (forward-line)
1985                               (point)))
1986                        (end (mime-editor/content-end))
1987                        )
1988                    (enriched-encode beg end)
1989                    (goto-char beg)
1990                    (if (search-forward "\n\n")
1991                        (delete-region beg (match-end 0))
1992                      )
1993                    ))))
1994         ;; Point is now on current tag.
1995         ;; Define encoding and encode text if necessary.
1996         (or encoding    ;Encoding is not specified.
1997             (let* ((encoding
1998                     (cdr
1999                      (assq charset
2000                            mime-editor/charset-default-encoding-alist)
2001                      ))
2002                    (beg (mime-editor/content-beginning))
2003                    )
2004               (encode-mime-charset-region beg (mime-editor/content-end)
2005                                           charset)
2006               (mime-encode-region beg (mime-editor/content-end) encoding)
2007               (mime-editor/define-encoding encoding)
2008               ))
2009         (goto-char (mime-editor/content-end))
2010         )
2011        ((null encoding)         ;Encoding is not specified.
2012         ;; Application, image, audio, video, and any other
2013         ;; unknown content-type without encoding should be
2014         ;; encoded.
2015         (let* ((encoding "base64")      ;Encode in BASE64 by default.
2016                (beg (mime-editor/content-beginning))
2017                (end (mime-editor/content-end))
2018                (body (buffer-substring beg end))
2019                )
2020           (mime-encode-region beg end encoding)
2021           (mime-editor/define-encoding encoding))
2022         (forward-line 1)
2023         ))
2024       )))
2025
2026 (defun mime-delete-field (field)
2027   "Delete header FIELD."
2028   (let ((regexp (format "^%s:[ \t]*" field)))
2029     (goto-char (point-min))
2030     (while (re-search-forward regexp nil t)
2031       (delete-region (match-beginning 0)
2032                      (progn (forward-line 1) (point)))
2033       )))
2034
2035 \f
2036 ;;;
2037 ;;; Platform dependent functions
2038 ;;;
2039
2040 ;; Sun implementations
2041
2042 (defun mime-voice-recorder-for-sun ()
2043   "Record voice in a buffer using Sun audio device, and return the buffer.
2044 If the environment variable AUDIOHOST is defined, its value is used as
2045 a recording host instead of local host."
2046   (let ((buffer (get-buffer-create " *MIME audio*"))
2047         (host (getenv "AUDIOHOST")))
2048     (message "Start the recording on %s.  Type C-g to finish the recording..."
2049              (or host (system-name)))
2050     (save-excursion
2051       (set-buffer buffer)
2052       (erase-buffer)
2053       (condition-case errorcode
2054           (let ((selective-display nil) ;Disable ^M to nl translation.
2055                 (mc-flag nil)           ;Mule
2056                 (kanji-flag nil))       ;NEmacs
2057             ;; If AUDIOHOST is defined, use the value as recording host.
2058             (cond ((not (null host))
2059                    ;; Disable automatic conversion of coding system if Mule.
2060                    (if (featurep 'mule)
2061                        (define-program-coding-system nil "rsh" *noconv*))
2062                    (call-process "rsh"
2063                                  nil
2064                                  buffer
2065                                  nil
2066                                  host
2067                                  "cat"
2068                                  "/dev/audio"
2069                                  ))
2070                   (t
2071                    ;; Disable automatic conversion of coding system if Mule.
2072                    (if (featurep 'mule)
2073                        (define-program-coding-system nil "cat" *noconv*))
2074                    (call-process "cat"
2075                                  "/dev/audio"
2076                                  buffer
2077                                  nil
2078                                  ))))
2079         (quit (message "Type C-g to finish recording... done.")
2080               buffer                    ;Return the buffer
2081               )))))
2082
2083 \f
2084 ;;; @ Other useful commands.
2085 ;;;
2086
2087 ;; Message forwarding commands as content-type "message/rfc822".
2088
2089 (defun mime-editor/insert-message (&optional message)
2090   (interactive)
2091   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
2092     (if (and inserter (fboundp inserter))
2093         (progn
2094           (mime-editor/insert-tag "message" "rfc822")
2095           (funcall inserter message)
2096           )
2097       (message "Sorry, I don't have message inserter for your MUA.")
2098       )))
2099
2100 (defun mime-editor/insert-mail (&optional message)
2101   (interactive)
2102   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
2103     (if (and inserter (fboundp inserter))
2104         (progn
2105           (mime-editor/insert-tag "message" "rfc822")
2106           (funcall inserter message)
2107           )
2108       (message "Sorry, I don't have mail inserter for your MUA.")
2109       )))
2110
2111 (defun mime-editor/inserted-message-filter ()
2112   (save-excursion
2113     (save-restriction
2114       (let ((header-start (point))
2115             (case-fold-search t)
2116             beg end)
2117         ;; for Emacs 18
2118         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2119         (if (re-search-forward "^$" (mark t))
2120             (narrow-to-region header-start (match-beginning 0))
2121           )
2122         (goto-char header-start)
2123         (while (and (re-search-forward
2124                      mime-editor/yank-ignored-field-regexp nil t)
2125                     (setq beg (match-beginning 0))
2126                     (setq end (1+ (rfc822/field-end)))
2127                     )
2128           (delete-region beg end)
2129           )
2130         ))))
2131
2132
2133 ;;; @ multipart enclosure
2134 ;;;
2135
2136 (defun mime-editor/enclose-region (type beg end)
2137   (save-excursion
2138     (goto-char beg)
2139     (let ((current (point)))
2140       (save-restriction
2141         (narrow-to-region beg end)
2142         (insert (format "--<<%s>>-{\n" type))
2143         (goto-char (point-max))
2144         (insert (format "--}-<<%s>>\n" type))
2145         (goto-char (point-max))
2146         )
2147       (or (looking-at mime-editor/beginning-tag-regexp)
2148           (eobp)
2149           (insert (mime-make-text-tag) "\n")
2150           )
2151       )))
2152
2153 (defun mime-editor/enclose-quote-region (beg end)
2154   (interactive "*r")
2155   (mime-editor/enclose-region "quote" beg end)
2156   )
2157
2158 (defun mime-editor/enclose-mixed-region (beg end)
2159   (interactive "*r")
2160   (mime-editor/enclose-region "mixed" beg end)
2161   )
2162
2163 (defun mime-editor/enclose-parallel-region (beg end)
2164   (interactive "*r")
2165   (mime-editor/enclose-region "parallel" beg end)
2166   )
2167
2168 (defun mime-editor/enclose-digest-region (beg end)
2169   (interactive "*r")
2170   (mime-editor/enclose-region "digest" beg end)
2171   )
2172
2173 (defun mime-editor/enclose-alternative-region (beg end)
2174   (interactive "*r")
2175   (mime-editor/enclose-region "alternative" beg end)
2176   )
2177
2178 (defun mime-editor/enclose-signed-region (beg end)
2179   (interactive "*r")
2180   (if mime-editor/signing-type
2181       (mime-editor/enclose-region "signed" beg end)
2182     (message "Please specify signing type.")
2183     ))
2184
2185 (defun mime-editor/enclose-encrypted-region (beg end)
2186   (interactive "*r")
2187   (if mime-editor/signing-type
2188       (mime-editor/enclose-region "encrypted" beg end)
2189     (message "Please specify encrypting type.")
2190     ))
2191
2192 (defun mime-editor/insert-key (&optional arg)
2193   "Insert a pgp public key."
2194   (interactive "P")
2195   (mime-editor/insert-tag "application" "pgp-keys")
2196   (mime-editor/define-encoding "7bit")
2197   (mc-insert-public-key)
2198   )
2199
2200
2201 ;;; @ flag setting
2202 ;;;
2203
2204 (defun mime-editor/set-split (arg)
2205   (interactive
2206    (list
2207     (y-or-n-p "Do you want to enable split?")
2208     ))
2209   (setq mime-editor/split-message arg)
2210   (if arg
2211       (message "This message is enabled to split.")
2212     (message "This message is not enabled to split.")
2213     ))
2214
2215 (defun mime-editor/toggle-transfer-level (&optional transfer-level)
2216   "Toggle transfer-level is 7bit or 8bit through.
2217
2218 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2219   (interactive)
2220   (if (numberp transfer-level)
2221       (setq mime-editor/transfer-level transfer-level)
2222     (if (< mime-editor/transfer-level 8)
2223         (setq mime-editor/transfer-level 8)
2224       (setq mime-editor/transfer-level 7)
2225       ))
2226   (setq mime-editor/charset-default-encoding-alist
2227         (mime-editor/make-charset-default-encoding-alist
2228          mime-editor/transfer-level))
2229   (message (format "Current transfer-level is %d bit"
2230                    mime-editor/transfer-level))
2231   (setq mime-editor/transfer-level-string
2232         (mime/encoding-name mime-editor/transfer-level 'not-omit))
2233   (force-mode-line-update)
2234   )
2235
2236
2237 ;;; @ pgp
2238 ;;;
2239
2240 (defun mime-editor/set-sign (arg)
2241   (interactive
2242    (list
2243     (y-or-n-p "Do you want to sign?")
2244     ))
2245   (if arg
2246       (if mime-editor/signing-type
2247           (progn
2248             (setq mime-editor/pgp-processing 'sign)
2249             (message "This message will be signed.")
2250             )
2251         (message "Please specify signing type.")
2252         )
2253     (if (eq mime-editor/pgp-processing 'sign)
2254         (setq mime-editor/pgp-processing nil)
2255       )
2256     (message "This message will not be signed.")
2257     ))
2258
2259 (defun mime-editor/set-encrypt (arg)
2260   (interactive
2261    (list
2262     (y-or-n-p "Do you want to encrypt?")
2263     ))
2264   (if arg
2265       (if mime-editor/encrypting-type
2266           (progn
2267             (setq mime-editor/pgp-processing 'encrypt)
2268             (message "This message will be encrypt.")
2269             )
2270         (message "Please specify encrypting type.")
2271         )
2272     (if (eq mime-editor/pgp-processing 'encrypt)
2273         (setq mime-editor/pgp-processing nil)
2274       )
2275     (message "This message will not be encrypt.")
2276     ))
2277
2278 (defvar mime-editor/pgp-processing nil)
2279 (make-variable-buffer-local 'mime-editor/pgp-processing)
2280
2281 (defun mime-editor/pgp-enclose-buffer ()
2282   (let ((beg (save-excursion
2283                (goto-char (point-min))
2284                (if (search-forward (concat "\n" mail-header-separator "\n"))
2285                    (match-end 0)
2286                  )))
2287         (end (point-max))
2288         )
2289     (if beg
2290         (cond ((eq mime-editor/pgp-processing 'sign)
2291                (mime-editor/enclose-signed-region beg end)
2292                )
2293               ((eq mime-editor/pgp-processing 'encrypt)
2294                (mime-editor/enclose-encrypted-region beg end)
2295                ))
2296       )))
2297
2298
2299 ;;; @ split
2300 ;;;
2301
2302 (defun mime-editor/insert-partial-header
2303   (fields subject id number total separator)
2304   (insert fields)
2305   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2306   (insert (format "Mime-Version: 1.0 (split by %s)\n"
2307                   mime-editor/version-name))
2308   (insert (format "\
2309 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2310                   id number total separator))
2311   )
2312
2313 (defun mime-editor/split-and-send
2314   (&optional cmd lines mime-editor/message-max-length)
2315   (interactive)
2316   (or lines
2317       (setq lines
2318             (count-lines (point-min) (point-max)))
2319       )
2320   (or mime-editor/message-max-length
2321       (setq mime-editor/message-max-length
2322             (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2323                 mime-editor/message-default-max-length))
2324       )
2325   (let* ((mime-editor/draft-file-name 
2326           (or (buffer-file-name)
2327               (make-temp-name
2328                (expand-file-name "tm-draft" mime/tmp-dir))))
2329          (separator mail-header-separator)
2330          (id (concat "\""
2331                      (replace-space-with-underline (current-time-string))
2332                      "@" (system-name) "\"")))
2333     (run-hooks 'mime-editor/before-split-hook)
2334     (let ((the-buf (current-buffer))
2335           (copy-buf (get-buffer-create " *Original Message*"))
2336           (header (rfc822/get-header-string-except
2337                    mime-editor/split-ignored-field-regexp separator))
2338           (subject (mail-fetch-field "subject"))
2339           (total (+ (/ lines mime-editor/message-max-length)
2340                     (if (> (mod lines mime-editor/message-max-length) 0)
2341                         1)))
2342           (command
2343            (or cmd
2344                (cdr
2345                 (assq major-mode
2346                       mime-editor/split-message-sender-alist))
2347                ))
2348           (mime-editor/partial-number 1)
2349           data)
2350       (save-excursion
2351         (set-buffer copy-buf)
2352         (erase-buffer)
2353         (insert-buffer the-buf)
2354         (save-restriction
2355           (if (re-search-forward
2356                (concat "^" (regexp-quote separator) "$") nil t)
2357               (let ((he (match-beginning 0)))
2358                 (replace-match "")
2359                 (narrow-to-region (point-min) he)
2360                 ))
2361           (goto-char (point-min))
2362           (while (re-search-forward mime-editor/split-blind-field-regexp nil t)
2363             (delete-region (match-beginning 0)
2364                            (1+ (rfc822/field-end)))
2365             )))
2366       (while (< mime-editor/partial-number total)
2367         (erase-buffer)
2368         (save-excursion
2369           (set-buffer copy-buf)
2370           (setq data (buffer-substring
2371                       (point-min)
2372                       (progn
2373                         (goto-line mime-editor/message-max-length)
2374                         (point))
2375                       ))
2376           (delete-region (point-min)(point))
2377           )
2378         (mime-editor/insert-partial-header
2379          header subject id mime-editor/partial-number total separator)
2380         (insert data)
2381         (save-excursion
2382           (message (format "Sending %d/%d..."
2383                            mime-editor/partial-number total))
2384           (call-interactively command)
2385           (message (format "Sending %d/%d... done"
2386                            mime-editor/partial-number total))
2387           )
2388         (setq mime-editor/partial-number
2389               (1+ mime-editor/partial-number))
2390         )
2391       (erase-buffer)
2392       (save-excursion
2393         (set-buffer copy-buf)
2394         (setq data (buffer-string))
2395         (erase-buffer)
2396         )
2397       (mime-editor/insert-partial-header
2398        header subject id mime-editor/partial-number total separator)
2399       (insert data)
2400       (save-excursion
2401         (message (format "Sending %d/%d..."
2402                          mime-editor/partial-number total))
2403         (message (format "Sending %d/%d... done"
2404                          mime-editor/partial-number total))
2405         )
2406       )))
2407
2408 (defun mime-editor/maybe-split-and-send (&optional cmd)
2409   (interactive)
2410   (run-hooks 'mime-editor/before-send-hook)
2411   (let ((mime-editor/message-max-length
2412          (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2413              mime-editor/message-default-max-length))
2414         (lines (count-lines (point-min) (point-max)))
2415         )
2416     (if (and (> lines mime-editor/message-max-length)
2417              mime-editor/split-message)
2418         (mime-editor/split-and-send cmd lines mime-editor/message-max-length)
2419       )))
2420
2421
2422 ;;; @ preview message
2423 ;;;
2424
2425 (defun mime-editor/preview-message ()
2426   "preview editing MIME message. [tm-edit.el]"
2427   (interactive)
2428   (let* ((str (buffer-string))
2429          (separator mail-header-separator)
2430          (the-buf (current-buffer))
2431          (buf-name (buffer-name))
2432          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2433          (buf (get-buffer temp-buf-name))
2434          )
2435     (if buf
2436         (progn
2437           (switch-to-buffer buf)
2438           (erase-buffer)
2439           )
2440       (setq buf (get-buffer-create temp-buf-name))
2441       (switch-to-buffer buf)
2442       )
2443     (insert str)
2444     (setq major-mode 'mime/temporary-message-mode)
2445     (make-local-variable 'mail-header-separator)
2446     (setq mail-header-separator separator)
2447     (make-local-variable 'mime/editing-buffer)
2448     (setq mime/editing-buffer the-buf)
2449     
2450     (run-hooks 'mime-editor/translate-hook)
2451     (mime-editor/translate-buffer)
2452     (goto-char (point-min))
2453     (if (re-search-forward
2454          (concat "^" (regexp-quote separator) "$"))
2455         (replace-match "")
2456       )
2457     (mime/viewer-mode)
2458     ))
2459
2460 (defun mime-editor/quitting-method ()
2461   (let ((temp mime::preview/article-buffer)
2462         buf)
2463     (mime-viewer/kill-buffer)
2464     (set-buffer temp)
2465     (setq buf mime/editing-buffer)
2466     (kill-buffer temp)
2467     (switch-to-buffer buf)
2468     ))
2469
2470 (set-alist 'mime-viewer/quitting-method-alist
2471            'mime/temporary-message-mode
2472            (function mime-editor/quitting-method)
2473            )
2474
2475
2476 ;;; @ draft preview
2477 ;;; 
2478 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2479 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2480
2481 (defvar mime-editor/draft-header-separator-alist
2482   '((news-reply-mode . mail-header-separator)
2483     (mh-letter-mode . mail-header-separator)
2484     ))
2485
2486 (defvar mime::article/draft-header-separator nil)
2487
2488 (defun mime-editor/draft-preview ()
2489   (interactive)
2490   (let ((sep (cdr (assq major-mode mime-editor/draft-header-separator-alist))))
2491     (or (stringp sep) (setq sep (eval sep)))
2492     (make-variable-buffer-local 'mime::article/draft-header-separator)
2493     (goto-char (point-min))
2494     (re-search-forward
2495      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2496     (setq mime::article/draft-header-separator
2497           (buffer-substring (match-beginning 0) (match-end 0)))
2498     (replace-match "")
2499     (mime/viewer-mode (current-buffer))
2500     (pop-to-buffer (current-buffer))
2501     ))
2502
2503 (defun mime-viewer::quitting-method/draft-preview ()
2504   (let ((mother mime::preview/mother-buffer))
2505     (save-excursion
2506       (switch-to-buffer mother)
2507       (goto-char (point-min))
2508       (if (and
2509            (re-search-forward
2510             (concat "^\\("
2511                     (regexp-quote mime::article/draft-header-separator)
2512                     "\\)?$") nil t)
2513            (bolp))
2514           (progn
2515             (insert mime::article/draft-header-separator)
2516             (set-buffer-modified-p (buffer-modified-p))
2517             )))
2518     (mime-viewer/kill-buffer)
2519     (pop-to-buffer mother)
2520     ))
2521
2522 (set-alist 'mime-viewer/quitting-method-alist
2523            'mh-letter-mode
2524            (function mime-viewer::quitting-method/draft-preview)
2525            )
2526
2527 (set-alist 'mime-viewer/quitting-method-alist
2528            'news-reply-mode
2529            (function mime-viewer::quitting-method/draft-preview)
2530            )
2531
2532
2533 ;;; @ edit again
2534 ;;;
2535
2536 (defun mime-editor::edit-again (code-conversion)
2537   (save-excursion
2538     (goto-char (point-min))
2539     (let ((ctl (mime/Content-Type)))
2540       (if ctl
2541           (let ((ctype (car ctl))
2542                 (params (cdr ctl))
2543                 type stype)
2544             (if (string-match "/" ctype)
2545                 (progn
2546                   (setq type (substring ctype 0 (match-beginning 0)))
2547                   (setq stype (substring ctype (match-end 0)))
2548                   )
2549               (setq type ctype)
2550               )
2551             (cond
2552              ((string-equal type "multipart")
2553               (let* ((boundary (assoc-value "boundary" params))
2554                      (boundary-pat
2555                       (concat "\n--" (regexp-quote boundary) "[ \t]*\n"))
2556                      )
2557                 (re-search-forward boundary-pat nil t)
2558                 (let ((bb (match-beginning 0)) eb tag)
2559                   (setq tag (format "\n--<<%s>>-{\n" stype))
2560                   (goto-char bb)
2561                   (insert tag)
2562                   (setq bb (+ bb (length tag)))
2563                   (re-search-forward
2564                    (concat "\n--" (regexp-quote boundary) "--[ \t]*\n")
2565                    nil t)
2566                   (setq eb (match-beginning 0))
2567                   (replace-match (format "--}-<<%s>>\n" stype))
2568                   (save-restriction
2569                     (narrow-to-region bb eb)
2570                     (goto-char (point-min))
2571                     (while (re-search-forward boundary-pat nil t)
2572                       (let ((beg (match-beginning 0))
2573                             end)
2574                         (delete-region beg (match-end 0))
2575                         (save-excursion
2576                           (if (re-search-forward boundary-pat nil t)
2577                               (setq end (match-beginning 0))
2578                             (setq end (point-max))
2579                             )
2580                           (save-restriction
2581                             (narrow-to-region beg end)
2582                             (mime-editor::edit-again code-conversion)
2583                             (goto-char (point-max))
2584                             ))))
2585                     ))
2586                 (goto-char (point-min))
2587                 (or (= (point-min) 1)
2588                     (delete-region (point-min)
2589                                    (if (search-forward "\n\n" nil t)
2590                                        (match-end 0)
2591                                      (point-min)
2592                                      )))
2593                 ))
2594              (t
2595               (let* (charset
2596                      (pstr
2597                       (mapconcat (function
2598                                   (lambda (attr)
2599                                     (if (string-equal (car attr)
2600                                                       "charset")
2601                                         (progn
2602                                           (setq charset (cdr attr))
2603                                           "")
2604                                       (concat ";" (car attr)
2605                                               "=" (cdr attr))
2606                                       )
2607                                     ))
2608                                  params ""))
2609                      encoding
2610                      encoded)
2611                 (save-excursion
2612                   (if (re-search-forward
2613                        "Content-Transfer-Encoding:" nil t)
2614                       (let ((beg (match-beginning 0))
2615                             (hbeg (match-end 0))
2616                             (end (rfc822/field-end)))
2617                         (setq encoding
2618                               (eliminate-top-spaces
2619                                (rfc822/unfolding-string
2620                                 (buffer-substring hbeg end))))
2621                         (if (or charset (string-equal type "text"))
2622                             (progn
2623                               (delete-region beg (1+ end))
2624                               (goto-char (point-min))
2625                               (if (search-forward "\n\n" nil t)
2626                                   (progn
2627                                     (mime-decode-region
2628                                      (match-end 0)(point-max) encoding)
2629                                     (setq encoded t
2630                                           encoding nil)
2631                                     )))))))
2632                 (if (or code-conversion encoded)
2633                     (decode-mime-charset-region
2634                      (point-min)(point-max)
2635                      (or charset default-mime-charset))
2636                   )
2637                 (let ((he
2638                        (if (re-search-forward "^$" nil t)
2639                            (match-end 0)
2640                          (point-min)
2641                          )))
2642                   (if (= (point-min) 1)
2643                       (progn
2644                         (goto-char he)
2645                         (insert
2646                          (concat "\n"
2647                                  (mime-create-tag
2648                                   (concat type "/" stype pstr) encoding)))
2649                         )
2650                     (delete-region (point-min) he)
2651                     (insert
2652                      (mime-create-tag
2653                       (concat type "/" stype pstr) encoding))
2654                     ))
2655                 ))))
2656         (if code-conversion
2657             (decode-mime-charset-region (point-min) (point-max)
2658                                         default-mime-charset)
2659           )
2660         ))))
2661
2662 (defun mime/edit-again (&optional code-conversion no-separator no-mode)
2663   (interactive)
2664   (mime-editor::edit-again code-conversion)
2665   (goto-char (point-min))
2666   (save-restriction
2667     (narrow-to-region
2668      (point-min)
2669      (if (re-search-forward
2670           (concat "^\\(" (regexp-quote mail-header-separator) "\\)?$")
2671           nil t)
2672          (match-end 0)
2673        (point-max)
2674        ))
2675     (goto-char (point-min))
2676     (while (re-search-forward
2677             "^\\(Content-.*\\|Mime-Version\\):" nil t)
2678       (delete-region (match-beginning 0) (1+ (rfc822/field-end)))
2679       ))
2680   (or no-separator
2681       (and (re-search-forward "^$")
2682            (replace-match mail-header-separator)
2683            ))
2684   (or no-mode
2685       (mime/editor-mode)
2686       ))
2687
2688
2689 ;;; @ end
2690 ;;;
2691
2692 (provide 'tm-edit)
2693
2694 (run-hooks 'tm-edit-load-hook)
2695
2696 ;;; tm-edit.el ends here