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