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