tm 7.48.
[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.48 $
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.48 1996/03/13 17:55:33 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 (defvar mime-editor/translate-buffer-hook
1468   '(mime-editor/pgp-enclose-buffer
1469     mime/encode-message-header
1470     mime-editor/translate-body))
1471
1472 (defun mime-editor/translate-buffer ()
1473   "Encode the tagged MIME message in current buffer in MIME compliant message."
1474   (interactive)
1475   (if (catch 'mime-editor/error
1476         (save-excursion
1477           (run-hooks 'mime-editor/translate-buffer-hook)
1478           ))
1479       (progn
1480         (undo)
1481         (error "Translation error!")
1482         )))
1483
1484 (defun mime-editor/find-inmost ()
1485   (goto-char (point-min))
1486   (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1487       (let ((bb (match-beginning 0))
1488             (be (match-end 0))
1489             (type (buffer-substring (match-beginning 1)(match-end 1)))
1490             end-exp eb ee)
1491         (setq end-exp (format "^--}-<<%s>>\n" type))
1492         (widen)
1493         (if (re-search-forward end-exp nil t)
1494             (progn
1495               (setq eb (match-beginning 0))
1496               (setq ee (match-end 0))
1497               )
1498           (setq eb (point-max))
1499           (setq ee (point-max))
1500           )
1501         (narrow-to-region be eb)
1502         (goto-char be)
1503         (if (re-search-forward mime-editor/multipart-beginning-regexp nil t)
1504             (let (ret)
1505               (narrow-to-region (match-beginning 0)(point-max))
1506               (mime-editor/find-inmost)
1507               )
1508           (widen)
1509           ;;(delete-region eb ee)
1510           (list type bb be eb)
1511           ))))
1512
1513 (defun mime-editor/process-multipart-1 (boundary)
1514   (let ((ret (mime-editor/find-inmost)))
1515     (if ret
1516         (let ((type (car ret))
1517               (bb (nth 1 ret))(be (nth 2 ret))
1518               (eb (nth 3 ret))
1519               )
1520           (narrow-to-region bb eb)
1521           (delete-region bb be)
1522           (setq bb (point-min))
1523           (setq eb (point-max))
1524           (widen)
1525           (goto-char eb)
1526           (if (looking-at mime-editor/multipart-end-regexp)
1527               (let ((beg (match-beginning 0))
1528                     (end (match-end 0))
1529                     )
1530                 (delete-region beg end)
1531                 (if (and (not (looking-at mime-editor/single-part-tag-regexp))
1532                          (not (eobp)))
1533                     (insert (concat (mime-make-text-tag) "\n"))
1534                   )))
1535           (cond ((string= type "signed")
1536                  (cond ((eq mime-editor/signing-type 'pgp-elkins)
1537                         (mime-editor/sign-pgp-elkins bb eb boundary)
1538                         )
1539                        ((eq mime-editor/signing-type 'pgp-kazu)
1540                         (mime-editor/process-pgp-kazu 'mc-sign
1541                                                       bb eb boundary)
1542                         )
1543                        ))
1544                 ((string= type "encrypted")
1545                  (cond ((eq mime-editor/signing-type 'pgp-elkins)
1546                         (mime-editor/encrypt-pgp-elkins bb eb boundary)
1547                         )
1548                        ((eq mime-editor/signing-type 'pgp-kazu)
1549                         (mime-editor/process-pgp-kazu 'mc-encrypt
1550                                                       bb eb boundary)
1551                         )))
1552                 (t
1553                  (setq boundary
1554                        (nth 2 (mime-editor/translate-region bb eb
1555                                                             boundary t)))
1556                  (goto-char bb)
1557                  (insert
1558                   (format "--[[multipart/%s;
1559  boundary=\"%s\"][7bit]]\n"
1560                           type boundary))
1561                  ))
1562           boundary))))
1563
1564 (defun tm:mc-pgp-generic-parser (result)
1565   (let ((ret (mc-pgp-generic-parser result)))
1566     (if (consp ret)
1567         (vector (car ret)(cdr ret))
1568       )))
1569
1570 (autoload 'mc-pgp-lookup-key "mc-pgp")
1571
1572 (defun tm:mc-process-region
1573   (beg end passwd program args parser &optional buffer boundary)
1574   (let ((obuf (current-buffer))
1575         (process-connection-type nil)
1576         mybuf result rgn proc)
1577     (unwind-protect
1578         (progn
1579           (setq mybuf (or buffer (generate-new-buffer " *mailcrypt temp")))
1580           (set-buffer mybuf)
1581           (erase-buffer)
1582           (set-buffer obuf)
1583           (buffer-disable-undo mybuf)
1584           (setq proc
1585                 (apply 'start-process "*PGP*" mybuf program args))
1586           (if passwd
1587               (progn
1588                 (process-send-string proc (concat passwd "\n"))
1589                 (or mc-passwd-timeout (mc-deactivate-passwd t))))
1590           (process-send-region proc beg end)
1591           (process-send-eof proc)
1592           (while (eq 'run (process-status proc))
1593             (accept-process-output proc 5))
1594           (setq result (process-exit-status proc))
1595           ;; Hack to force a status_notify() in Emacs 19.29
1596           (delete-process proc)
1597           (set-buffer mybuf)
1598           (goto-char (point-max))
1599           (if (re-search-backward "\nProcess \\*PGP.*\n\\'" nil t)
1600               (delete-region (match-beginning 0) (match-end 0)))
1601           (goto-char (point-min))
1602           ;; CRNL -> NL
1603           (while (search-forward "\r\n" nil t)
1604             (replace-match "\n"))
1605           ;; Hurm.  FIXME; must get better result codes.
1606           (if (stringp result)
1607               (error "%s exited abnormally: '%s'" program result)
1608             (setq rgn (funcall parser result))
1609             ;; If the parser found something, migrate it
1610             (if (consp rgn)
1611                 (progn
1612                   (set-buffer obuf)
1613                   (if boundary
1614                       (save-restriction
1615                         (narrow-to-region beg end)
1616                         (goto-char beg)
1617                         (insert (format "--%s\n" boundary))
1618                         (goto-char (point-max))
1619                         (insert (format "\n--%s
1620 Content-Type: application/pgp-signature
1621 Content-Transfer-Encoding: 7bit
1622
1623 " boundary))
1624                         (insert-buffer-substring mybuf (car rgn) (cdr rgn))
1625                         (goto-char (point-max))
1626                         (insert (format "\n--%s--\n" boundary))
1627                         )
1628                     (delete-region beg end)
1629                     (goto-char beg)
1630                     (insert-buffer-substring mybuf (car rgn) (cdr rgn))
1631                     )
1632                   (set-buffer mybuf)
1633                   (delete-region (car rgn) (cdr rgn)))))
1634           ;; Return nil on failure and exit code on success
1635           (if rgn result))
1636       ;; Cleanup even on nonlocal exit
1637       (if (and proc (eq 'run (process-status proc)))
1638           (interrupt-process proc))
1639       (set-buffer obuf)
1640       (or buffer (null mybuf) (kill-buffer mybuf)))))
1641
1642 (defun tm:mc-pgp-sign-region (start end &optional id unclear boundary)
1643   (if (not (boundp 'mc-pgp-user-id))
1644       (load "mc-pgp")
1645     )
1646   (let ((process-environment process-environment)
1647         (buffer (get-buffer-create mc-buffer-name))
1648         passwd args key
1649         (parser (function mc-pgp-generic-parser))
1650         (pgp-path mc-pgp-path)
1651         )
1652     (setq key (mc-pgp-lookup-key (or id mc-pgp-user-id)))
1653     (setq passwd
1654           (mc-activate-passwd
1655            (cdr key)
1656            (format "PGP passphrase for %s (%s): " (car key) (cdr key))))
1657     (setenv "PGPPASSFD" "0")
1658     (setq args
1659           (cons
1660            (if boundary
1661                "-fbast"
1662              "-fast")
1663            (list "+verbose=1" "+language=en"
1664                  (format "+clearsig=%s" (if unclear "off" "on"))
1665                  "+batchmode" "-u" (cdr key))))
1666     (if mc-pgp-comment
1667         (setq args (cons (format "+comment=%s" mc-pgp-comment) args))
1668       )
1669     (message "Signing as %s ..." (car key))
1670     (if (tm:mc-process-region
1671          start end passwd pgp-path args parser buffer boundary)
1672         (progn
1673           (if boundary
1674               (progn
1675                 (goto-char (point-min))
1676                 (insert
1677                  (format "\
1678 --[[multipart/signed; protocol=\"application/pgp-signature\";
1679  boundary=\"%s\"; micalg=pgp-md5][7bit]]\n" boundary))
1680                 ))
1681           (message "Signing as %s ... Done." (car key))
1682           t)
1683       nil)))
1684
1685 (defun mime-editor/sign-pgp-elkins (beg end boundary)
1686   (save-excursion
1687     (save-restriction
1688       (narrow-to-region beg end)
1689       (let* ((ret
1690               (mime-editor/translate-region beg end boundary))
1691              (ctype    (car ret))
1692              (encoding (nth 1 ret))
1693              (parts    (nth 3 ret))
1694              (pgp-boundary (concat "pgp-sign-" boundary))
1695              )
1696         (goto-char beg)
1697         (insert (format "Content-Type: %s\n" ctype))
1698         (if encoding
1699             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1700           )
1701         (insert "\n")
1702         (or (tm:mc-pgp-sign-region (point-min)(point-max)
1703                                    nil nil pgp-boundary)
1704             (throw 'mime-editor/error 'pgp-error)
1705             )
1706         ))))
1707
1708 (autoload 'mc-pgp-encrypt-region "mc-pgp")
1709
1710 (defun mime-editor/encrypt-pgp-elkins (beg end boundary)
1711   (save-excursion
1712     (save-restriction
1713       (let ((from (rfc822/get-field-body "From"))
1714             (to (rfc822/get-field-body "To"))
1715             (cc (rfc822/get-field-body "cc"))
1716             recipients)
1717         (narrow-to-region beg end)
1718         (let* ((ret
1719                 (mime-editor/translate-region beg end boundary))
1720                (ctype    (car ret))
1721                (encoding (nth 1 ret))
1722                (parts    (nth 3 ret))
1723                (pgp-boundary (concat "pgp-" boundary))
1724                )
1725           (goto-char beg)
1726           (if (and (stringp from)
1727                    (not (string-equal from "")))
1728               (insert (format "From: %s\n" from))
1729             )
1730           (if (and (stringp to)
1731                    (not (string-equal to "")))
1732               (progn
1733                 (insert (format "To: %s\n" to))
1734                 (setq recipients to)
1735                 ))
1736           (if (and (stringp cc)
1737                    (not (string-equal cc "")))
1738               (progn
1739                 (insert (format "cc: %s\n" cc))
1740                 (if recipients
1741                     (setq recipients (concat recipients "," cc))
1742                   (setq recipients cc)
1743                   )))
1744           (insert (format "Content-Type: %s\n" ctype))
1745           (if encoding
1746               (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1747             )
1748           (insert "\n")
1749           (if (null
1750                (let ((mc-pgp-always-sign 'never))
1751                  (mc-pgp-encrypt-region
1752                   (mc-split "\\([ \t\n]*,[ \t\n]*\\)+" recipients)
1753                   (point-min) (point-max) from nil)
1754                  ))
1755               (throw 'mime-editor/error 'pgp-error)
1756             )
1757           (goto-char beg)
1758           (insert (format "--[[multipart/encrypted;
1759  boundary=\"%s\";
1760  protocol=\"application/pgp-encrypted\"][7bit]]
1761 --%s
1762 Content-Type: application/pgp-encrypted
1763
1764 --%s
1765 Content-Type: application/octet-stream
1766 Content-Transfer-Encoding: 7bit
1767
1768 " pgp-boundary pgp-boundary pgp-boundary))
1769           (goto-char (point-max))
1770           (insert (format "\n--%s--\n" pgp-boundary))
1771           )))))
1772
1773 (defun mime-editor/process-pgp-kazu (type beg end boundary)
1774   (save-excursion
1775     (save-restriction
1776       (narrow-to-region beg end)
1777       (let* ((ret
1778               (mime-editor/translate-region beg end boundary))
1779              (ctype    (car ret))
1780              (encoding (nth 1 ret))
1781              (parts    (nth 3 ret))
1782              )
1783         (goto-char beg)
1784         (insert (format "Content-Type: %s\n" ctype))
1785         (if encoding
1786             (insert (format "Content-Transfer-Encoding: %s\n" encoding))
1787           )
1788         (insert "\n")
1789         (if (null
1790              (progn
1791                (goto-char beg)
1792                (insert "=\n")
1793                (prog1
1794                    (let ((mail-header-separator "="))
1795                      (call-interactively type)
1796                      )
1797                  (goto-char beg)
1798                  (and (search-forward "=\n")
1799                       (replace-match ""))
1800                  )))
1801             (throw 'mime-editor/error 'pgp-error)
1802           )
1803         (goto-char beg)
1804         (insert
1805          "--[[application/pgp; format=mime][7bit]]\n")
1806         ))
1807     ))
1808
1809 (defun mime-editor/translate-body ()
1810   "Encode the tagged MIME body in current buffer in MIME compliant message."
1811   (interactive)
1812   (save-excursion
1813     (let ((boundary
1814            (concat mime-multipart-boundary "_"
1815                    (replace-space-with-underline (current-time-string))
1816                    ))
1817           (i 1)
1818           ret)
1819       (while (mime-editor/process-multipart-1
1820               (format "%s-%d" boundary i))
1821         (setq i (1+ i))
1822         )
1823       (save-restriction
1824         ;; We are interested in message body.
1825         (let* ((beg
1826                 (progn
1827                   (goto-char (point-min))
1828                   (re-search-forward
1829                    (concat "\n" (regexp-quote mail-header-separator)
1830                            (if mime-ignore-preceding-spaces
1831                                "[ \t\n]*\n" "\n")) nil 'move)
1832                   (point)))
1833                (end
1834                 (progn
1835                   (goto-char (point-max))
1836                   (and mime-ignore-trailing-spaces
1837                        (re-search-backward "[^ \t\n]\n" beg t)
1838                        (forward-char 1))
1839                   (point))))
1840           (setq ret (mime-editor/translate-region
1841                      beg end
1842                      (format "%s-%d" boundary i)))
1843           ))
1844       (let ((contype (car ret))         ;Content-Type
1845             (encoding (nth 1 ret))      ;Content-Transfer-Encoding
1846             )
1847         ;; Make primary MIME headers.
1848         (or (mail-position-on-field "Mime-Version")
1849             (insert mime-editor/mime-version-value))
1850         ;; Remove old Content-Type and other fields.
1851         (save-restriction
1852           (goto-char (point-min))
1853           (search-forward (concat "\n" mail-header-separator "\n") nil t)
1854           (narrow-to-region (point-min) (point))
1855           (goto-char (point-min))
1856           (mime-delete-field "Content-Type")
1857           (mime-delete-field "Content-Transfer-Encoding"))
1858         ;; Then, insert Content-Type and Content-Transfer-Encoding fields.
1859         (mail-position-on-field "Content-Type")
1860         (insert contype)
1861         (if encoding
1862             (progn
1863               (mail-position-on-field "Content-Transfer-Encoding")
1864               (insert encoding)))
1865         ))))
1866
1867 (defun mime-editor/translate-region (beg end &optional boundary multipart)
1868   (if (null boundary)
1869       (setq boundary
1870             (concat mime-multipart-boundary "_"
1871                     (replace-space-with-underline (current-time-string))))
1872     )
1873   (save-excursion
1874     (save-restriction
1875       (narrow-to-region beg end)
1876       (let ((tag nil)                   ;MIME tag
1877             (contype nil)               ;Content-Type
1878             (encoding nil)              ;Content-Transfer-Encoding
1879             (nparts 0))                 ;Number of body parts
1880         ;; Normalize the body part by inserting appropriate message
1881         ;; tags for every message contents.
1882         (mime-editor/normalize-body)
1883         ;; Counting the number of Content-Type.
1884         (goto-char (point-min))
1885         (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1886           (setq nparts (1+ nparts)))
1887         ;; Begin translation.
1888         (cond ((and (<= nparts 1)(not multipart))
1889                ;; It's a singular message.
1890                (goto-char (point-min))
1891                (while (re-search-forward
1892                        mime-editor/single-part-tag-regexp nil t)
1893                  (setq tag
1894                        (buffer-substring (match-beginning 0) (match-end 0)))
1895                  (delete-region (match-beginning 0) (1+ (match-end 0)))
1896                  (setq contype (mime-editor/get-contype tag))
1897                  (setq encoding (mime-editor/get-encoding tag))
1898                  ))
1899               (t
1900                ;; It's a multipart message.
1901                (goto-char (point-min))
1902                (while (re-search-forward
1903                        mime-editor/single-part-tag-regexp nil t)
1904                  (setq tag
1905                        (buffer-substring (match-beginning 0) (match-end 0)))
1906                  (delete-region (match-beginning 0) (match-end 0))
1907                  (setq contype (mime-editor/get-contype tag))
1908                  (setq encoding (mime-editor/get-encoding tag))
1909                  (insert "--" boundary "\n")
1910                  (insert "Content-Type: " contype "\n")
1911                  (if encoding
1912                      (insert "Content-Transfer-Encoding: " encoding "\n"))
1913                  )
1914                ;; Define Content-Type as "multipart/mixed".
1915                (setq contype
1916                      (concat "multipart/mixed;\n boundary=\"" boundary "\""))
1917                ;; Content-Transfer-Encoding must be "7bit".
1918                ;; The following encoding can be `nil', but is
1919                ;; specified as is since there is no way that a user
1920                ;; specifies it.
1921                (setq encoding "7bit")
1922                ;; Insert the trailer.
1923                (goto-char (point-max))
1924                (if multipart
1925                    (insert "--" boundary "--\n")
1926                  (insert "\n--" boundary "--\n")
1927                  )))
1928         (list contype encoding boundary nparts)
1929         ))))
1930
1931 (defun mime-editor/normalize-body ()
1932   "Normalize the body part by inserting appropriate message tags."
1933   ;; Insert the first MIME tags if necessary.
1934   (goto-char (point-min))
1935   (if (not (looking-at mime-editor/single-part-tag-regexp))
1936       (insert (mime-make-text-tag) "\n"))
1937   ;; Check each tag, and add new tag or correct it if necessary.
1938   (goto-char (point-min))
1939   (while (re-search-forward mime-editor/single-part-tag-regexp nil t)
1940     (let* ((tag (buffer-substring (match-beginning 0) (match-end 0)))
1941            (contype (mime-editor/get-contype tag))
1942            (charset (mime-get-parameter contype "charset"))
1943            (encoding (mime-editor/get-encoding tag)))
1944       ;; Remove extra whitespaces after the tag.
1945       (if (looking-at "[ \t]+$")
1946           (delete-region (match-beginning 0) (match-end 0)))
1947       (cond ((= (following-char) ?\^M)
1948              ;; It must be image, audio or video.
1949              (let ((beg (point))
1950                    (end (mime-editor/content-end)))
1951                ;; Insert explicit MIME tags after hidden messages.
1952                (forward-line 1)
1953                (if (and (not (eobp))
1954                         (not (looking-at mime-editor/single-part-tag-regexp)))
1955                    (progn
1956                      (insert (mime-make-text-tag) "\n")
1957                      (forward-line -1)  ;Process it again as text.
1958                      ))
1959                ;; Show a hidden message.  The point is not altered
1960                ;; after the conversion.
1961                (mime-flag-region beg end ?\n)))
1962             ((mime-test-content-type contype "message")
1963              ;; Content-type "message" should be sent as is.
1964              (forward-line 1))
1965             ((mime-test-content-type contype "text")
1966              ;; Define charset for text if necessary.
1967              (setq charset (or charset (mime-editor/choose-charset)))
1968              (mime-editor/define-charset charset)
1969              (if (string-equal contype "text/x-rot13-47")
1970                  (save-excursion
1971                    (forward-line)
1972                    (set-mark (point))
1973                    (goto-char (mime-editor/content-end))
1974                    (tm:caesar-region)
1975                    ))
1976              ;; Point is now on current tag.
1977              ;; Define encoding and encode text if necessary.
1978              (if (null encoding)        ;Encoding is not specified.
1979                  (let* ((encoding
1980                          (cdr
1981                           (assoc charset
1982                                  mime-editor/charset-default-encoding-alist)
1983                           ))
1984                         (beg (mime-editor/content-beginning))
1985                         (end (mime-editor/content-end))
1986                         (body (buffer-substring beg end))
1987                         (encoded (funcall mime-string-encoder
1988                                           (cons charset encoding) body)))
1989                    (if (not (string-equal body encoded))
1990                        (progn
1991                          (goto-char beg)
1992                          (delete-region beg end)
1993                          (insert encoded)
1994                          (goto-char beg)))
1995                    (mime-editor/define-encoding encoding)))
1996              (forward-line 1))
1997             ((null encoding)            ;Encoding is not specified.
1998              ;; Application, image, audio, video, and any other
1999              ;; unknown content-type without encoding should be
2000              ;; encoded.
2001              (let* ((encoding "base64") ;Encode in BASE64 by default.
2002                     (beg (mime-editor/content-beginning))
2003                     (end (mime-editor/content-end))
2004                     (body (buffer-substring beg end))
2005                     (encoded (funcall mime-string-encoder
2006                                       (cons nil encoding) body)))
2007                (if (not (string-equal body encoded))
2008                    (progn
2009                      (goto-char beg)
2010                      (delete-region beg end)
2011                      (insert encoded)
2012                      (goto-char beg)))
2013                (mime-editor/define-encoding encoding))
2014              (forward-line 1))
2015             )
2016       )))
2017
2018 (defun mime-delete-field (field)
2019   "Delete header FIELD."
2020   (let ((regexp (format "^%s:[ \t]*" field)))
2021     (goto-char (point-min))
2022     (while (re-search-forward regexp nil t)
2023       (delete-region (match-beginning 0)
2024                      (progn (forward-line 1) (point)))
2025       )))
2026
2027 \f
2028 ;;;
2029 ;;; Platform dependent functions
2030 ;;;
2031
2032 ;; Emacs 18 implementations
2033
2034 (defun mime-string-encoder-for-emacs18 (method string)
2035   "For given METHOD that is a cons of charset and encoding, encode a STRING."
2036   (let ((charset (car method))
2037         (encoding (cdr method)))
2038     (cond ((stringp encoding)
2039            (mime-encode-string encoding string))
2040           ;; Return string without any encoding.
2041           (t string)
2042           )))
2043
2044 \f
2045 ;; Emacs 19 implementations
2046
2047 (defun mime-string-encoder-for-emacs19 (method string)
2048   "For given METHOD that is a cons of charset and encoding, encode a STRING."
2049   (let ((charset (car method))
2050         (encoding (cdr method)))
2051     (cond ((stringp encoding)
2052            (mime-encode-string encoding string))
2053           ;; Return string without any encoding.
2054           (t string)
2055           )))
2056
2057 \f
2058 ;; NEmacs implementations
2059
2060 (defun mime-string-encoder-for-nemacs (method string)
2061   "For given METHOD that is a cons of charset and encoding, encode a STRING.
2062 US-ASCII and ISO-2022-JP are supported on NEmacs."
2063   (let ((charset (car method))
2064         (encoding (cdr method)))
2065     (cond ((stringp encoding)
2066            (mime-encode-string encoding
2067                                ;; Convert internal (EUC) to JIS code.
2068                                (convert-string-kanji-code string 3 2)
2069                                ))
2070           ;; NEmacs can convert into ISO-2022-JP automatically,
2071           ;; but can do it myself as follows:
2072           ;;(t (convert-string-kanji-code string 3 2))
2073
2074           ;; Return string without any encoding.
2075           (t string)
2076           )))
2077
2078 \f
2079 ;; Mule implementations
2080 ;; Thanks to contributions by wkenji@flab.fujitsu.co.jp (Kenji
2081 ;; WAKAMIYA) and handa@etl.go.jp (Kenichi Handa).
2082
2083 (defun mime-string-encoder-for-mule (method string)
2084   "For given METHOD that is a cons of charset and encoding, encode a
2085 STRING.  US-ASCII, ISO-8859-* (except for ISO-8859-6), ISO-2022-JP,
2086 ISO-2022-JP-2 and ISO-2022-INT-1 are supported on Mule.  Either of
2087 charset ISO-2022-JP-2 or ISO-2022-INT-1 is used for multilingual
2088 text."
2089   (let* ((charset (car method))
2090          (encoding (cdr method))
2091          (coding-system
2092           (cdr (assoc (and (stringp charset) (upcase charset))
2093                       '(("ISO-8859-1" . *ctext*)
2094                         ("ISO-8859-2" . *iso-8859-2*)
2095                         ("ISO-8859-3" . *iso-8859-3*)
2096                         ("ISO-8859-4" . *iso-8859-4*)
2097                         ("ISO-8859-5" . *iso-8859-5*)
2098                         ;;("ISO-8859-6" . *iso-8859-6*)
2099                         ("ISO-8859-7" . *iso-8859-7*)
2100                         ("ISO-8859-8" . *iso-8859-8*)
2101                         ("ISO-8859-9" . *iso-8859-9*)
2102                         ("ISO-2022-JP" . *junet*)
2103                         ("ISO-2022-JP-2" . *iso-2022-ss2-7*)
2104                         ("ISO-2022-KR" . *korean-mail*)
2105                         ("ISO-2022-INT-1" . *iso-2022-int-1*)
2106                         )))))
2107     ;; In bilingual environment it may be unnecessary to convert the
2108     ;; coding system of the string unless transfer encoding is
2109     ;; required since such conversion may be performed by mule
2110     ;; automatically.
2111     (if (not (null coding-system))
2112         (setq string (code-convert-string string *internal* coding-system)))
2113     (if (stringp encoding)
2114         (setq string (mime-encode-string encoding string)))
2115     string
2116     ))
2117
2118 \f
2119 ;; Sun implementations
2120
2121 (defun mime-voice-recorder-for-sun ()
2122   "Record voice in a buffer using Sun audio device, and return the buffer.
2123 If the environment variable AUDIOHOST is defined, its value is used as
2124 a recording host instead of local host."
2125   (let ((buffer (get-buffer-create " *MIME audio*"))
2126         (host (getenv "AUDIOHOST")))
2127     (message "Start the recording on %s.  Type C-g to finish the recording..."
2128              (or host (system-name)))
2129     (save-excursion
2130       (set-buffer buffer)
2131       (erase-buffer)
2132       (condition-case errorcode
2133           (let ((selective-display nil) ;Disable ^M to nl translation.
2134                 (mc-flag nil)           ;Mule
2135                 (kanji-flag nil))       ;NEmacs
2136             ;; If AUDIOHOST is defined, use the value as recording host.
2137             (cond ((not (null host))
2138                    ;; Disable automatic conversion of coding system if Mule.
2139                    (if (featurep 'mule)
2140                        (define-program-coding-system nil "rsh" *noconv*))
2141                    (call-process "rsh"
2142                                  nil
2143                                  buffer
2144                                  nil
2145                                  host
2146                                  "cat"
2147                                  "/dev/audio"
2148                                  ))
2149                   (t
2150                    ;; Disable automatic conversion of coding system if Mule.
2151                    (if (featurep 'mule)
2152                        (define-program-coding-system nil "cat" *noconv*))
2153                    (call-process "cat"
2154                                  "/dev/audio"
2155                                  buffer
2156                                  nil
2157                                  ))))
2158         (quit (message "Type C-g to finish recording... done.")
2159               buffer                    ;Return the buffer
2160               )))))
2161
2162 \f
2163 ;;; @ Other useful commands.
2164 ;;;
2165
2166 ;; Message forwarding commands as content-type "message/rfc822".
2167
2168 (defun mime-editor/insert-message (&optional message)
2169   (interactive)
2170   (let ((inserter (assoc-value major-mode mime-editor/message-inserter-alist)))
2171     (if (and inserter (fboundp inserter))
2172         (progn
2173           (mime-editor/insert-tag "message" "rfc822")
2174           (funcall inserter message)
2175           )
2176       (message "Sorry, I don't have message inserter for your MUA.")
2177       )))
2178
2179 (defun mime-editor/insert-mail (&optional message)
2180   (interactive)
2181   (let ((inserter (assoc-value major-mode mime-editor/mail-inserter-alist)))
2182     (if (and inserter (fboundp inserter))
2183         (progn
2184           (mime-editor/insert-tag "message" "rfc822")
2185           (funcall inserter message)
2186           )
2187       (message "Sorry, I don't have mail inserter for your MUA.")
2188       )))
2189
2190 (defun mime-editor/inserted-message-filter ()
2191   (save-excursion
2192     (save-restriction
2193       (let ((header-start (point))
2194             (case-fold-search t)
2195             beg end)
2196         ;; for Emacs 18
2197         ;; (if (re-search-forward "^$" (marker-position (mark-marker)))
2198         (if (re-search-forward "^$" (mark t))
2199             (narrow-to-region header-start (match-beginning 0))
2200           )
2201         (goto-char header-start)
2202         (while (and (re-search-forward
2203                      mime-editor/yank-ignored-field-regexp nil t)
2204                     (setq beg (match-beginning 0))
2205                     (setq end (1+ (rfc822/field-end)))
2206                     )
2207           (delete-region beg end)
2208           )
2209         ))))
2210
2211
2212 ;;; @ multipart enclosure
2213 ;;;
2214
2215 (defun mime-editor/enclose-region (type beg end)
2216   (save-excursion
2217     (goto-char beg)
2218     (let ((current (point))
2219           exist-prev-tag)
2220       (save-excursion
2221         (if (mime-editor/goto-tag)
2222             (or (eq current (match-beginning 0))
2223                 (setq exist-prev-tag t)
2224                 )))
2225       (save-restriction
2226         (narrow-to-region beg end)
2227         (goto-char beg)
2228         (if exist-prev-tag
2229             (insert "\n")
2230           )
2231         (insert (format "--<<%s>>-{\n" type))
2232         (goto-char (point-max))
2233         (insert (format "\n--}-<<%s>>\n" type))
2234         (goto-char (point-max))
2235         )
2236       (if (and (not (looking-at mime-editor/single-part-tag-regexp))
2237                (not (eobp)))
2238           (insert (mime-make-text-tag) "\n")
2239         )
2240       )))
2241
2242 (defun mime-editor/enclose-mixed-region (beg end)
2243   (interactive "*r")
2244   (mime-editor/enclose-region "mixed" beg end)
2245   )
2246
2247 (defun mime-editor/enclose-parallel-region (beg end)
2248   (interactive "*r")
2249   (mime-editor/enclose-region "parallel" beg end)
2250   )
2251
2252 (defun mime-editor/enclose-digest-region (beg end)
2253   (interactive "*r")
2254   (mime-editor/enclose-region "digest" beg end)
2255   )
2256
2257 (defun mime-editor/enclose-alternative-region (beg end)
2258   (interactive "*r")
2259   (mime-editor/enclose-region "alternative" beg end)
2260   )
2261
2262 (defun mime-editor/enclose-signed-region (beg end)
2263   (interactive "*r")
2264   (if mime-editor/signing-type
2265       (mime-editor/enclose-region "signed" beg end)
2266     (message "Please specify signing type.")
2267     ))
2268
2269 (defun mime-editor/enclose-encrypted-region (beg end)
2270   (interactive "*r")
2271   (if mime-editor/signing-type
2272       (mime-editor/enclose-region "encrypted" beg end)
2273     (message "Please specify encrypting type.")
2274     ))
2275
2276 (defun mime-editor/insert-key (&optional arg)
2277   "Insert a pgp public key."
2278   (interactive "P")
2279   (mime-editor/insert-tag "application" "pgp-keys")
2280   (mime-editor/define-encoding "7bit")
2281   (mc-insert-public-key)
2282   )
2283
2284
2285 ;;; @ flag setting
2286 ;;;
2287
2288 (defun mime-editor/set-split (arg)
2289   (interactive
2290    (list
2291     (y-or-n-p "Do you want to enable split?")
2292     ))
2293   (setq mime-editor/split-message arg)
2294   (if arg
2295       (message "This message is enabled to split.")
2296     (message "This message is not enabled to split.")
2297     ))
2298
2299 (defun mime-editor/toggle-transfer-level (&optional transfer-level)
2300   "Toggle transfer-level is 7bit or 8bit through.
2301
2302 Optional TRANSFER-LEVEL is a number of transfer-level, 7 or 8."
2303   (interactive)
2304   (if (numberp transfer-level)
2305       (setq mime-editor/transfer-level transfer-level)
2306     (if (< mime-editor/transfer-level 8)
2307         (setq mime-editor/transfer-level 8)
2308       (setq mime-editor/transfer-level 7)
2309       ))
2310   (setq mime-editor/charset-default-encoding-alist
2311         (mime/make-charset-default-encoding-alist
2312          mime-editor/transfer-level))
2313   (message (format "Current transfer-level is %d bit"
2314                    mime-editor/transfer-level))
2315   (setq mime-editor/transfer-level-string
2316         (mime/encoding-name mime-editor/transfer-level 'not-omit))
2317   (force-mode-line-update)
2318   )
2319
2320
2321 ;;; @ pgp
2322 ;;;
2323
2324 (defun mime-editor/set-sign (arg)
2325   (interactive
2326    (list
2327     (y-or-n-p "Do you want to sign?")
2328     ))
2329   (if arg
2330       (if mime-editor/signing-type
2331           (progn
2332             (setq mime-editor/pgp-processing 'sign)
2333             (message "This message will be signed.")
2334             )
2335         (message "Please specify signing type.")
2336         )
2337     (if (eq mime-editor/pgp-processing 'sign)
2338         (setq mime-editor/pgp-processing nil)
2339       )
2340     (message "This message will not be signed.")
2341     ))
2342
2343 (defun mime-editor/set-encrypt (arg)
2344   (interactive
2345    (list
2346     (y-or-n-p "Do you want to encrypt?")
2347     ))
2348   (if arg
2349       (if mime-editor/encrypting-type
2350           (progn
2351             (setq mime-editor/pgp-processing 'encrypt)
2352             (message "This message will be encrypt.")
2353             )
2354         (message "Please specify encrypting type.")
2355         )
2356     (if (eq mime-editor/pgp-processing 'encrypt)
2357         (setq mime-editor/pgp-processing nil)
2358       )
2359     (message "This message will not be encrypt.")
2360     ))
2361
2362 (defvar mime-editor/pgp-processing nil)
2363 (make-variable-buffer-local 'mime-editor/pgp-processing)
2364
2365 (defun mime-editor/pgp-enclose-buffer ()
2366   (let ((beg (save-excursion
2367                (goto-char (point-min))
2368                (if (search-forward (concat "\n" mail-header-separator "\n"))
2369                    (match-end 0)
2370                  )))
2371         (end (point-max))
2372         )
2373     (if beg
2374         (cond ((eq mime-editor/pgp-processing 'sign)
2375                (mime-editor/enclose-signed-region beg end)
2376                )
2377               ((eq mime-editor/pgp-processing 'encrypt)
2378                (mime-editor/enclose-encrypted-region beg end)
2379                ))
2380       )))
2381
2382
2383 ;;; @ split
2384 ;;;
2385
2386 (defun mime-editor/insert-partial-header
2387   (fields subject id number total separator)
2388   (insert fields)
2389   (insert (format "Subject: %s (%d/%d)\n" subject number total))
2390   (insert (format "Mime-Version: 1.0 (split by tm-edit %s)\n"
2391                   mime-editor/version))
2392   (insert (format "\
2393 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2394                   id number total separator))
2395   )
2396
2397 (defun mime-editor/split-and-send
2398   (&optional cmd lines mime-editor/message-max-length)
2399   (interactive)
2400   (or lines
2401       (setq lines
2402             (count-lines (point-min) (point-max)))
2403       )
2404   (or mime-editor/message-max-length
2405       (setq mime-editor/message-max-length
2406             (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2407                 mime-editor/message-default-max-length))
2408       )
2409   (let* ((mime-editor/draft-file-name 
2410           (or (buffer-file-name)
2411               (make-temp-name
2412                (expand-file-name "tm-draft" mime/tmp-dir))))
2413          (separator mail-header-separator)
2414          (config
2415           (eval (cdr (assq major-mode mime-editor/window-config-alist))))
2416          (id (concat "\""
2417                      (replace-space-with-underline (current-time-string))
2418                      "@" (system-name) "\"")))
2419     (run-hooks 'mime-editor/before-split-hook)
2420     (let* ((header (rfc822/get-header-string-except
2421                     mime-editor/split-ignored-field-regexp separator))
2422            (subject (mail-fetch-field "subject"))
2423            (total (+ (/ lines mime-editor/message-max-length)
2424                      (if (> (mod lines mime-editor/message-max-length) 0)
2425                          1)))
2426            (the-buf (current-buffer))
2427            (buf (get-buffer "*tmp-send*"))
2428            (command
2429             (or cmd
2430                 (cdr
2431                  (assq major-mode
2432                        mime-editor/split-message-sender-alist))
2433                 (cdr
2434                  (assq major-mode
2435                        mime-editor/message-default-sender-alist))
2436                 ))
2437            data)
2438       (goto-char (point-min))
2439       (if (re-search-forward (concat "^" (regexp-quote separator) "$")
2440                              nil t)
2441           (replace-match "")
2442         )
2443       (if buf
2444           (progn
2445             (switch-to-buffer buf)
2446             (erase-buffer)
2447             (switch-to-buffer the-buf)
2448             )
2449         (setq buf (get-buffer-create "*tmp-send*"))
2450         )
2451       (switch-to-buffer buf)
2452       (make-local-variable 'mail-header-separator)
2453       (setq mail-header-separator separator)
2454       (switch-to-buffer the-buf)
2455       (goto-char (point-min))
2456       (re-search-forward "^$" nil t)
2457       (let ((mime-editor/partial-number 1))
2458         (setq data (buffer-substring
2459                     (point-min)
2460                     (progn
2461                       (goto-line mime-editor/message-max-length)
2462                       (point))
2463                     ))
2464         (delete-region (point-min)(point))
2465         (switch-to-buffer buf)
2466         (mime-editor/insert-partial-header
2467          header subject id mime-editor/partial-number total separator)
2468         (insert data)
2469         (save-excursion
2470           (save-restriction
2471             (goto-char (point-min))
2472             (search-forward (concat "\n" mail-header-separator "\n"))
2473             (narrow-to-region
2474              (match-end 0)
2475              (if (re-search-forward "^$" nil t)
2476                  (match-beginning 0)
2477                (point-max)
2478                ))
2479             (goto-char (point-min))
2480             (while (re-search-forward
2481                     mime-editor/split-blind-field-regexp nil t)
2482               (delete-region (match-beginning 0)
2483                              (let ((e (rfc822/field-end)))
2484                                (if (< e (point-max))
2485                                    (1+ e)
2486                                  e)))
2487               )
2488             ))
2489         (save-excursion
2490           (message (format "Sending %d/%d..."
2491                            mime-editor/partial-number total))
2492           (call-interactively command)
2493           (message (format "Sending %d/%d... done"
2494                            mime-editor/partial-number total))
2495           )
2496         (erase-buffer)
2497         (switch-to-buffer the-buf)
2498         (setq mime-editor/partial-number 2)
2499         (while (< mime-editor/partial-number total)
2500           (setq data (buffer-substring
2501                       (point-min)
2502                       (progn
2503                         (goto-line mime-editor/message-max-length)
2504                         (point))
2505                       ))
2506           (delete-region (point-min)(point))
2507           (switch-to-buffer buf)
2508           (mime-editor/insert-partial-header
2509            header subject id mime-editor/partial-number total separator)
2510           (insert data)
2511           (save-excursion
2512             (message (format "Sending %d/%d..."
2513                              mime-editor/partial-number total))
2514             (call-interactively command)
2515             (message (format "Sending %d/%d... done"
2516                              mime-editor/partial-number total))
2517             )
2518           (erase-buffer)
2519           (switch-to-buffer the-buf)
2520           (setq mime-editor/partial-number
2521                 (1+ mime-editor/partial-number))
2522           )
2523         (goto-char (point-min))
2524         (mime-editor/insert-partial-header
2525          header subject id mime-editor/partial-number total separator)
2526         (message (format "Sending %d/%d..."
2527                          mime-editor/partial-number total))
2528         ))))
2529
2530 (defun mime-editor/maybe-split-and-send (&optional cmd)
2531   (interactive)
2532   (run-hooks 'mime-editor/before-send-hook)
2533   (let ((mime-editor/message-max-length
2534          (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2535              mime-editor/message-default-max-length))
2536         (lines (count-lines (point-min) (point-max)))
2537         )
2538     (if (and (> lines mime-editor/message-max-length)
2539              mime-editor/split-message)
2540         (mime-editor/split-and-send cmd lines mime-editor/message-max-length)
2541       )))
2542
2543
2544 ;;; @ preview message
2545 ;;;
2546
2547 (defun mime-editor/preview-message ()
2548   "preview editing MIME message. [tm-edit.el]"
2549   (interactive)
2550   (let* ((str (buffer-string))
2551          (separator mail-header-separator)
2552          (the-buf (current-buffer))
2553          (buf-name (buffer-name))
2554          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2555          (buf (get-buffer temp-buf-name))
2556          )
2557     (if buf
2558         (progn
2559           (switch-to-buffer buf)
2560           (erase-buffer)
2561           )
2562       (setq buf (get-buffer-create temp-buf-name))
2563       (switch-to-buffer buf)
2564       )
2565     (insert str)
2566     (setq major-mode 'mime/temporary-message-mode)
2567     (make-local-variable 'mail-header-separator)
2568     (setq mail-header-separator separator)
2569     (make-local-variable 'mime/editing-buffer)
2570     (setq mime/editing-buffer the-buf)
2571     
2572     (run-hooks 'mime-editor/translate-hook)
2573     (mime-editor/translate-buffer)
2574     (goto-char (point-min))
2575     (if (re-search-forward
2576          (concat "^" (regexp-quote separator) "$"))
2577         (replace-match "")
2578       )
2579     (mime/viewer-mode)
2580     ))
2581
2582 (defun mime-editor/quitting-method ()
2583   (let ((temp mime::preview/article-buffer)
2584         buf)
2585     (mime-viewer/kill-buffer)
2586     (set-buffer temp)
2587     (setq buf mime/editing-buffer)
2588     (kill-buffer temp)
2589     (switch-to-buffer buf)
2590     ))
2591
2592 (set-alist 'mime-viewer/quitting-method-alist
2593            'mime/temporary-message-mode
2594            (function mime-editor/quitting-method)
2595            )
2596
2597
2598 ;;; @ draft preview
2599 ;;; 
2600 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2601 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2602
2603 (defvar mime-editor/draft-header-separator-alist
2604   '((news-reply-mode . mail-header-separator)
2605     (mh-letter-mode . mail-header-separator)
2606     ))
2607
2608 (defvar mime::article/draft-header-separator nil)
2609
2610 (defun mime-editor/draft-preview ()
2611   (interactive)
2612   (let ((sep (cdr (assq major-mode mime-editor/draft-header-separator-alist))))
2613     (or (stringp sep) (setq sep (eval sep)))
2614     (make-variable-buffer-local 'mime::article/draft-header-separator)
2615     (goto-char (point-min))
2616     (re-search-forward
2617      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2618     (setq mime::article/draft-header-separator
2619           (buffer-substring (match-beginning 0) (match-end 0)))
2620     (replace-match "")
2621     (mime/viewer-mode (current-buffer))
2622     (pop-to-buffer (current-buffer))
2623     ))
2624
2625 (defun mime-viewer::quitting-method/draft-preview ()
2626   (let ((mother mime::preview/mother-buffer))
2627     (save-excursion
2628       (switch-to-buffer mother)
2629       (goto-char (point-min))
2630       (if (and
2631            (re-search-forward
2632             (concat "^\\("
2633                     (regexp-quote mime::article/draft-header-separator)
2634                     "\\)?$") nil t)
2635            (bolp))
2636           (progn
2637             (insert mime::article/draft-header-separator)
2638             (set-buffer-modified-p (buffer-modified-p))
2639             )))
2640     (mime-viewer/kill-buffer)
2641     (pop-to-buffer mother)
2642     ))
2643
2644 (set-alist 'mime-viewer/quitting-method-alist
2645            'mh-letter-mode
2646            (function mime-viewer::quitting-method/draft-preview)
2647            )
2648
2649 (set-alist 'mime-viewer/quitting-method-alist
2650            'news-reply-mode
2651            (function mime-viewer::quitting-method/draft-preview)
2652            )
2653
2654
2655 ;;; @ edit again
2656 ;;;
2657
2658 (defun mime-editor::edit-again (code-conversion)
2659   (save-excursion
2660     (goto-char (point-min))
2661     (let ((ctl (mime/Content-Type)))
2662       (if ctl
2663           (let ((ctype (car ctl))
2664                 (params (cdr ctl))
2665                 type stype)
2666             (if (string-match "/" ctype)
2667                 (progn
2668                   (setq type (substring ctype 0 (match-beginning 0)))
2669                   (setq stype (substring ctype (match-end 0)))
2670                   )
2671               (setq type ctype)
2672               )
2673             (cond ((string-equal type "multipart")
2674                    (let ((boundary (assoc-value "boundary" params)))
2675                      (re-search-forward (concat "\n--" boundary) nil t)
2676                      (let ((bb (match-beginning 0)) eb tag)
2677                        (setq tag (format "\n--<<%s>>-{" stype))
2678                        (goto-char bb)
2679                        (insert tag)
2680                        (setq bb (+ bb (length tag)))
2681                        (re-search-forward (concat "\n--" boundary "--") nil t)
2682                        (setq eb (match-beginning 0))
2683                        (replace-match (format "\n--}-<<%s>>" stype))
2684                        (save-restriction
2685                          (narrow-to-region bb eb)
2686                          (goto-char (point-min))
2687                          (while (re-search-forward
2688                                  (concat "\n--" boundary "\n") nil t)
2689                            (let ((beg (match-beginning 0))
2690                                  end)
2691                              (delete-region beg (match-end 0))
2692                              (save-excursion
2693                                (if (re-search-forward
2694                                     (concat "\n--" boundary) nil t)
2695                                    (setq end (match-beginning 0))
2696                                  (setq end (point-max))
2697                                  )
2698                                (save-restriction
2699                                  (narrow-to-region beg end)
2700                                  (mime-editor::edit-again code-conversion)
2701                                  (goto-char (point-max))
2702                                  ))))
2703                          ))
2704                      (goto-char (point-min))
2705                      (or (= (point-min) 1)
2706                          (delete-region (point-min)
2707                                         (if (re-search-forward "^$" nil t)
2708                                             (match-end 0)
2709                                           (point-min)
2710                                           )))
2711                      ))
2712                   (t
2713                    (let* ((str (rfc822/get-header-string-except
2714                                 "^Content-Type" ""))
2715                           charset
2716                           (pstr
2717                            (mapconcat (function
2718                                        (lambda (attr)
2719                                          (if (string-equal (car attr)
2720                                                            "charset")
2721                                              (progn
2722                                                (setq charset (cdr attr))
2723                                                "")
2724                                            (concat ";" (car attr)
2725                                                    "=" (cdr attr))
2726                                            )
2727                                          ))
2728                                       params ""))
2729                           )
2730                      (if code-conversion
2731                          (if charset
2732                              (mime/code-convert-region-to-emacs
2733                               (point-min) (point-max) charset)
2734                            (code-convert-region
2735                             (point-min) (point-max)
2736                             mime/default-coding-system *internal*)
2737                            ))
2738                      (and str
2739                           (setq pstr (concat pstr "\n" str))
2740                           )
2741                      (let ((he
2742                             (if (re-search-forward "^$" nil t)
2743                                 (match-end 0)
2744                               (point-min)
2745                               )))
2746                        (if (= (point-min) 1)
2747                            (progn
2748                              (goto-char he)
2749                              (insert
2750                               (concat
2751                                "\n"
2752                                (mime-create-tag (concat type "/" stype))
2753                                ))
2754                              )
2755                          (delete-region (point-min) he)
2756                          (insert
2757                           (concat "\n" (mime-create-tag
2758                                         (concat type "/" stype pstr))))
2759                          ))
2760                      ))))
2761         (if code-conversion
2762             (code-convert-region (point-min) (point-max)
2763                                  mime/default-coding-system *internal*)
2764           )
2765         ))))
2766
2767 (defun mime/edit-again (&optional code-conversion no-separator no-mode)
2768   (interactive)
2769   (mime-editor::edit-again code-conversion)
2770   (goto-char (point-min))
2771   (save-restriction
2772     (narrow-to-region (point-min)
2773                       (if (re-search-forward "^$" nil t)
2774                           (match-end 0)
2775                         (point-max)
2776                         ))
2777     (goto-char (point-min))
2778     (while (re-search-forward
2779             "^\\(Content-.*\\|Mime-Version\\):" nil t)
2780       (delete-region (match-beginning 0) (1+ (rfc822/field-end)))
2781       ))
2782   (or no-separator
2783       (and (re-search-forward "^$")
2784            (replace-match mail-header-separator)
2785            ))
2786   (or no-mode
2787       (mime/editor-mode)
2788       ))
2789
2790
2791 ;;; @ end
2792 ;;;
2793
2794 (provide 'tm-edit)
2795
2796 (run-hooks 'tm-edit-load-hook)
2797
2798 ;;; tm-edit.el ends here