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