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