(mime-editor/version-name): New constant.
[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 by UMEDA Masanobu;
11 ;;;          1996/05/24 renamed from tm-edit.el
12 ;;; Version: $Revision: 0.4 $
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 "mime-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.4 1996-05-25 14:42:47 morioka Exp $")
127
128 (defconst mime-editor/version (get-version-string mime-editor/RCS-ID))
129
130 (defconst mime-editor/version-name
131   (concat "SEMI mime-edit " mime-editor/version))
132
133
134 ;;; @ variables
135 ;;;
136
137 (defvar mime-prefix "\C-c\C-x"
138   "*Keymap prefix for MIME commands.")
139
140 (defvar mime-ignore-preceding-spaces nil
141   "*Ignore preceding white spaces if non-nil.")
142
143 (defvar mime-ignore-trailing-spaces nil
144   "*Ignore trailing white spaces if non-nil.")
145
146 (defvar mime-ignore-same-text-tag t
147   "*Ignore preceding text content-type tag that is same with new one.
148 If non-nil, the text tag is not inserted unless something different.")
149
150 (defvar mime-auto-hide-body t
151   "*Hide non-textual body encoded in base64 after insertion if non-nil.")
152
153 (defvar mime-voice-recorder
154   (function mime-voice-recorder-for-sun)
155   "*Function to record a voice message and return a buffer that contains it.")
156
157 (defvar mime/editor-mode-hook nil
158   "*Hook called when enter MIME mode.")
159
160 (defvar mime-editor/translate-hook nil
161   "*Hook called before translating into a MIME compliant message.
162 To insert a signature file automatically, call the function
163 `mime-editor/insert-signature' from this hook.")
164
165 (defvar mime-editor/exit-hook nil
166   "*Hook called when exit MIME mode.")
167
168 (defvar mime-content-types
169   '(("text"
170      ;; Charset parameter need not to be specified, since it is
171      ;; defined automatically while translation.
172      ("plain"
173       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
174       )
175      ("richtext"
176       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
177       )
178      ("enriched"
179       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
180       )
181      ("x-latex"
182       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
183       )
184      ("html"
185       ;;("charset" "" "ISO-2022-JP" "US-ASCII" "ISO-8859-1" "ISO-8859-8")
186       )
187      ("x-rot13-47")
188      )
189     ("message"
190      ("external-body"
191       ("access-type"
192        ("anon-ftp"
193         ("site" "ftp.jaist.ac.jp" "wnoc-fuk.wide.ad.jp" "nic.karrn.ad.jp")
194         ("directory" "/pub/GNU/elisp/mime")
195         ("name")
196         ("mode" "image" "ascii" "local8"))
197        ("ftp"
198         ("site")
199         ("directory")
200         ("name")
201         ("mode" "image" "ascii" "local8"))
202        ("tftp"        ("site") ("name"))
203        ("afs"         ("site") ("name"))
204        ("local-file"  ("site") ("name"))
205        ("mail-server" ("server" "ftpmail@nic.karrn.ad.jp"))
206        ))
207      ("rfc822")
208      )
209     ("application"
210      ("octet-stream" ("type" "" "tar" "shar"))
211      ("postscript")
212      ("x-kiss" ("x-cnf")))
213     ("image"
214      ("gif")
215      ("jpeg")
216      ("tiff")
217      ("x-pic")
218      ("x-mag")
219      ("x-xwd")
220      ("x-xbm")
221      )
222     ("audio" ("basic"))
223     ("video" ("mpeg"))
224     )
225   "*Alist of content-type, subtype, parameters and its values.")
226
227 (defvar mime-file-types
228   '(("\\.rtf$"
229      "text"     "richtext"      nil
230      nil
231      nil                nil)
232     ("\\.html$"
233      "text"     "html"          nil
234      nil
235      nil                nil)
236     ("\\.ps$"
237      "application" "postscript" nil
238      "quoted-printable"
239      "attachment"       (("filename" . file))
240      )
241     ("\\.jpg$"
242      "image"    "jpeg"          nil
243      "base64"
244      "inline"           (("filename" . file))
245      )
246     ("\\.gif$"
247      "image"    "gif"           nil
248      "base64"
249      "inline"           (("filename" . file))
250      )
251     ("\\.tiff$"
252      "image"    "tiff"          nil
253      "base64"
254      "inline"           (("filename" . file))
255      )
256     ("\\.pic$"
257      "image"    "x-pic"         nil
258      "base64"
259      "inline"           (("filename" . file))
260      )
261     ("\\.mag$"
262      "image"    "x-mag"         nil
263      "base64"
264      "inline"           (("filename" . file))
265      )
266     ("\\.xbm$"
267      "image"    "x-xbm"         nil
268      "base64"
269      "inline"           (("filename" . file))
270      )
271     ("\\.xwd$"
272      "image"    "x-xwd"         nil
273      "base64"
274      "inline"           (("filename" . file))
275      )
276     ("\\.au$"
277      "audio"    "basic"         nil
278      "base64"
279      "attachment"               (("filename" . file))
280      )
281     ("\\.mpg$"
282      "video"    "mpeg"          nil
283      "base64"
284      "attachment"       (("filename" . file))
285      )
286     ("\\.el$"
287      "application" "octet-stream" (("type" . "emacs-lisp"))
288      "7bit"
289      "attachment"       (("filename" . file))
290      )
291     ("\\.lsp$"
292      "application" "octet-stream" (("type" . "common-lisp"))
293      "7bit"
294      "attachment"       (("filename" . file))
295      )
296     ("\\.tar\\.gz$"
297      "application" "octet-stream" (("type" . "tar+gzip"))
298      nil
299      "attachment"       (("filename" . file))
300      )
301     ("\\.tgz$"
302      "application" "octet-stream" (("type" . "tar+gzip"))
303      nil
304      "attachment"       (("filename" . file))
305      )
306     ("\\.tar\\.Z$"
307      "application" "octet-stream" (("type" . "tar+compress"))
308      nil
309      "attachment"       (("filename" . file))
310      )
311     ("\\.taz$"
312      "application" "octet-stream" (("type" . "tar+compress"))
313      nil
314      "attachment"       (("filename" . file))
315      )
316     ("\\.gz$"
317      "application" "octet-stream" (("type" . "gzip"))
318      nil
319      "attachment"       (("filename" . file))
320      )
321     ("\\.Z$"
322      "application" "octet-stream" (("type" . "compress"))
323      nil
324      "attachment"       (("filename" . file))
325      )
326     ("\\.lzh$"
327      "application" "octet-stream" (("type" . "lha"))
328      nil
329      "attachment"       (("filename" . file))
330      )
331     ("\\.zip$"
332      "application" "zip" nil
333      nil
334      "attachment"       (("filename" . file))
335      )
336     ("\\.diff$"
337      "application" "octet-stream" (("type" . "patch"))
338      nil
339      "attachment"       (("filename" . file))
340      )
341     ("\\.signature"
342      "text"     "plain"         nil     nil)
343     (".*"
344      "application" "octet-stream" nil
345      nil
346      "attachment"       (("filename" . file))
347      )
348     )
349   "*Alist of file name, types, parameters, and default encoding.
350 If encoding is nil, it is determined from its contents.")
351
352 ;;; @@ about charset, encoding and transfer-level
353 ;;;
354
355 (defvar mime-editor/transfer-level 7
356   "*A number of network transfer level. It should be bigger than 7.")
357 (make-variable-buffer-local 'mime-editor/transfer-level)
358
359 (defvar mime-editor/transfer-level-string
360   (mime/encoding-name mime-editor/transfer-level 'not-omit)
361   "*A string formatted version of mime/defaul-transfer-level")
362 (make-variable-buffer-local 'mime-editor/transfer-level-string)
363
364 (defvar mime-editor/charset-default-encoding-alist
365   (mime/make-charset-default-encoding-alist mime-editor/transfer-level))
366 (make-variable-buffer-local 'mime-editor/charset-default-encoding-alist)
367
368 ;;; @@ about message inserting
369 ;;;
370
371 (defvar mime-editor/yank-ignored-field-list
372   '("Received" "Approved" "Path" "Replied" "Status" "X-VM-.*" "X-UIDL")
373   "Delete these fields from original message when it is inserted
374 as message/rfc822 part.
375 Each elements are regexp of field-name. [mime-edit.el]")
376
377 (defvar mime-editor/yank-ignored-field-regexp
378   (concat "^"
379           (apply (function regexp-or) mime-editor/yank-ignored-field-list)
380           ":"))
381
382 (defvar mime-editor/message-inserter-alist nil)
383 (defvar mime-editor/mail-inserter-alist nil)
384
385 ;;; @@ about message splitting
386 ;;;
387
388 (defvar mime-editor/split-message t
389   "*Split large message if it is non-nil. [mime-edit.el]")
390
391 (defvar mime-editor/message-default-max-length 1000
392   "*Default maximum size of a message. [mime-edit.el]")
393
394 (defvar mime-editor/message-max-length-alist
395   '((news-reply-mode . 500)))
396
397 (defconst mime-editor/split-ignored-field-regexp
398   "\\(^Content-\\|^Subject:\\|^Mime-Version:\\)")
399
400 (defvar mime-editor/split-blind-field-regexp
401   "\\(^[BDFbdf]cc:\\|^cc:[ \t]*$\\)")
402
403 (defvar mime-editor/message-default-sender-alist
404   '((mail-mode . mail-send-and-exit)
405     (mh-letter-mode . mh-send-letter)
406     (news-reply-mode . gnus-inews-news)
407     ))
408
409 (defvar mime-editor/split-message-sender-alist
410   '((mail-mode
411      . (lambda ()
412          (interactive)
413          (sendmail-send-it)
414          ))
415     (mh-letter-mode
416      . (lambda (&optional arg)
417          (interactive "P")
418          (write-region (point-min) (point-max)
419                        mime-editor/draft-file-name nil 'no-message)
420          (cond (arg
421                 (pop-to-buffer "MH mail delivery")
422                 (erase-buffer)
423                 (mh-exec-cmd-output mh-send-prog t "-watch" "-nopush"
424                                     "-nodraftfolder"
425                                     mh-send-args mime-editor/draft-file-name)
426                 (goto-char (point-max)) ; show the interesting part
427                 (recenter -1)
428                 (sit-for 1))
429                (t
430                 (apply 'mh-exec-cmd-quiet t mh-send-prog 
431                        (mh-list-to-string
432                         (list "-nopush" "-nodraftfolder"
433                               "-noverbose" "-nowatch"
434                               mh-send-args mime-editor/draft-file-name)))))
435          ))
436     ))
437
438 (defvar mime-editor/window-config-alist
439   '((mail-mode       . nil)
440     (mh-letter-mode  . mh-previous-window-config)
441     (news-reply-mode . (cond ((boundp 'gnus-winconf-post-news)
442                               (prog1
443                                   gnus-winconf-post-news
444                                 (setq gnus-winconf-post-news nil)
445                                 ))
446                              ((boundp 'gnus-prev-winconf)
447                               (prog1
448                                   gnus-prev-winconf
449                                 (setq gnus-prev-winconf nil)
450                                 ))
451                              ))
452     ))
453
454 (defvar mime-editor/news-reply-mode-server-running nil)
455
456
457 ;;; @@ about PGP
458 ;;;
459
460 (defvar mime-editor/signing-type nil
461   "*PGP signing type (pgp-elkins, pgp-kazu or nil). [mime-edit.el]")
462
463 (defvar mime-editor/encrypting-type nil
464   "*PGP encrypting type (pgp-elkins, pgp-kazu or nil). [mime-edit.el]")
465
466 (if (or mime-editor/signing-type mime-editor/encrypting-type)
467     (require 'mailcrypt)
468   )
469
470
471 ;;; @@ about tag
472 ;;;
473
474 (defconst mime-editor/single-part-tag-regexp
475   "--[[][[]\\([^]]*\\)]\\([[]\\([^]]*\\)]\\|\\)]"
476   "*Regexp of MIME tag in the form of [[CONTENT-TYPE][ENCODING]].")
477
478 (defconst mime-editor/quoted-single-part-tag-regexp
479   (concat "- " (substring mime-editor/single-part-tag-regexp 1)))
480
481 (defconst mime-editor/multipart-beginning-regexp "^--<<\\([^<>]+\\)>>-{\n")
482
483 (defconst mime-editor/multipart-end-regexp "^--}-<<\\([^<>]+\\)>>\n")
484
485 (defconst mime-editor/beginning-tag-regexp
486   (regexp-or mime-editor/single-part-tag-regexp
487              mime-editor/multipart-beginning-regexp))
488
489 (defconst mime-editor/end-tag-regexp
490   (regexp-or mime-editor/single-part-tag-regexp
491              mime-editor/multipart-end-regexp))
492
493 (defconst mime-editor/tag-regexp
494   (regexp-or mime-editor/single-part-tag-regexp
495              mime-editor/multipart-beginning-regexp
496              mime-editor/multipart-end-regexp))
497
498 (defvar mime-tag-format "--[[%s]]"
499   "*Control-string making a MIME tag.")
500
501 (defvar mime-tag-format-with-encoding "--[[%s][%s]]"
502   "*Control-string making a MIME tag with encoding.")
503
504 ;;; @@ multipart boundary
505 ;;;
506
507 (defvar mime-multipart-boundary "Multipart"
508   "*Boundary of a multipart message.")
509
510
511 ;;; @@ buffer local variables
512 ;;;
513
514 (defvar mime/editor-mode-old-local-map nil)
515 (defvar mime/editor-mode-old-selective-display nil)
516 (defvar mime/editing-buffer nil)
517
518 \f
519 ;;; @ constants
520 ;;;
521
522 (defconst mime-tspecials-regexp "[][()<>@,;:\\\"/?.= \t]"
523   "*Specify MIME tspecials.
524 Tspecials means any character that matches with it in header must be quoted.")
525
526 (defconst mime-editor/mime-version-value
527   (concat "1.0 (" mime-editor/version-name ")")
528   "MIME version number.")
529
530 (defconst mime-editor/mime-map (make-sparse-keymap)
531   "Keymap for MIME commands.")
532
533
534 ;;; @ keymap and menu
535 ;;;
536
537 (defvar mime/editor-mode-flag nil)
538 (make-variable-buffer-local 'mime/editor-mode-flag)
539
540 (set-alist 'minor-mode-alist
541            'mime/editor-mode-flag
542            '((" MIME-Edit "  mime-editor/transfer-level-string)))
543
544 (defun mime-editor/define-keymap (keymap)
545   "Add mime-editor commands to KEYMAP."
546   (if (not (keymapp keymap))
547       nil
548     (define-key keymap "\C-t" 'mime-editor/insert-text)
549     (define-key keymap "\C-i" 'mime-editor/insert-file)
550     (define-key keymap "\C-e" 'mime-editor/insert-external)
551     (define-key keymap "\C-v" 'mime-editor/insert-voice)
552     (define-key keymap "\C-y" 'mime-editor/insert-message)
553     (define-key keymap "\C-m" 'mime-editor/insert-mail)
554     (define-key keymap "\C-w" 'mime-editor/insert-signature)
555     (define-key keymap "\C-s" 'mime-editor/insert-signature)
556     (define-key keymap "\C-k" 'mime-editor/insert-key)
557     (define-key keymap "t"    'mime-editor/insert-tag)
558     (define-key keymap "a"    'mime-editor/enclose-alternative-region)
559     (define-key keymap "p"    'mime-editor/enclose-parallel-region)
560     (define-key keymap "m"    'mime-editor/enclose-mixed-region)
561     (define-key keymap "d"    'mime-editor/enclose-digest-region)
562     (define-key keymap "s"    'mime-editor/enclose-signed-region)
563     (define-key keymap "e"    'mime-editor/enclose-encrypted-region)
564     (define-key keymap "\C-p" 'mime-editor/preview-message)
565     (define-key keymap "\C-z" 'mime-editor/exit)
566     (define-key keymap "?"    'mime-editor/help)
567     ))
568
569 (mime-editor/define-keymap mime-editor/mime-map)
570
571 (defconst mime-editor/menu-title "MIME-Edit")
572
573 (defconst mime-editor/menu-list
574   '((mime-help  "Describe MIME editor mode" mime-editor/help)
575     (file       "Insert File"           mime-editor/insert-file)
576     (external   "Insert External"       mime-editor/insert-external)
577     (voice      "Insert Voice"          mime-editor/insert-voice)
578     (message    "Insert Message"        mime-editor/insert-message)
579     (mail       "Insert Mail"           mime-editor/insert-mail)
580     (signature  "Insert Signature"      mime-editor/insert-signature)
581     (text       "Insert Text"           mime-editor/insert-text)
582     (tag        "Insert Tag"            mime-editor/insert-tag)
583     (alternative "Enclose as alternative"
584                  mime-editor/enclose-alternative-region)
585     (parallel   "Enclose as parallel"   mime-editor/enclose-parallel-region)
586     (mixed      "Enclose as serial"     mime-editor/enclose-mixed-region)
587     (digest     "Enclose as digest"     mime-editor/enclose-digest-region)
588     (signed     "Enclose as signed"     mime-editor/enclose-signed-region)
589     (encrypted  "Enclose as encrypted"  mime-editor/enclose-encrypted-region)
590     (key        "Insert Public Key"     mime-editor/insert-key)
591     (split      "About split"           mime-editor/set-split)
592     (sign       "About sign"            mime-editor/set-sign)
593     (encrypt    "About encryption"      mime-editor/set-encrypt)
594     (preview    "Preview Message"       mime-editor/preview-message)
595     (level      "Toggle transfer-level" mime-editor/toggle-transfer-level)
596     )
597   "MIME-edit menubar entry.")
598
599 (defun mime-editor/define-menu-for-emacs19 ()
600   "Define menu for Emacs 19."
601   (define-key (current-local-map) [menu-bar mime-edit]
602     (cons mime-editor/menu-title
603           (make-sparse-keymap mime-editor/menu-title)))
604   (mapcar (function
605            (lambda (item)
606              (define-key (current-local-map)
607                (vector 'menu-bar 'mime-edit (car item))
608                (cons (nth 1 item)(nth 2 item))
609                )
610              ))
611           (reverse mime-editor/menu-list)
612           ))
613
614 ;;; modified by Pekka Marjola <pema@iki.fi>
615 ;;;     1995/9/5 (c.f. [tm-en:69])
616 (defun mime-editor/define-menu-for-xemacs ()
617   "Define menu for Emacs 19."
618   (cond ((featurep 'menubar)
619          (make-local-variable 'current-menubar)
620          (set-buffer-menubar current-menubar)
621          (add-submenu nil
622                       (cons mime-editor/menu-title
623                             (mapcar (function
624                                      (lambda (item)
625                                        (vector (nth 1 item)(nth 2 item)
626                                                mime/editor-mode-flag)
627                                        ))
628                                     mime-editor/menu-list)))
629          )))
630
631 ;;; modified by Steven L. Baur <steve@miranova.com>
632 ;;;     1995/12/6 (c.f. [tm-en:209])
633 (if (and running-xemacs (not (boundp 'mime-editor/popup-menu-for-xemacs)))
634     (setq mime-editor/popup-menu-for-xemacs
635           (append '("MIME Commands" "---")
636                   (mapcar (function (lambda (item)
637                                       (vector (nth 1 item)
638                                               (nth 2 item)
639                                               t)))
640                           mime-editor/menu-list)))
641   )
642 ;;; end
643
644
645 ;;; @ functions
646 ;;;
647
648 ;;;###autoload
649 (defun mime/editor-mode ()
650   "MIME minor mode for editing the tagged MIME message.
651
652 In this mode, basically, the message is composed in the tagged MIME
653 format.  The message tag looks like:
654
655         `--[[text/plain; charset=ISO-2022-JP][7bit]]'.
656
657 The tag specifies the MIME content type, subtype, optional parameters
658 and transfer encoding of the message following the tag.  Messages
659 without any tag are treated as `text/plain' by default.  Charset and
660 transfer encoding are automatically defined unless explicitly
661 specified.  Binary messages such as audio and image are usually hidden
662 using selective-display facility.  The messages in the tagged MIME
663 format are automatically translated into a MIME compliant message when
664 exiting this mode.
665
666 Available charsets depend on Emacs version being used.  The following
667 lists the available charsets of each emacs.
668
669 Emacs18:        US-ASCII is only available.
670 NEmacs:         US-ASCII and ISO-2022-JP are available.
671 Emacs19:        US-ASCII and ISO-8859-1 are available.
672 Mule:           US-ASCII, ISO-8859-* (except for ISO-8859-6),
673                 ISO-2022-JP, ISO-2022-JP-2 and ISO-2022-INT-1 are available.
674
675 ISO-2022-JP-2 and ISO-2022-INT-1 charsets used in Mule is expected to
676 be used to represent multilingual text in intermixed manner.  Any
677 languages that has no registered charset are represented as either
678 ISO-2022-JP-2 or ISO-2022-INT-1 in Mule.
679
680 Following commands are available in addition to major mode commands:
681 \\[mime-editor/insert-text]     insert a text message.
682 \\[mime-editor/insert-file]     insert a (binary) file.
683 \\[mime-editor/insert-external] insert a reference to external body.
684 \\[mime-editor/insert-voice]    insert a voice message.
685 \\[mime-editor/insert-message]  insert a mail or news message.
686 \\[mime-editor/insert-mail]     insert a mail message.
687 \\[mime-editor/insert-signature]        insert a signature file at end.
688 \\[mime-editor/insert-tag]      insert a new MIME tag.
689 \\[mime-editor/enclose-alternative-region]      enclose as multipart/alternative.
690 \\[mime-editor/enclose-parallel-region] enclose as multipart/parallel.
691 \\[mime-editor/enclose-mixed-region]    enclose as multipart/mixed.
692 \\[mime-editor/enclose-digest-region]   enclose as multipart/digest.
693 \\[mime-editor/enclose-signed-region]   enclose as PGP signed.
694 \\[mime-editor/enclose-encrypted-region]        enclose as PGP encrypted.
695 \\[mime-editor/insert-key]      insert PGP public key.
696 \\[mime-editor/preview-message] preview editing MIME message.
697 \\[mime-editor/exit]    exit and translate into a MIME compliant message.
698 \\[mime-editor/maybe-translate] exit and translate if in MIME mode, then split.
699 \\[mime-editor/help]    show this help.
700
701 Additional commands are available in some major modes:
702 C-c C-c         exit, translate and run the original command.
703 C-c C-s         exit, translate and run the original command.
704
705 The following is a message example written in the tagged MIME format.
706 TABs at the beginning of the line are not a part of the message:
707
708         This is a conventional plain text.  It should be translated
709         into text/plain.
710         --[[text/plain]]
711         This is also a plain text.  But, it is explicitly specified as
712         is.
713         --[[text/plain; charset=ISO-2022-JP]]
714         \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
715         \e$B%H$G$9\e(B.
716         --[[text/richtext]]
717         <center>This is a richtext.</center>
718         --[[image/gif][base64]]^M...image encoded in base64 here...
719         --[[audio/basic][base64]]^M...audio encoded in base64 here...
720
721 User customizable variables (not documented all of them):
722  mime-prefix
723     Specifies a key prefix for MIME minor mode commands.
724
725  mime-ignore-preceding-spaces
726     Preceding white spaces in a message body are ignored if non-nil.
727
728  mime-ignore-trailing-spaces
729     Trailing white spaces in a message body are ignored if non-nil.
730
731  mime-auto-fill-header
732     Fill header fields that contain encoded-words if non-nil.
733
734  mime-auto-hide-body
735     Hide a non-textual body message encoded in base64 after insertion
736     if non-nil.
737
738  mime-voice-recorder
739     Specifies a function to record a voice message and return a buffer
740     that contains it.  The function mime-voice-recorder-for-sun is for
741     Sun SparcStations.
742
743  mime/editor-mode-hook
744     Turning on MIME mode calls the value of mime/editor-mode-hook, if
745     it is non-nil.
746
747  mime-editor/translate-hook
748     The value of mime-editor/translate-hook is called just before translating
749     the tagged MIME format into a MIME compliant message if it is
750     non-nil.  If the hook call the function mime-editor/insert-signature,
751     the signature file will be inserted automatically.
752
753  mime-editor/exit-hook
754     Turning off MIME mode calls the value of mime-editor/exit-hook, if it is
755     non-nil."
756   (interactive)
757   (if mime/editor-mode-flag
758       (error "You are already editing a MIME message.")
759     (setq mime/editor-mode-flag t)
760     ;; Remember old key bindings.
761     (if running-xemacs
762         nil
763       (make-local-variable 'mime/editor-mode-old-local-map)
764       (setq mime/editor-mode-old-local-map (current-local-map))
765       ;; Add MIME commands to current local map.
766       (use-local-map (copy-keymap (current-local-map)))
767       )
768     (if (not (lookup-key (current-local-map) mime-prefix))
769         (define-key (current-local-map) mime-prefix mime-editor/mime-map))
770
771     ;; Set transfer level into mode line
772     ;;
773     (setq mime-editor/transfer-level-string
774           (mime/encoding-name mime-editor/transfer-level 'not-omit))
775     (force-mode-line-update)
776     
777     ;; Define menu.  Menus for other emacs implementations are
778     ;; welcome.
779     (cond (running-xemacs
780            (mime-editor/define-menu-for-xemacs))
781           ((>= emacs-major-version 19)
782            (mime-editor/define-menu-for-emacs19)
783            ))
784     ;; end
785     
786     ;; Remember old selective-display.
787     (make-local-variable 'mime/editor-mode-old-selective-display)
788     (setq mime/editor-mode-old-selective-display selective-display)
789     (setq selective-display t)
790     ;; I don't care about saving these.
791     (setq paragraph-start
792           (regexp-or mime-editor/single-part-tag-regexp
793                      paragraph-start))
794     (setq paragraph-separate
795           (regexp-or mime-editor/single-part-tag-regexp
796                      paragraph-separate))
797     (run-hooks 'mime/editor-mode-hook)
798     (message
799      (substitute-command-keys
800       "Type \\[mime-editor/exit] to exit MIME mode, and type \\[mime-editor/help] to get help."))
801     ))
802
803 ;;;###autoload
804 (defalias 'edit-mime 'mime/editor-mode)         ; for convenience
805 (defalias 'mime-mode 'mime/editor-mode)         ; for convenience
806
807 (defun mime-editor/exit (&optional nomime no-error)
808   "Translate the tagged MIME message into a MIME compliant message.
809 With no argument encode a message in the buffer into MIME, otherwise
810 just return to previous mode."
811   (interactive "P")
812   (if (not mime/editor-mode-flag)
813       (if (null no-error)
814           (error "You aren't editing a MIME message.")
815         )
816     (if (not nomime)
817         (progn
818           (run-hooks 'mime-editor/translate-hook)
819           (mime-editor/translate-buffer)))
820     ;; Restore previous state.
821     (setq mime/editor-mode-flag nil)
822     (cond (running-xemacs
823            ;; mime-prefix only defined if binding was nil
824            (if (eq (lookup-key (current-local-map) mime-prefix)
825                    mime-editor/mime-map)
826                (define-key (current-local-map) mime-prefix nil))
827            (delete-menu-item (list mime-editor/menu-title)))
828           (t
829            (use-local-map mime/editor-mode-old-local-map)))
830     
831     (setq selective-display mime/editor-mode-old-selective-display)
832     (set-buffer-modified-p (buffer-modified-p))
833     (run-hooks 'mime-editor/exit-hook)
834     (message "Exit MIME editor mode.")
835     ))
836
837 (defun mime-editor/maybe-translate ()
838   (interactive)
839   (mime-editor/exit nil t)
840   (call-interactively 'mime-editor/maybe-split-and-send)
841   )
842
843 (defun mime-editor/help ()
844   "Show help message about MIME mode."
845   (interactive)
846   (with-output-to-temp-buffer "*Help*"
847     (princ "MIME editor mode:\n")
848     (princ (documentation 'mime/editor-mode))
849     (print-help-return-message)))
850
851 (defun mime-editor/insert-text ()
852   "Insert a text message.
853 Charset is automatically obtained from the `mime/lc-charset-alist'."
854   (interactive)
855   (if (and (mime-editor/insert-tag "text" nil nil)
856            (looking-at mime-editor/single-part-tag-regexp))
857       (progn
858         ;; Make a space between the following message.
859         (insert "\n")
860         (forward-char -1)
861         )))
862
863 (defun mime-editor/insert-file (file)
864   "Insert a message from a file."
865   (interactive "fInsert file as MIME message: ")
866   (let*  ((guess (mime-find-file-type file))
867           (pritype (nth 0 guess))
868           (subtype (nth 1 guess))
869           (parameters (nth 2 guess))
870           (default (nth 3 guess))       ;Guess encoding from its file name.
871           (disposition-type (nth 4 guess))
872           (disposition-params (nth 5 guess))
873           (encoding
874            (if (not (interactive-p))
875                default
876              (completing-read
877               (concat "What transfer encoding"
878                       (if default
879                           (concat " (default "
880                                   (if (string-equal default "")
881                                       "\"\""
882                                     default)
883                                   ")"
884                                   ))
885                       ": ")
886               mime-encoding-method-alist nil t nil))))
887     (if (string-equal encoding "")
888         (setq encoding default))
889     (if (or (consp parameters) (stringp disposition-type))
890         (let ((rest parameters) cell attribute value)
891           (setq parameters "")
892           (while rest
893             (setq cell (car rest))
894             (setq attribute (car cell))
895             (setq value (cdr cell))
896             (if (eq value 'file)
897                 (setq value (rfc822/wrap-as-quoted-string
898                              (file-name-nondirectory file)))
899               )
900             (setq parameters (concat parameters "; " attribute "=" value))
901             (setq rest (cdr rest))
902             )
903           (if disposition-type
904               (progn
905                 (setq parameters
906                       (concat parameters "\n"
907                               "Content-Disposition: " disposition-type))
908                 (setq rest disposition-params)
909                 (while rest
910                   (setq cell (car rest))
911                   (setq attribute (car cell))
912                   (setq value (cdr cell))
913                   (if (eq value 'file)
914                       (setq value (rfc822/wrap-as-quoted-string
915                                    (file-name-nondirectory file)))
916                     )
917                   (setq parameters
918                         (concat parameters "; " attribute "=" value))
919                   (setq rest (cdr rest))
920                   )
921                 ))
922           ))
923     (mime-editor/insert-tag pritype subtype parameters)
924     (mime-editor/insert-binary-file file encoding)
925     ))
926
927 (defun mime-editor/insert-external ()
928   "Insert a reference to external body."
929   (interactive)
930   (mime-editor/insert-tag "message" "external-body" nil ";\n\t")
931   ;;(forward-char -1)
932   ;;(insert "Content-Description: " (read-string "Content-Description: ") "\n")
933   ;;(forward-line 1)
934   (let* ((pritype (mime-prompt-for-type))
935          (subtype (mime-prompt-for-subtype pritype))
936          (parameters (mime-prompt-for-parameters pritype subtype ";\n\t")))
937     (and pritype
938          subtype
939          (insert "Content-Type: "
940                  pritype "/" subtype (or parameters "") "\n")))
941   (if (and (not (eobp))
942            (not (looking-at mime-editor/single-part-tag-regexp)))
943       (insert (mime-make-text-tag) "\n")))
944
945 (defun mime-editor/insert-voice ()
946   "Insert a voice message."
947   (interactive)
948   (mime-editor/insert-tag "audio" "basic" nil)
949   (let ((buffer (funcall mime-voice-recorder)))
950     (unwind-protect
951         (mime-editor/insert-binary-buffer buffer "base64")
952       (kill-buffer buffer)
953       )))
954
955 (defun mime-editor/insert-signature (&optional arg)
956   "Insert a signature file."
957   (interactive "P")
958   (let ((signature-insert-hook
959          (function
960           (lambda ()
961             (apply (function mime-editor/insert-tag)
962                    (mime-find-file-type signature))
963             )))
964         )
965     (insert-signature arg)
966     ))
967
968 \f
969 ;; Insert a new tag around a point.
970
971 (defun mime-editor/insert-tag (&optional pritype subtype parameters delimiter)
972   "Insert new MIME tag and return a list of PRITYPE, SUBTYPE, and PARAMETERS.
973 If nothing is inserted, return nil."
974   (interactive)
975   (let ((oldtag nil)
976         (newtag nil)
977         (current (point))
978         exist-prev-tag exist-next-tag)
979     (setq pritype
980           (or pritype
981               (mime-prompt-for-type)))
982     (setq subtype
983           (or subtype
984               (mime-prompt-for-subtype pritype)))
985     (setq parameters
986           (or parameters
987               (mime-prompt-for-parameters pritype subtype delimiter)))
988     ;; Make a new MIME tag.
989     (setq newtag (mime-make-tag pritype subtype parameters))
990     ;; Find an current MIME tag.
991     (setq oldtag
992           (save-excursion
993             (if (mime-editor/goto-tag)
994                 (progn
995                   (if (eq current (match-beginning 0))
996                       (setq exist-next-tag t)
997                     (setq exist-prev-tag t)
998                     )
999                   (buffer-substring (match-beginning 0) (match-end 0))
1000                   )
1001               ;; Assume content type is 'text/plan'.
1002               (mime-make-tag "text" "plain")
1003               )))
1004     ;; We are only interested in TEXT.
1005     (if (and oldtag
1006              (not (mime-test-content-type
1007                    (mime-editor/get-contype oldtag) "text")))
1008         (setq oldtag nil))
1009     (cond (exist-prev-tag (insert "\n"))
1010           (exist-next-tag (save-excursion
1011                             (insert "\n")
1012                             )))
1013     (if (not (bolp))
1014         (if exist-prev-tag
1015             (forward-line 1)
1016           (insert "\n")
1017           ))
1018     ;; Make a new tag.
1019     (if (or (not oldtag)                ;Not text
1020             (or mime-ignore-same-text-tag
1021                 (not (string-equal oldtag newtag))))
1022         (progn
1023           ;; Mark the beginning of the tag for convenience.
1024           (push-mark (point) 'nomsg)
1025           (insert newtag "\n")
1026           (list pritype subtype parameters) ;New tag is created.
1027           )
1028       ;; Restore previous point.
1029       (goto-char current)
1030       nil                               ;Nothing is created.
1031       )
1032     ))
1033
1034 ;; Insert the binary content after MIME tag.
1035 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
1036 ;;      for x-uue
1037 (defun mime-editor/insert-binary-file (file &optional encoding)
1038   "Insert binary FILE at point.
1039 Optional argument ENCODING specifies an encoding method such as base64."
1040   (let ((tmpbuf (get-buffer-create " *MIME insert*")))
1041     (save-excursion
1042       (set-buffer tmpbuf)
1043       (erase-buffer)
1044       (let ((mc-flag nil)               ;Mule
1045             (file-coding-system-for-read
1046              (if (featurep 'mule) *noconv*))
1047             (kanji-flag nil)            ;NEmacs
1048             (emx-binary-mode t)         ;Stop CRLF to LF conversion in OS/2
1049             )
1050         (let (jka-compr-compression-info-list
1051               jam-zcat-filename-list)
1052           (insert-file-contents file))))
1053     (prog1
1054         (if (and (stringp encoding)
1055                  (string-equal (downcase encoding) "x-uue"))
1056             (progn
1057               (require 'mel-u)
1058               (let ((uuencode-external-encoder
1059                      (cons (car uuencode-external-encoder)
1060                            (list (file-name-nondirectory file))
1061                            )))
1062                 (mime-editor/insert-binary-buffer tmpbuf encoding)
1063                 ))
1064           (mime-editor/insert-binary-buffer tmpbuf encoding))
1065       (kill-buffer tmpbuf))))
1066
1067 ;; Insert the binary content after MIME tag.
1068 ;;      modified by MORITA Masahiro <hiro@isl.ntt.JP>
1069 ;;      for x-uue
1070 (defun mime-editor/insert-binary-buffer (buffer &optional encoding)
1071   "Insert binary BUFFER at point.
1072 Optional argument ENCODING specifies an encoding method such as base64."
1073   (let* ((tagend (1- (point)))          ;End of the tag
1074          (hide-p (and mime-auto-hide-body
1075                       (stringp encoding)
1076                       (let ((en (downcase encoding)))
1077                         (or (string-equal en "base64")
1078                             (string-equal en "x-uue")
1079                             ))))
1080          )
1081     (save-restriction
1082       (narrow-to-region (1- (point)) (point))
1083       (let ((start (point))
1084             (emx-binary-mode t))        ;Stop LF to CRLF conversion in OS/2
1085         (insert-buffer-substring buffer)
1086         ;; Encode binary message if necessary.
1087         (if encoding
1088             (mime-encode-region start (point-max) encoding)
1089           ))
1090       (if hide-p
1091           (progn
1092             (mime-flag-region (point-min) (1- (point-max)) ?\^M)
1093             (goto-char (point-max)))
1094         ))
1095     ;; Define encoding even if it is 7bit.
1096     (if (stringp encoding)
1097         (save-excursion
1098           (goto-char tagend)            ;Make sure which line the tag is on.
1099           (mime-editor/define-encoding encoding)))
1100     ))
1101
1102 \f
1103 ;; Commands work on a current message flagment.
1104
1105 (defun mime-editor/goto-tag ()
1106   "Search for the beginning of the tagged MIME message."
1107   (let ((current (point)) multipart)
1108     (if (looking-at mime-editor/tag-regexp)
1109         t
1110       ;; At first, go to the end.
1111       (cond ((re-search-forward mime-editor/beginning-tag-regexp nil t)
1112              (goto-char (1- (match-beginning 0))) ;For multiline tag
1113              )
1114             (t
1115              (goto-char (point-max))
1116              ))
1117       ;; Then search for the beginning. 
1118       (re-search-backward mime-editor/end-tag-regexp nil t)
1119       (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         (goto-char (mime-editor/content-end))
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 (%s)\n" mime-editor/version-name))
2339   (insert (format "\
2340 Content-Type: message/partial; id=%s; number=%d; total=%d\n%s\n"
2341                   id number total separator))
2342   )
2343
2344 (defun mime-editor/split-and-send
2345   (&optional cmd lines mime-editor/message-max-length)
2346   (interactive)
2347   (or lines
2348       (setq lines
2349             (count-lines (point-min) (point-max)))
2350       )
2351   (or mime-editor/message-max-length
2352       (setq mime-editor/message-max-length
2353             (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2354                 mime-editor/message-default-max-length))
2355       )
2356   (let* ((mime-editor/draft-file-name 
2357           (or (buffer-file-name)
2358               (make-temp-name
2359                (expand-file-name "tm-draft" mime/tmp-dir))))
2360          (separator mail-header-separator)
2361          (config
2362           (eval (cdr (assq major-mode mime-editor/window-config-alist))))
2363          (id (concat "\""
2364                      (replace-space-with-underline (current-time-string))
2365                      "@" (system-name) "\"")))
2366     (run-hooks 'mime-editor/before-split-hook)
2367     (let* ((header (rfc822/get-header-string-except
2368                     mime-editor/split-ignored-field-regexp separator))
2369            (subject (mail-fetch-field "subject"))
2370            (total (+ (/ lines mime-editor/message-max-length)
2371                      (if (> (mod lines mime-editor/message-max-length) 0)
2372                          1)))
2373            (the-buf (current-buffer))
2374            (buf (get-buffer "*tmp-send*"))
2375            (command
2376             (or cmd
2377                 (cdr
2378                  (assq major-mode
2379                        mime-editor/split-message-sender-alist))
2380                 (cdr
2381                  (assq major-mode
2382                        mime-editor/message-default-sender-alist))
2383                 ))
2384            data)
2385       (goto-char (point-min))
2386       (if (re-search-forward (concat "^" (regexp-quote separator) "$")
2387                              nil t)
2388           (replace-match "")
2389         )
2390       (if buf
2391           (progn
2392             (switch-to-buffer buf)
2393             (erase-buffer)
2394             (switch-to-buffer the-buf)
2395             )
2396         (setq buf (get-buffer-create "*tmp-send*"))
2397         )
2398       (switch-to-buffer buf)
2399       (make-local-variable 'mail-header-separator)
2400       (setq mail-header-separator separator)
2401       (switch-to-buffer the-buf)
2402       (goto-char (point-min))
2403       (re-search-forward "^$" nil t)
2404       (let ((mime-editor/partial-number 1))
2405         (setq data (buffer-substring
2406                     (point-min)
2407                     (progn
2408                       (goto-line mime-editor/message-max-length)
2409                       (point))
2410                     ))
2411         (delete-region (point-min)(point))
2412         (switch-to-buffer buf)
2413         (mime-editor/insert-partial-header
2414          header subject id mime-editor/partial-number total separator)
2415         (insert data)
2416         (save-excursion
2417           (save-restriction
2418             (goto-char (point-min))
2419             (search-forward (concat "\n" mail-header-separator "\n"))
2420             (narrow-to-region
2421              (match-end 0)
2422              (if (re-search-forward "^$" nil t)
2423                  (match-beginning 0)
2424                (point-max)
2425                ))
2426             (goto-char (point-min))
2427             (while (re-search-forward
2428                     mime-editor/split-blind-field-regexp nil t)
2429               (delete-region (match-beginning 0)
2430                              (let ((e (rfc822/field-end)))
2431                                (if (< e (point-max))
2432                                    (1+ e)
2433                                  e)))
2434               )
2435             ))
2436         (save-excursion
2437           (message (format "Sending %d/%d..."
2438                            mime-editor/partial-number total))
2439           (call-interactively command)
2440           (message (format "Sending %d/%d... done"
2441                            mime-editor/partial-number total))
2442           )
2443         (erase-buffer)
2444         (switch-to-buffer the-buf)
2445         (setq mime-editor/partial-number 2)
2446         (while (< mime-editor/partial-number total)
2447           (setq data (buffer-substring
2448                       (point-min)
2449                       (progn
2450                         (goto-line mime-editor/message-max-length)
2451                         (point))
2452                       ))
2453           (delete-region (point-min)(point))
2454           (switch-to-buffer buf)
2455           (mime-editor/insert-partial-header
2456            header subject id mime-editor/partial-number total separator)
2457           (insert data)
2458           (save-excursion
2459             (message (format "Sending %d/%d..."
2460                              mime-editor/partial-number total))
2461             (call-interactively command)
2462             (message (format "Sending %d/%d... done"
2463                              mime-editor/partial-number total))
2464             )
2465           (erase-buffer)
2466           (switch-to-buffer the-buf)
2467           (setq mime-editor/partial-number
2468                 (1+ mime-editor/partial-number))
2469           )
2470         (goto-char (point-min))
2471         (mime-editor/insert-partial-header
2472          header subject id mime-editor/partial-number total separator)
2473         (message (format "Sending %d/%d..."
2474                          mime-editor/partial-number total))
2475         ))))
2476
2477 (defun mime-editor/maybe-split-and-send (&optional cmd)
2478   (interactive)
2479   (run-hooks 'mime-editor/before-send-hook)
2480   (let ((mime-editor/message-max-length
2481          (or (cdr (assq major-mode mime-editor/message-max-length-alist))
2482              mime-editor/message-default-max-length))
2483         (lines (count-lines (point-min) (point-max)))
2484         )
2485     (if (and (> lines mime-editor/message-max-length)
2486              mime-editor/split-message)
2487         (mime-editor/split-and-send cmd lines mime-editor/message-max-length)
2488       )))
2489
2490
2491 ;;; @ preview message
2492 ;;;
2493
2494 (defun mime-editor/preview-message ()
2495   "preview editing MIME message. [mime-edit.el]"
2496   (interactive)
2497   (let* ((str (buffer-string))
2498          (separator mail-header-separator)
2499          (the-buf (current-buffer))
2500          (buf-name (buffer-name))
2501          (temp-buf-name (concat "*temp-article:" buf-name "*"))
2502          (buf (get-buffer temp-buf-name))
2503          )
2504     (if buf
2505         (progn
2506           (switch-to-buffer buf)
2507           (erase-buffer)
2508           )
2509       (setq buf (get-buffer-create temp-buf-name))
2510       (switch-to-buffer buf)
2511       )
2512     (insert str)
2513     (setq major-mode 'mime/temporary-message-mode)
2514     (make-local-variable 'mail-header-separator)
2515     (setq mail-header-separator separator)
2516     (make-local-variable 'mime/editing-buffer)
2517     (setq mime/editing-buffer the-buf)
2518     
2519     (run-hooks 'mime-editor/translate-hook)
2520     (mime-editor/translate-buffer)
2521     (goto-char (point-min))
2522     (if (re-search-forward
2523          (concat "^" (regexp-quote separator) "$"))
2524         (replace-match "")
2525       )
2526     (mime/viewer-mode)
2527     ))
2528
2529 (defun mime-editor/quitting-method ()
2530   (let ((temp mime::preview/article-buffer)
2531         buf)
2532     (mime-viewer/kill-buffer)
2533     (set-buffer temp)
2534     (setq buf mime/editing-buffer)
2535     (kill-buffer temp)
2536     (switch-to-buffer buf)
2537     ))
2538
2539 (set-alist 'mime-viewer/quitting-method-alist
2540            'mime/temporary-message-mode
2541            (function mime-editor/quitting-method)
2542            )
2543
2544
2545 ;;; @ draft preview
2546 ;;; 
2547 ;; by "OKABE Yasuo <okabe@kudpc.kyoto-u.ac.jp>
2548 ;;       Mon, 10 Apr 1995 20:03:07 +0900
2549
2550 (defvar mime-editor/draft-header-separator-alist
2551   '((news-reply-mode . mail-header-separator)
2552     (mh-letter-mode . mail-header-separator)
2553     ))
2554
2555 (defvar mime::article/draft-header-separator nil)
2556
2557 (defun mime-editor/draft-preview ()
2558   (interactive)
2559   (let ((sep (cdr (assq major-mode mime-editor/draft-header-separator-alist))))
2560     (or (stringp sep) (setq sep (eval sep)))
2561     (make-variable-buffer-local 'mime::article/draft-header-separator)
2562     (goto-char (point-min))
2563     (re-search-forward
2564      (concat "^\\(" (regexp-quote sep) "\\)?$"))
2565     (setq mime::article/draft-header-separator
2566           (buffer-substring (match-beginning 0) (match-end 0)))
2567     (replace-match "")
2568     (mime/viewer-mode (current-buffer))
2569     (pop-to-buffer (current-buffer))
2570     ))
2571
2572 (defun mime-viewer::quitting-method/draft-preview ()
2573   (let ((mother mime::preview/mother-buffer))
2574     (save-excursion
2575       (switch-to-buffer mother)
2576       (goto-char (point-min))
2577       (if (and
2578            (re-search-forward
2579             (concat "^\\("
2580                     (regexp-quote mime::article/draft-header-separator)
2581                     "\\)?$") nil t)
2582            (bolp))
2583           (progn
2584             (insert mime::article/draft-header-separator)
2585             (set-buffer-modified-p (buffer-modified-p))
2586             )))
2587     (mime-viewer/kill-buffer)
2588     (pop-to-buffer mother)
2589     ))
2590
2591 (set-alist 'mime-viewer/quitting-method-alist
2592            'mh-letter-mode
2593            (function mime-viewer::quitting-method/draft-preview)
2594            )
2595
2596 (set-alist 'mime-viewer/quitting-method-alist
2597            'news-reply-mode
2598            (function mime-viewer::quitting-method/draft-preview)
2599            )
2600
2601
2602 ;;; @ edit again
2603 ;;;
2604
2605 (defun mime-editor::edit-again (code-conversion)
2606   (save-excursion
2607     (goto-char (point-min))
2608     (let ((ctl (mime/Content-Type)))
2609       (if ctl
2610           (let ((ctype (car ctl))
2611                 (params (cdr ctl))
2612                 type stype)
2613             (if (string-match "/" ctype)
2614                 (progn
2615                   (setq type (substring ctype 0 (match-beginning 0)))
2616                   (setq stype (substring ctype (match-end 0)))
2617                   )
2618               (setq type ctype)
2619               )
2620             (cond
2621              ((string-equal type "multipart")
2622               (let ((boundary (assoc-value "boundary" params)))
2623                 (re-search-forward (concat "\n--" boundary) nil t)
2624                 (let ((bb (match-beginning 0)) eb tag)
2625                   (setq tag (format "\n--<<%s>>-{" stype))
2626                   (goto-char bb)
2627                   (insert tag)
2628                   (setq bb (+ bb (length tag)))
2629                   (re-search-forward (concat "\n--" boundary "--") nil t)
2630                   (setq eb (match-beginning 0))
2631                   (replace-match (format "\n--}-<<%s>>" stype))
2632                   (save-restriction
2633                     (narrow-to-region bb eb)
2634                     (goto-char (point-min))
2635                     (while (re-search-forward
2636                             (concat "\n--" boundary "\n") nil t)
2637                       (let ((beg (match-beginning 0))
2638                             end)
2639                         (delete-region beg (match-end 0))
2640                         (save-excursion
2641                           (if (re-search-forward
2642                                (concat "\n--" boundary) nil t)
2643                               (setq end (match-beginning 0))
2644                             (setq end (point-max))
2645                             )
2646                           (save-restriction
2647                             (narrow-to-region beg end)
2648                             (mime-editor::edit-again code-conversion)
2649                             (goto-char (point-max))
2650                             ))))
2651                     ))
2652                 (goto-char (point-min))
2653                 (or (= (point-min) 1)
2654                     (delete-region (point-min)
2655                                    (if (re-search-forward "^$" nil t)
2656                                        (match-end 0)
2657                                      (point-min)
2658                                      )))
2659                 ))
2660              (t
2661               (let* (charset
2662                      (pstr
2663                       (mapconcat (function
2664                                   (lambda (attr)
2665                                     (if (string-equal (car attr)
2666                                                       "charset")
2667                                         (progn
2668                                           (setq charset (cdr attr))
2669                                           "")
2670                                       (concat ";" (car attr)
2671                                               "=" (cdr attr))
2672                                       )
2673                                     ))
2674                                  params ""))
2675                      encoding
2676                      encoded)
2677                 (save-excursion
2678                   (if (re-search-forward
2679                        "Content-Transfer-Encoding:" nil t)
2680                       (let ((beg (match-beginning 0))
2681                             (hbeg (match-end 0))
2682                             (end (rfc822/field-end)))
2683                         (setq encoding
2684                               (eliminate-top-spaces
2685                                (rfc822/unfolding-string
2686                                 (buffer-substring hbeg end))))
2687                         (if (or charset (string-equal type "text"))
2688                             (progn
2689                               (delete-region beg (1+ end))
2690                               (goto-char (point-min))
2691                               (if (search-forward "\n\n" nil t)
2692                                   (progn
2693                                     (mime-decode-region
2694                                      (match-end 0)(point-max) encoding)
2695                                     (setq encoded t
2696                                           encoding nil)
2697                                     )))))))
2698                 (if (or code-conversion encoded)
2699                     (if charset
2700                         (mime-charset-decode-region (point-min)(point-max)
2701                                                     charset)
2702                       (character-decode-region (point-min)(point-max)
2703                                                mime/default-coding-system)
2704                       ))
2705                 (let ((he
2706                        (if (re-search-forward "^$" nil t)
2707                            (match-end 0)
2708                          (point-min)
2709                          )))
2710                   (if (= (point-min) 1)
2711                       (progn
2712                         (goto-char he)
2713                         (insert
2714                          (concat
2715                           "\n"
2716                           (mime-create-tag
2717                            (concat type "/" stype pstr) encoding)
2718                           ))
2719                         )
2720                     (delete-region (point-min) he)
2721                     (insert
2722                      (concat "\n"
2723                              (mime-create-tag
2724                               (concat type "/" stype pstr) encoding)
2725                              ))
2726                     ))
2727                 ))))
2728         (if code-conversion
2729             (character-decode-region (point-min) (point-max)
2730                                      mime/default-coding-system)
2731           )
2732         ))))
2733
2734 (defun mime/edit-again (&optional code-conversion no-separator no-mode)
2735   (interactive)
2736   (mime-editor::edit-again code-conversion)
2737   (goto-char (point-min))
2738   (save-restriction
2739     (narrow-to-region (point-min)
2740                       (if (re-search-forward "^$" nil t)
2741                           (match-end 0)
2742                         (point-max)
2743                         ))
2744     (goto-char (point-min))
2745     (while (re-search-forward
2746             "^\\(Content-.*\\|Mime-Version\\):" nil t)
2747       (delete-region (match-beginning 0) (1+ (rfc822/field-end)))
2748       ))
2749   (or no-separator
2750       (and (re-search-forward "^$")
2751            (replace-match mail-header-separator)
2752            ))
2753   (or no-mode
2754       (mime/editor-mode)
2755       ))
2756
2757
2758 ;;; @ end
2759 ;;;
2760
2761 (provide 'mime-edit)
2762
2763 (run-hooks 'mime-edit-load-hook)
2764
2765 ;;; mime-edit.el ends here